Merge branch 'master' into urlstate
[mkws-moved-to-github.git] / src / mkws-core.js
1 /*! MKWS, the MasterKey Widget Set.
2  *  Copyright (C) 2013-2015 Index Data
3  *  See the file LICENSE for details
4  */
5
6 "use strict";
7
8
9 // Set up global mkws object. Contains truly global state such as SP
10 // authentication, and a hash of team objects, indexed by team-name.
11 //
12 // We set it as a property of window to make the global explicit as
13 // some things complain about an implicit global.
14 window.mkws = {
15   $: $, // Our own local copy of the jQuery object
16   authenticated: false,
17   authenticating: false,
18   active: false,
19   logger: undefined,
20   log_level: "info",
21   teams: {},
22   widgetType2function: {},
23   defaultTemplates: {},
24
25   locale_lang: {
26     "de": {
27       "Authors": "Autoren",
28       "Subjects": "Schlagwörter",
29       "Sources": "Daten und Quellen",
30       "source": "datenquelle",
31       "Facets": "Termlisten",
32       "Next": "Weiter",
33       "Prev": "Zurück",
34       "Search": "Suche",
35       "Sort by": "Sortieren nach",
36       "and show": "und zeige",
37       "per page": "pro Seite",
38       "Displaying": "Zeige",
39       "to": "von",
40       "of": "aus",
41       "found": "gefunden",
42       "Title": "Titel",
43       "Author": "Autor",
44       "author": "autor",
45       "Date": "Datum",
46       "Subject": "Schlagwort",
47       "subject": "schlagwort",
48       "Location": "Ort",
49       "Records": "Datensätze",
50       "Targets": "Datenbanken",
51       "State": "Status",
52       "relevance": "Relevanz",
53       "title": "Titel",
54       "newest": "Neueste",
55       "oldest": "Älteste",
56
57       "dummy": "dummy"
58     },
59
60     "da": {
61       "Authors": "Forfattere",
62       "Subjects": "Emner",
63       "Sources": "Kilder",
64       "source": "kilder",
65       "Facets": "Termlists",
66       "Next": "Næste",
67       "Prev": "Forrige",
68       "Search": "Søg",
69       "Sort by": "Sorter efter",
70       "and show": "og vis",
71       "per page": "per side",
72       "Displaying": "Viser",
73       "to": "til",
74       "of": "ud af",
75       "found": "fandt",
76       "Title": "Title",
77       "Author": "Forfatter",
78       "author": "forfatter",
79       "Date": "Dato",
80       "Subject": "Emneord",
81       "subject": "emneord",
82       "Location": "Lokation",
83       "Records": "Poster",
84       "Targets": "Baser",
85       "State": "Status",
86       "relevance": "Relevans",
87       "title": "Titel",
88       "newest": "Nyeste",
89       "oldest": "Ældste",
90
91       "dummy": "dummy"
92     }
93   }
94 };
95
96 // We may be using a separate copy
97 if (typeof(mkws_jQuery) !== "undefined") {
98   mkws.$ = mkws_jQuery;
99 } else {
100   mkws.$ = jQuery;
101 }
102
103 // It's ridiculous that JSNLog doesn't provide this
104 mkws.stringToLevel = function(s) {
105   if (s === 'trace') {
106     return JL.getTraceLevel();
107   } else if (s === 'debug') {
108     return JL.getDebugLevel();
109   } else if (s === 'info') {
110     return JL.getInfoLevel();
111   } else if (s === 'warn') {
112     return JL.getWarnLevel();
113   } else if (s === 'error') {
114     return JL.getErrorLevel();
115   } else if (s === 'fatal') {
116     return JL.getFatalLevel();
117   } else {
118     throw "bad log-level '" + s + "'";
119   }
120 }
121
122 mkws.logger = JL('mkws');
123 var consoleAppender = JL.createConsoleAppender('consoleAppender');
124 mkws.logger.setOptions({ "appenders": [consoleAppender] });
125
126
127 function _log() {
128   var argsAsARealArray = Array.prototype.slice.call(arguments);
129   var fn = argsAsARealArray.shift();
130   fn.apply(mkws.logger, argsAsARealArray);
131 };
132 mkws.trace = function(x) { _log(mkws.logger.trace, x) };
133 mkws.debug = function(x) { _log(mkws.logger.debug, x) };
134 mkws.info = function(x) { _log(mkws.logger.info, x) };
135 mkws.warn = function(x) { _log(mkws.logger.warn, x) };
136 mkws.error = function(x) { _log(mkws.logger.error, x) };
137 mkws.fatal = function(x) { _log(mkws.logger.fatal, x) };
138
139
140 // Translation function.
141 mkws.M = function(word) {
142   var lang = mkws.config.lang;
143
144   if (!lang || !mkws.locale_lang[lang])
145     return word;
146
147   return mkws.locale_lang[lang][word] || word;
148 };
149
150
151 // This function is taken from a StackOverflow answer
152 // http://stackoverflow.com/questions/901115/how-can-i-get-query-string-values-in-javascript/901144#901144
153 mkws.getParameterByName = function(name, url) {
154   if (!url) url = location.search;
155   name = name.replace(/[\[]/, "\\[").replace(/[\]]/, "\\]");
156   var regex = new RegExp("[\\?&]" + name + "=([^&#]*)"),
157   results = regex.exec(url);
158   return results == null ? "" : decodeURIComponent(results[1].replace(/\+/g, " "));
159 }
160
161
162 mkws.registerWidgetType = function(name, fn) {
163   if(mkws._old2new.hasOwnProperty(name)) {
164       mkws.warn("registerWidgetType old widget name: " + name + " => " + mkws._old2new[name]);
165       name = mkws._old2new[name];
166   }
167
168   mkws.widgetType2function[name] = fn;
169   mkws.info("registered widget-type '" + name + "'");
170 };
171
172 mkws.aliasWidgetType = function(newName, oldName) {
173   mkws.widgetType2function[newName] = mkws.widgetType2function[oldName];
174   mkws.info("aliased widget-type '" + newName + "' to '" + oldName + "'");
175
176 };
177
178 mkws.promotionFunction = function(name) {
179   return mkws.widgetType2function[name];
180 };
181
182
183 mkws.setMkwsConfig = function(overrides) {
184   var config_default = {
185     use_service_proxy: true,
186     pazpar2_url: undefined,
187     pp2_hostname: "sp-mkws.indexdata.com",
188     pp2_path: "service-proxy/",
189     service_proxy_auth: undefined,
190     sp_auth_path: undefined,
191     sp_auth_query: "command=auth&action=perconfig",
192     sp_auth_credentials: undefined,
193     lang: "",
194     sort_options: [["relevance"], ["title:1", "title"], ["date:0", "newest"], ["date:1", "oldest"]],
195     perpage_options: [10, 20, 30, 50],
196     sort_default: "relevance",
197     perpage_default: 20,
198     show_lang: true,    /* show/hide language menu */
199     show_sort: true,    /* show/hide sort menu */
200     show_perpage: true, /* show/hide perpage menu */
201     show_switch: true,  /* show/hide switch menu */
202     lang_options: [],   /* display languages links for given languages, [] for all */
203     facets: ["xtargets", "subject", "author"], /* display facets, in this order, [] for none */
204     responsive_design_width: undefined, /* a page with less pixel width considered as narrow */
205     log_level: 1,     /* log level for development: 0..2 */
206     template_vars: {}, /* values that may be exposed to templates */
207
208     dummy: "dummy"
209   };
210
211   mkws.config = mkws.objectInheritingFrom(config_default);
212   for (var k in overrides) {
213     mkws.config[k] = overrides[k];
214   }
215 };
216
217
218 // This code is from Douglas Crockford's article "Prototypal Inheritance in JavaScript"
219 // http://javascript.crockford.com/prototypal.html
220 // mkws.objectInheritingFrom behaves the same as Object.create,
221 // but since the latter is not available in IE8 we can't use it.
222 //
223 mkws.objectInheritingFrom = function(o) {
224   function F() {}
225   F.prototype = o;
226   return new F();
227 }
228
229
230 // The following functions are dispatchers for team methods that
231 // are called from the UI using a team-name rather than implicit
232 // context.
233 mkws.switchView = function(tname, view) {
234   mkws.teams[tname].switchView(view);
235 };
236
237 mkws.showDetails = function(tname, prefixRecId) {
238   mkws.teams[tname].showDetails(prefixRecId);
239 };
240
241 mkws.limitCategory  = function(tname, id) {
242   mkws.teams[tname].limitCategory(id);
243 };
244
245 mkws.delimitTarget = function(tname, id) {
246   mkws.teams[tname].delimitTarget(id);
247 };
248
249 mkws.delimitQuery = function(tname, field, value) {
250   mkws.teams[tname].delimitQuery(field, value);
251 };
252
253 mkws.showPage = function(tname, pageNum) {
254   mkws.teams[tname].showPage(pageNum);
255 };
256
257 mkws.pagerPrev = function(tname) {
258   mkws.teams[tname].pagerPrev();
259 };
260
261 mkws.pagerNext = function(tname) {
262   mkws.teams[tname].pagerNext();
263 };
264
265
266 mkws.pazpar2_url = function() {
267   if (mkws.config.pazpar2_url) {
268     mkws.info("using pre-baked pazpar2_url '" + mkws.config.pazpar2_url + "'");
269     return mkws.config.pazpar2_url;
270   } else {
271     var s = document.location.protocol + "//" + mkws.config.pp2_hostname + "/" + mkws.config.pp2_path;
272     mkws.info("generated pazpar2_url '" + s + "'");
273     return s;
274   }
275 };
276
277
278 // We put a session token in window.name, as it's the only place to
279 // keep data that is preserved across reloads and within-site
280 // navigation. pz2.js picks this up and uses it as part of the
281 // cookie-name, to ensure we get a new session when we need one.
282 //
283 // We want to use different sessions for different windows/tabs (so
284 // they don't receive each other's messages), different hosts and
285 // different paths on a host (since in general these will
286 // authenticate as different libraries). So the window name needs to
287 // include the hostname and the path from the URL, plus the token.
288 //
289 var token;
290 if (window.name) {
291   token = window.name.replace(/.*\//, '');
292   mkws.debug("Reusing existing window token '" + token + "'");
293 } else {
294   // Incredible that the standard JavaScript runtime doesn't define a
295   // unique windowId. Instead, we have to make one up. And since there's
296   // no global area shared between windows, the best we can do for
297   // ensuring uniqueness is generating a random ID and crossing our
298   // fingers.
299   //
300   // Ten chars from 26 alpha-numerics = 36^10 = 3.65e15 combinations.
301   // At one per second, it will take 116 million years to duplicate a token
302   token = Math.random().toString(36).slice(2, 12);
303   mkws.debug("Generated new window token '" + token + "'");
304 }
305
306 window.name = window.location.hostname + window.location.pathname + '/' + token;
307 mkws.info("Using window.name '" + window.name + "'");
308
309
310 // wrapper to provide local copy of the jQuery object.
311 (function($) {
312   var _old2new = { // Maps old-style widget names to new-style
313     'Authname': 'auth-name',
314     'ConsoleBuilder': 'console-builder',
315     'Coverart': 'cover-art',
316     'GoogleImage': 'google-image',
317     'MOTD': 'motd',
318     'MOTDContainer': 'motd-container',
319     'Perpage': 'per-page',
320     'SearchForm': 'search-form',
321     'ReferenceUniverse': 'reference-universe',
322     'Termlists': 'facets'
323   };
324   // Annoyingly, there is no built-in way to invert a hash
325   var _new2old = {};
326   for (var key in _old2new) {
327     if(_old2new.hasOwnProperty(key)) {
328       _new2old[_old2new[key]] = key;
329     }
330   }
331
332   mkws._old2new = _old2new;
333
334   function handleNodeWithTeam(node, callback) {
335     // First branch for DOM objects; second branch for jQuery objects
336     var classes = node.className || node.attr('class');
337     if (!classes) {
338       // For some reason, if we try to proceed when classes is
339       // undefined, we don't get an error message, but this
340       // function and its callers, up several stack level,
341       // silently return. What a crock.
342       mkws.fatal("handleNodeWithTeam() called on node with no classes");
343       return;
344     }
345     var list = classes.split(/\s+/)
346     var teamName, type;
347
348     for (var i = 0; i < list.length; i++) {
349       var cname = list[i];
350       if (cname.match(/^mkws-team-/)) {
351         // New-style teamnames of the form mkws-team-xyz
352         teamName = cname.replace(/^mkws-team-/, '');
353       } else if (cname.match(/^mkwsTeam_/)) {
354         // Old-style teamnames of the form mkwsTeam_xyz
355         teamName = cname.replace(/^mkwsTeam_/, '');
356       } else if (cname.match(/^mkws-/)) {
357         // New-style names of the from mkws-foo-bar
358         type = cname.replace(/^mkws-/, '');
359       } else if (cname.match(/^mkws/)) {
360         // Old-style names of the form mkwsFooBar
361         var tmp = cname.replace(/^mkws/, '');
362         type = _old2new[tmp] || tmp.toLowerCase();
363       }
364     }
365
366     // Widgets without a team are on team "AUTO"
367     if (!teamName) {
368       teamName = "AUTO";
369       // Autosearch widgets don't join team AUTO if there is already an
370       // autosearch on the team or the team has otherwise gotten a query
371       if (node.getAttribute("autosearch")) {
372         if (mkws.autoHasAuto ||
373             mkws.teams["AUTO"] && mkws.teams["AUTO"].config["query"]) {
374           mkws.warn("AUTO team already has a query, using unique team");
375           teamName = "UNIQUE";
376         }
377         mkws.autoHasAuto = true;
378       }
379     }
380
381     // Widgets on team "UNIQUE" get a random team
382     if (teamName === "UNIQUE") {
383       teamName = Math.floor(Math.random() * 100000000).toString();
384     }
385
386     callback.call(node, teamName, type);
387   }
388
389
390   function resizePage() {
391     var threshhold = mkws.config.responsive_design_width;
392     var width = $(window).width();
393     var from, to, method;
394
395     if ((mkws.width === undefined || mkws.width > threshhold) &&
396         width <= threshhold) {
397       from = "wide"; to = "narrow"; method = "hide";
398     } else if ((mkws.width === undefined || mkws.width <= threshhold) &&
399                width > threshhold) {
400       from = "narrow"; to = "wide"; method = "show";
401     }
402     mkws.width = width;
403
404     if (from) {
405       mkws.info("changing from " + from + " to " + to + ": " + width);
406       for (var tname in mkws.teams) {
407         var team = mkws.teams[tname];
408         team.visitWidgets(function(t, w) {
409           var w1 = team.widget(t + "-container-" + from);
410           var w2 = team.widget(t + "-container-" + to);
411           if (w1) {
412             w1.node.hide();
413           }
414           if (w2) {
415             w2.node.show();
416             w.node.appendTo(w2.node);
417           }
418         });
419         team.queue("resize-" + to).publish();
420       }
421     }
422   };
423
424
425   /*
426    * Run service-proxy authentication in background (after page load).
427    * The username/password is configured in the apache config file
428    * for the site.
429    */
430   function authenticateSession(auth_url, auth_domain, pp2_url) {
431     mkws.authenticating = true;
432     mkws.info("service proxy authentication on URL: " + auth_url);
433
434     if (!auth_domain) {
435       auth_domain = pp2_url.replace(/^(https?:)?\/\/(.*?)\/.*/, '$2');
436       mkws.info("guessed auth_domain '" + auth_domain + "' from pp2_url '" + pp2_url + "'");
437     }
438
439     var request = new pzHttpRequest(auth_url, function(err) {
440       alert("HTTP call for authentication failed: " + err)
441       return;
442     }, auth_domain);
443
444     request.get(null, function(data) {
445       mkws.authenticating = false;
446       if (!$.isXMLDoc(data)) {
447         alert("Service Proxy authentication response is not a valid XML document");
448         return;
449       }
450       var status = $(data).find("status");
451       if (status.text() != "OK") {
452         var message = $(data).find("message");
453         alert("Service Proxy authentication response: " + status.text() + " (" + message.text() + ")");
454         return;
455       }
456
457       mkws.info("service proxy authentication successful");
458       mkws.authenticated = true;
459       var authName = $(data).find("displayName").text();
460       // You'd think there would be a better way to do this:
461       var realm = $(data).find("realm:not(realmAttributes realm)").text();
462       for (var teamName in mkws.teams) {
463         mkws.teams[teamName].queue("authenticated").publish(authName, realm);
464       }
465
466       runAutoSearches();
467     });
468   }
469
470
471   function runAutoSearches() {
472     mkws.info("running auto searches");
473
474     for (var teamName in mkws.teams) {
475       mkws.teams[teamName].queue("ready").publish();
476     }
477   }
478
479
480   function selectorForAllWidgets() {
481     if (mkws.config && mkws.config.scan_all_nodes) {
482       // This is the old version, which works by telling jQuery to
483       // find every node that has a class beginning with "mkws". In
484       // theory it should be slower than the class-based selector; but
485       // instrumentation suprisingly shows this is consistently
486       // faster. It also has the advantage that any widgets of
487       // non-registered types are logged as warnings rather than
488       // silently ignored.
489       return '[class^="mkws"],[class*=" mkws"]';
490     } else {
491       // This is the new version, which works by looking up the
492       // specific classes of all registered widget types and their
493       // resize containers. Because all it requires jQuery to do is
494       // some hash lookups in pre-built tables, it should be very
495       // fast; but it silently ignores widgets of unregistered types.
496       var s = "";
497       for (var type in mkws.widgetType2function) {
498         if (s) s += ',';
499         s += '.mkws-' + type;
500         s += ',.mkws-' + type + "-container-wide";
501         s += ',.mkws-' + type + "-container-narrow";
502         // Annoyingly, we also need to recognise old-style names
503         var oldtype = _new2old[type] || type.charAt(0).toUpperCase() + type.slice(1);
504         s += ',.mkws' + oldtype;
505         s += ',.mkws' + oldtype + "-Container-wide";
506         s += ',.mkws' + oldtype + "-Container-narrow";
507       }
508       return s;
509     }
510   }
511
512
513   function makeWidgetsWithin(level, node) {
514     if (node) var widgetNodes = node.find(selectorForAllWidgets());
515     else widgetNodes = $(selectorForAllWidgets());
516     // Return false if we parse no widgets
517     if (widgetNodes.length < 1) return false;
518     widgetNodes.each(function() {
519       handleNodeWithTeam(this, function(tname, type) {
520         var myTeam = mkws.teams[tname];
521         if (!myTeam) {
522           myTeam = mkws.teams[tname] = mkws.makeTeam($, tname);
523         }
524
525         var oldHTML = this.innerHTML;
526         var myWidget = mkws.makeWidget($, myTeam, type, this);
527         myTeam.addWidget(myWidget);
528         var newHTML = this.innerHTML;
529         if (newHTML !== oldHTML) {
530           myTeam.info("widget " + type + " HTML changed: reparsing");
531           makeWidgetsWithin(level+1, $(this));
532         }
533       });
534     });
535     return true;
536   }
537
538
539   // The second "rootsel" parameter is passed to jQuery and is a DOM node
540   // or a selector string you would like to constrain the search for widgets to.
541   //
542   // This function has no side effects if run again on an operating session,
543   // even if the element/selector passed causes existing widgets to be reparsed:
544   //
545   // (TODO: that last bit isn't true and we currently have to avoid reinitialising
546   // widgets, MKWS-261)
547   //
548   // * configuration is not regenerated
549   // * authentication is not performed again
550   // * autosearches are not re-run
551   mkws.init = function(message, rootsel) {
552     var greet = "MKWS initialised";
553     if (rootsel) greet += " (limited to " + rootsel + ")"
554     if (message) greet += " :: " + message;
555     mkws.info(greet);
556
557     // MKWS is not active until init() has been run against an object with widget nodes.
558     // We only set initial configuration when MKWS is first activated.
559     if (!mkws.isActive) {
560       var widgetSelector = selectorForAllWidgets();
561       if ($(widgetSelector).length < 1) {
562         mkws.warn("no widgets found");
563         return;
564       }
565
566       // Initial configuration
567       mkws.autoHasAuto = false;
568       var saved_config;
569       if (typeof mkws_config === 'undefined') {
570         mkws.info("setting empty config");
571         saved_config = {};
572       } else {
573         mkws.info("using config: " + $.toJSON(mkws_config));
574         saved_config = mkws_config;
575       }
576       mkws.setMkwsConfig(saved_config);
577
578       for (var key in mkws.config) {
579         if (mkws.config.hasOwnProperty(key)) {
580           if (key.match(/^language_/)) {
581             var lang = key.replace(/^language_/, "");
582             // Copy custom languages into list
583             mkws.locale_lang[lang] = mkws.config[key];
584             mkws.info("added locally configured language '" + lang + "'");
585           }
586         }
587       }
588
589       var lang = mkws.getParameterByName("lang") || mkws.config.lang;
590       if (!lang || !mkws.locale_lang[lang]) {
591         mkws.config.lang = ""
592       } else {
593         mkws.config.lang = lang;
594       }
595
596       mkws.info("using language: " + (mkws.config.lang ? mkws.config.lang : "none"));
597
598       // protocol independent link for pazpar2: "//mkws/sp" -> "https://mkws/sp"
599       if (mkws.pazpar2_url().match(/^\/\//)) {
600         mkws.config.pazpar2_url = document.location.protocol + mkws.config.pazpar2_url;
601         mkws.info("adjusted protocol independent link to " + mkws.pazpar2_url());
602       }
603
604       if (mkws.config.responsive_design_width) {
605         // Responsive web design - change layout on the fly based on
606         // current screen width. Required for mobile devices.
607         $(window).resize(resizePage);
608         // initial check after page load
609         $(document).ready(resizePage);
610       }
611     }
612
613     var then = $.now();
614     // If we've made no widgets, return without starting an SP session
615     // or marking MKWS active.
616     if (makeWidgetsWithin(1, rootsel ? $(rootsel) : undefined) === false) {
617       return false;
618     }
619     var now = $.now();
620
621     mkws.info("walking MKWS nodes took " + (now-then) + " ms");
622     for (var tName in mkws.teams) {
623       var myTeam = mkws.teams[tName]
624       myTeam.makePz2();
625       myTeam.info("made PZ2 object");
626     }
627
628     function sp_auth_url(config) {
629       if (config.service_proxy_auth) {
630         mkws.info("using pre-baked sp_auth_url '" + config.service_proxy_auth + "'");
631         return config.service_proxy_auth;
632       } else {
633         var s = '//';
634         s += config.sp_auth_hostname ? config.sp_auth_hostname : config.pp2_hostname;
635         s += '/';
636         s += config.sp_auth_path ? config.sp_auth_path : config.pp2_path;
637         var q = config.sp_auth_query;
638         if (q) {
639           s += '?' + q;
640         }
641         var c = config.sp_auth_credentials;
642         if (c) {
643           s += ('&username=' + c.substr(0, c.indexOf('/')) +
644                 '&password=' + c.substr(c.indexOf('/')+1));
645         }
646         mkws.info("generated sp_auth_url '" + s + "'");
647         return s;
648       }
649     }
650
651     if (mkws.config.use_service_proxy && !mkws.authenticated && !mkws.authenticating) {
652       authenticateSession(sp_auth_url(mkws.config),
653                           mkws.config.service_proxy_auth_domain,
654                           mkws.pazpar2_url());
655     } else if (!mkws.authenticating) {
656       // raw pp2 or we have a session already open
657       runAutoSearches();
658       for (var teamName in mkws.teams) {
659         mkws.teams[teamName].queue("authenticated").publish();
660       }
661     }
662
663     mkws.isActive = true;
664     return true;
665   };
666
667   $(document).ready(function() {
668     if (!window.mkws_noready && !mkws.authenticating && !mkws.active) {
669        mkws.init();
670     }
671   });
672
673   // Set global log_level flag early so that _log() works
674   if (typeof mkws_config !== 'undefined') {
675     var tmp = mkws_config.log_level;
676     if (typeof tmp !== 'undefined') {
677       mkws.logger.setOptions({ "level": mkws.stringToLevel(tmp) });
678     }
679   }
680
681   // This function is adapted from Yarin's code at
682   // https://stackoverflow.com/questions/4197591/parsing-url-hash-fragment-identifier-with-javascript#4198132
683   function parse_fragment(s) {
684     var hashParams = {};
685     var e,
686         a = /\+/g,  // Regex for replacing addition symbol with a space
687         r = /([^&;=]+)=?([^&;]*)/g,
688         d = function (s) { return decodeURIComponent(s.replace(a, " ")); },
689         q = s.substring(1);
690
691     while (e = r.exec(q)) {
692       var key = d(e[1]);
693       if (key === 'mkws') {
694         key = 'AUTO';
695       } else {
696         key = key.replace('mkws', '');
697       }
698       var team = mkws.teams[key];
699       if (team) {
700         hashParams[key] = team.parseFragment(d(e[2]));
701       } else {
702         alert("can't resolve team name '" + key + "'");
703       }
704     }
705
706     return hashParams;
707   }
708
709   var oldHash = location.hash;
710   $(window).bind('hashchange', function(e) {
711     mkws.warn("hashchange: old='" + oldHash + "', new='" + location.hash + "'");
712     var oldStates = parse_fragment(oldHash);
713     var newStates = parse_fragment(location.hash);
714     oldHash = location.hash;
715
716     for (var teamName in newStates) {
717       var team = mkws.teams[teamName];
718       if (!team) {
719         alert("can't resolve team name '" + teamName + "'");
720         continue;
721       }
722
723       team.handleChanges(oldStates[teamName], newStates[teamName]);
724     }
725   });
726 })(mkws.$);