Merge branch 'master' into urlstate
[mkws-moved-to-github.git] / src / mkws-widget-main.js
1 (function($) { // jQuery wrapper
2
3 // Functions follow for promoting the regular widget object into
4 // widgets of specific types. These could be moved into their own
5 // source files.
6
7
8 mkws.registerWidgetType('targets', function() {
9   if (!this.config.show_switch) return;
10   var that = this;
11
12   this.node.html('No information available yet.');
13   this.node.css("display", "none");
14
15   this.team.queue("targets").subscribe(function(data) {
16     // There is a bug in pz2.js wherein it makes each data object an array but
17     // simply assigns properties to it.
18     // TODO: remove this when PAZ-946 is addressed.
19     var cleandata = [];
20     for (var i = 0; i < data.length; i++) {
21       var cur = {};
22       cur.name = data[i].name;
23       cur.id = data[i].id;
24       cur.hits = data[i].hits;
25       cur.diagnostic = data[i].diagnostic;
26       cur.message = data[i].message;
27       cur.records = data[i].records;
28       cur.state = data[i].state.replace(/^Client_/, '');
29       cleandata.push(cur);
30     }
31
32     cleandata.sort(function(a,b) { return a.name.localeCompare(b.name) });
33
34     var template = that.team.loadTemplate(that.config.template || "targets");
35     that.node.html(template({data: cleandata}));
36   });
37 });
38
39
40 mkws.registerWidgetType('stat', function() {
41   var that = this;
42   this.team.queue("stat").subscribe(function(data) {
43     var template = that.team.loadTemplate(that.config.template || "stat");
44     that.node.html(template(data));
45   });
46 });
47
48
49 mkws.registerWidgetType('pager', function() {
50   var that = this;
51   var M = mkws.M;
52
53   this.team.queue("pager").subscribe(function(data) {
54     var teamName = that.team.name();
55     var output = {};
56     output.first = data.start + 1;
57     output.last = data.start + data.num;
58     output.count = data.merged;
59     output.found = data.total;
60
61     //client indexes pages from 1 but pz2 from 0
62     var onsides = 5;
63     var pages = Math.ceil(that.team.totalRecordCount() / that.team.perpage());
64     var currentPage = that.team.currentPage();
65
66     var firstClkbl = (currentPage - onsides > 0)
67       ? currentPage - onsides
68       : 1;
69     var lastClkbl = firstClkbl + 2*onsides < pages
70       ? firstClkbl + 2*onsides
71       : pages;
72
73     if (firstClkbl > 1) output.morePrev = true;
74     if (lastClkbl < pages) output.moreNext = true;
75
76     if (currentPage > 1) output.prevHref = '#' + that.team.urlFragment({ page: currentPage-1 });
77
78     output.pages = [];
79     for(var i = firstClkbl; i <= lastClkbl; i++) {
80       var o = {};
81       o.number = i;
82       if (i !== currentPage) {
83         o.href = '#' + that.team.urlFragment({ page: i });
84       }
85       output.pages.push(o);
86     }
87
88     if (pages - currentPage > 0) output.nextHref = '#' + that.team.urlFragment({ page: currentPage+1 });
89
90     var template = that.team.loadTemplate(that.config.template || "pager");
91     that.node.html(template(output));
92   });
93 });
94
95 mkws.registerWidgetType('details', function() {
96   var that = this;
97   var recid = that.node.attr("data-mkws-recid");
98   if (this.team.gotRecords()) { 
99     that.team.fetchDetails(recid);
100   } else {
101     this.team.queue("firstrecords").subscribe(function() {
102       that.team.fetchDetails(recid);
103     });
104   }
105   this.team.queue("record").subscribe(function(data) {
106     if ($.inArray(recid, data.recid) > -1) {
107       var template = that.team.loadTemplate(that.config.template || "details");
108       that.node.html(template(data));
109     }
110   });
111 });
112
113 mkws.registerWidgetType('records', function() {
114   var that = this;
115   var team = this.team;
116
117   this.team.queue("searchtriggered").subscribe(function() {
118     var op = that.config.newsearch_opacity;
119     if (op !== undefined) { that.node.fadeTo(500, op); }
120   });
121
122   var m_dataToRedraw = null;
123   function refreshRecordData() {
124     that.node.stop();
125     that.node.css('opacity', 1);
126
127     if (m_dataToRedraw) {
128       for (var i = 0; i < m_dataToRedraw.hits.length; i++) {
129         var hit = m_dataToRedraw.hits[i];
130         hit.detailLinkId = team.recordElementId(hit.recid[0]);
131         hit.detailClick = "mkws.showDetails('" + team.name() + "', '" + hit.recid[0] + "');return false;";
132         hit.containerClass = "mkws-summary mkwsSummary mkws-team-" + team.name();
133         hit.containerClass += " " + hit.detailLinkId;
134         // ### At some point, we may be able to move the
135         // m_currentRecordId and m_currentRecordData members
136         // from the team object into this widget.
137         if (hit.recid == team.currentRecordId()) {
138           if (team.currentRecordData()) {
139             hit.renderedDetails = team.renderDetails(team.currentRecordData());
140           } 
141         }
142
143         var urls = hit['md-electronic-url'];
144         var bestLink = null;
145         var otherLinks = [];
146         for (var j = 0; j < urls.length; j++) {
147           var url = urls[j];
148           if (!url.match(/^(https?:)?\/\//)) {
149             that.warn("link '" + url + "' is not a valid URL");
150           } else if (!bestLink) {
151             bestLink = url;
152           } else {
153             otherLinks.push(url);
154           }
155         }
156         hit.bestLink = bestLink;
157         hit.otherLinks = otherLinks;
158       }
159
160       var template = team.loadTemplate(that.config.template || "records");
161       var summaryPartial = team.loadTemplate(that.config['summary-template'] || "summary");
162       var tdata = $.extend({}, {"hits": m_dataToRedraw.hits}, that.config.template_vars);
163       that.node.html(template(tdata, {"partials":{"summary":summaryPartial}}));
164     }
165
166     m_dataToRedraw = null;
167   }
168
169   var m_frozen = false;
170   this.team.queue("records").subscribe(function(data) {
171     m_dataToRedraw = data;
172     if (!m_frozen) {
173       refreshRecordData();
174     }
175   });
176
177   var m_timer;
178   this.node.mousemove(function() {
179     var op = that.config.freeze_opacity;
180     if (op !== undefined) { that.node.css('opacity', op); }
181     m_frozen = true;
182     clearTimeout(m_timer);
183     m_timer = setTimeout(unfreezeRecordDisplay, 1000);
184   });
185
186   function unfreezeRecordDisplay() {
187     clearTimeout(m_timer);
188     that.node.css('opacity', 1);
189     m_frozen = false;
190     refreshRecordData();
191   }
192   this.node.mouseleave(unfreezeRecordDisplay);
193
194   that.autosearch();
195 });
196
197
198 mkws.registerWidgetType('navi', function() {
199   var that = this;
200   var teamName = this.team.name();
201
202   this.team.queue("searchtriggered").subscribe(function() {
203     var filters = that.team.filters();
204     var output = {filters:[]};
205
206     filters.visitTargets(function(id, name) {
207       var cur = {};
208       cur.facet = 'source';
209       cur.value = name;
210       cur.click = "mkws.delimitTarget('" + teamName + "', '" + id + "'); return false;";
211       output.filters.push(cur);
212     });
213
214     filters.visitFields(function(field, value) {
215       var cur = {};
216       cur.facet = field;
217       cur.value = value;
218       cur.click = "mkws.delimitQuery('" + teamName + "', '" + field + "', '" + value + "'" + ");return false;";
219       output.filters.push(cur);
220     });
221
222     var template = that.team.loadTemplate(that.config.template || "navi");
223     that.node.html(template(output));
224   });
225 });
226
227
228 // It seems this and the Perpage widget doen't need to subscribe to
229 // anything, since they produce events rather than consuming them.
230 //
231 mkws.registerWidgetType('sort', function() {
232   var that = this;
233
234   this.node.change(function() {
235     window.location.href = '#' + that.team.urlFragment({ sort: that.node.val() });
236     return false;
237   });
238 });
239
240
241 mkws.registerWidgetType('per-page', function() {
242   var that = this;
243
244   this.node.change(function() {
245     window.location.href = '#' + that.team.urlFragment({ size: that.node.val() });
246     return false;
247   });
248 });
249
250
251 mkws.registerWidgetType('done', function() {
252   var that = this;
253   this.team.queue("complete").subscribe(function(n) {
254     var template = that.team.loadTemplate(that.config.template || "done");
255     that.node.html(template({count: n}));
256   });
257 });
258
259
260 mkws.registerWidgetType('switch', function() {
261   if (!this.config.show_switch) return;
262   var tname = this.team.name();
263   var output = {};
264   output.recordClick = "mkws.switchView(\'" + tname + "\', \'records\')";
265   output.targetClick = "mkws.switchView(\'" + tname + "\', \'targets\')";
266   var template = this.team.loadTemplate(this.config.template || "switch");
267   this.node.html(template(output));
268   this.hideWhenNarrow();
269 });
270
271
272 mkws.registerWidgetType('search', function() {
273   var output = {};
274   output.team = this.team.name();
275   var template = this.team.loadTemplate(this.config.template || "search");
276   this.node.html(template(output));
277 });
278
279
280 mkws.registerWidgetType('search-form', function() {
281   var team = this.team;
282   this.node.submit(function() {
283     var val = team.widget('query').value();
284     team.newSearch(val);
285     return false;
286   });
287 });
288
289
290 mkws.registerWidgetType('results', function() {
291   var template = this.team.loadTemplate(this.config.template || "results");
292   this.node.html(template({team: this.team.name()}));
293   this.autosearch();
294 });
295
296
297 mkws.registerWidgetType('ranking', function() {
298   var output = {};
299   output.perPage = [];
300   output.sort = [];
301   output.team = this.team.name();
302   output.showSort = this.config.show_sort;
303   output.showPerPage = this.config.show_perpage;
304
305   var order = this.team.sortOrder();
306   this.info("making sort, sortOrder = '" + order + "'");
307   for (var i = 0; i < this.config.sort_options.length; i++) {
308     var cur = {};
309     var opt = this.config.sort_options[i];
310     cur.key = opt[0];
311     cur.label = opt.length == 1 ? opt[0] : mkws.M(opt[1]);
312     if (order == cur.key || order == cur.label) cur.selected = true;
313     output.sort.push(cur);
314   }
315
316   var perpage = this.team.perpage();
317   this.info("making perpage, perpage = " + perpage);
318   for(var i = 0; i < this.config.perpage_options.length; i++) {
319     var cur = {};
320     cur.perPage = this.config.perpage_options[i];
321     if (cur.perPage == perpage) cur.selected = true;
322     output.perPage.push(cur);
323   }
324
325   var template = this.team.loadTemplate(this.config.template || "ranking");
326   this.node.html(template(output));
327 });
328
329
330 mkws.registerWidgetType('lang', function() {
331   // dynamic URL or static page? /path/foo?query=test
332   /* create locale language menu */
333   if (!this.config.show_lang) return;
334
335   var lang_default = "en";
336   var lang = this.config.lang || lang_default;
337   var list = [];
338
339   /* display a list of configured languages, or all */
340   var lang_options = this.config.lang_options;
341   var toBeIncluded = {};
342   for (var i = 0; i < lang_options.length; i++) {
343     toBeIncluded[lang_options[i]] = true;
344   }
345
346   for (var k in mkws.locale_lang) {
347     if (toBeIncluded[k] || lang_options.length == 0) {
348       cur = {};
349       if (lang === k) cur.selected = true;
350       cur.code = k;
351       cur.url = lang_url(k);
352       list.push(cur);
353     }
354   }
355
356   // add english link
357   if (lang_options.length == 0 || toBeIncluded[lang_default]) {
358       cur = {};
359       if (lang === lang_default) cur.selected = true;
360       cur.code = lang_default;
361       cur.url = lang_url(lang_default);
362       list.push(cur);
363   }
364
365   this.info("language menu: " + list.join(", "));
366
367   var template = this.team.loadTemplate(this.config.template || "lang");
368   this.node.html(template({languages: list}));
369   this.hideWhenNarrow();
370
371   // set or re-set "lang" URL parameter
372   function lang_url(lang) {
373     var query = location.search;
374     // no query parameters? done
375     if (!query) {
376       return "?lang=" + lang;
377     }
378
379     // parameter does not exist
380     if (!query.match(/[\?&]lang=/)) {
381       return query + "&lang=" + lang;
382     }
383
384     // replace existing parameter
385     query = query.replace(/\?lang=([^&#;]*)/, "?lang=" + lang);
386     query = query.replace(/\&lang=([^&#;]*)/, "&lang=" + lang);
387     return query;
388   }
389 });
390
391
392 mkws.registerWidgetType('motd', function() {
393   var container = this.team.widget('motd-container');
394   if (container) {
395     // Move the MOTD from the provided element down into the container
396     this.node.appendTo(container.node);
397   }
398 });
399
400
401 // This widget has no functionality of its own, but its configuration
402 // is copied up into its team, allowing it to affect other widgets in
403 // the team.
404 //
405 mkws.registerWidgetType('config', function() {
406   var c = this.config;
407   for (var name in c) {
408     if (c.hasOwnProperty(name)) {
409       this.team.config[name] = c[name];
410       this.info(this + " copied property " + name + "='" + c[name] + "' up to team");
411     }
412   }
413 });
414
415
416 mkws.registerWidgetType('progress', function() {
417   var that = this;
418   this.node.hide();
419   this.team.queue("stat").subscribe(function(data) {
420     var template = that.team.loadTemplate(that.config.template || "progress");
421     that.node.html(template({
422       done: data.clients - data.activeclients,
423       waiting: data.activeclients
424     }));
425     that.node.show();
426   });
427 });
428
429
430 mkws.registerWidgetType('waiting', function() {
431   var that = this;
432
433   this.node.css("visibility", "hidden");
434   var template = that.team.loadTemplate(that.config.template || "waiting");
435   this.node.html(template({
436     src: this.config.src || "http://mkws.indexdata.com/progress.gif"
437   }));
438
439   this.team.queue("searchtriggered").subscribe(function(data) {
440     that.node.css("visibility", "visible");
441   });
442   this.team.queue("complete").subscribe(function(n) {
443     that.node.css("visibility", "hidden");
444   });
445 });
446
447
448 // Some elements have mkws* classes that makes them appear as widgets
449 // -- for example, because we want to style them using CSS -- but have
450 // no actual functionality. We register these to prevent ignorable
451 // warnings when they occur.
452
453 mkws.registerWidgetType('query', function() {});
454 mkws.registerWidgetType('motd-container', function() {});
455 mkws.registerWidgetType('button', function() {});
456
457
458 })(mkws.$); // jQuery wrapper