1 // Factory function for team objects. As much as possible, this uses
2 // only member variables (prefixed "m_") and inner functions with
5 // Some functions are visible as member-functions to be called from
6 // outside code -- specifically, from generated HTML. These functions
7 // are that.switchView(), showDetails(), limitTarget(), limitQuery(),
8 // limitCategory(), delimitTarget(), delimitQuery(), showPage(),
9 // pagerPrev(), pagerNext().
11 // Before the team can be used for searching and related operations,
12 // its pz2 object must be created by calling team.makePz2().
14 mkws.makeTeam = function($, teamName) {
16 var m_teamName = teamName;
17 var m_submitted = false;
18 var m_query; // initially undefined
19 var m_sortOrder; // will be set below
20 var m_perpage; // will be set below
21 var m_filterSet = filterSet(that);
22 var m_totalRecordCount = 0;
23 var m_currentPage = 1;
24 var m_currentRecordId = '';
25 var m_currentRecordData = null;
27 // Timestamps for logging
31 var m_paz; // will be initialised below
32 var m_templateText = {}; // widgets can register templates to be compiled
33 var m_template = {}; // compiled templates, from any source
34 var m_widgets = {}; // Maps widget-type to array of widget objects
35 var m_gotRecords = false;
37 var config = mkws.objectInheritingFrom(mkws.config);
40 that.toString = function() { return '[Team ' + teamName + ']'; };
42 // Accessor methods for individual widgets: readers
43 that.name = function() { return m_teamName; };
44 that.submitted = function() { return m_submitted; };
45 that.sortOrder = function() { return m_sortOrder; };
46 that.perpage = function() { return m_perpage; };
47 that.query = function() { return m_query; };
48 that.totalRecordCount = function() { return m_totalRecordCount; };
49 that.currentPage = function() { return m_currentPage; };
50 that.currentRecordId = function() { return m_currentRecordId; };
51 that.currentRecordData = function() { return m_currentRecordData; };
52 that.filters = function() { return m_filterSet; };
53 that.gotRecords = function() { return m_gotRecords; };
55 // Accessor methods for individual widgets: writers
56 that.set_sortOrder = function(val) { m_sortOrder = val };
57 that.set_perpage = function(val) { m_perpage = val };
60 // The following PubSub code is modified from the jQuery manual:
61 // http://api.jquery.com/jQuery.Callbacks/
64 // team.queue("eventName").subscribe(function(param1, param2 ...) { ... });
65 // team.queue("eventName").publish(arg1, arg2, ...);
70 var callbacks = $.Callbacks();
72 publish: callbacks.fire,
73 subscribe: callbacks.add,
74 unsubscribe: callbacks.remove
82 function _log(fn, s) {
84 var timestamp = (((now - m_logTime.start)/1000).toFixed(3) + " (+" +
85 ((now - m_logTime.last)/1000).toFixed(3) + ") ");
87 fn.call(mkws.log, m_teamName + ": " + timestamp + s);
88 that.queue("log").publish(m_teamName, timestamp, s);
91 that.trace = function(x) { _log(mkws.trace, x) };
92 that.debug = function(x) { _log(mkws.debug, x) };
93 that.info = function(x) { _log(mkws.info, x) };
94 that.warn = function(x) { _log(mkws.warn, x) };
95 that.error = function(x) { _log(mkws.error, x) };
96 that.fatal = function(x) { _log(mkws.fatal, x) };
98 that.info("making new widget team");
100 m_sortOrder = config.sort_default;
101 m_perpage = config.perpage_default;
103 // pz2.js event handlers:
110 function onBytarget(data) {
111 that.info("bytarget");
112 queue("targets").publish(data);
115 function onStat(data) {
116 queue("stat").publish(data);
117 var hitcount = parseInt(data.hits[0], 10);
118 if (!m_gotRecords && hitcount > 0) {
120 queue("firstrecords").publish(hitcount);
122 if (parseInt(data.activeclients[0], 10) === 0) {
123 that.info("complete");
124 queue("complete").publish(hitcount);
128 function onTerm(data) {
130 queue("facets").publish(data);
133 function onShow(data, teamName) {
135 m_totalRecordCount = data.merged;
136 that.info("found " + m_totalRecordCount + " records");
137 queue("pager").publish(data);
138 queue("records").publish(data);
141 function onRecord(data, args, teamName) {
143 // FIXME: record is async!!
144 clearTimeout(m_paz.recordTimer);
145 queue("record").publish(data);
146 var detRecordDiv = findnode(recordDetailsId(data.recid[0]));
147 if (detRecordDiv.length) {
148 // in case on_show was faster to redraw element
151 m_currentRecordData = data;
152 var recordDiv = findnode('.' + recordElementId(m_currentRecordData.recid[0]));
153 var html = renderDetails(m_currentRecordData);
154 $(recordDiv).append(html);
158 // create a parameters array and pass it to the pz2's constructor
159 // then register the form submit event with the pz2.search function
160 // autoInit is set to true on default
161 that.makePz2 = function() {
162 that.debug("m_queues=" + $.toJSON(m_queues));
164 "windowid": teamName,
165 "pazpar2path": mkws.pazpar2_url(),
166 "usesessions" : config.use_service_proxy ? false : true,
167 "showtime": 500, //each timer (show, stat, term, bytarget) can be specified this way
168 "termlist": config.facets.join(',')
171 params.oninit = onInit;
172 if (m_queues.targets) {
173 params.onbytarget = onBytarget;
174 that.info("setting bytarget callback");
176 if (m_queues.stat || m_queues.firstrecords || m_queues.complete) {
177 params.onstat = onStat;
178 that.info("setting stat callback");
180 if (m_queues.facets && config.facets.length) {
181 params.onterm = onTerm;
182 that.info("setting term callback");
184 if (m_queues.records) {
185 that.info("setting show callback");
186 params.onshow = onShow;
187 // Record callback is subscribed from records callback
188 that.info("setting record callback");
189 params.onrecord = onRecord;
192 m_paz = new pz2(params);
193 that.info("created main pz2 object");
197 // Used by the Records widget and onRecord()
198 function recordElementId(s) {
199 return 'mkws-rec_' + s.replace(/[^a-z0-9]/ig, '_');
201 that.recordElementId = recordElementId;
203 // Used by onRecord(), showDetails() and renderDetails()
204 function recordDetailsId(s) {
205 return 'mkws-det_' + s.replace(/[^a-z0-9]/ig, '_');
209 that.targetFiltered = function(id) {
210 return m_filterSet.targetFiltered(id);
214 that.limitTarget = function(id, name) {
215 that.info("limitTarget(id=" + id + ", name=" + name + ")");
216 m_filterSet.add(targetFilter(id, name));
217 if (m_query) triggerSearch();
222 that.limitQuery = function(field, value) {
223 that.info("limitQuery(field=" + field + ", value=" + value + ")");
224 m_filterSet.add(fieldFilter(field, value));
225 if (m_query) triggerSearch();
230 that.limitCategory = function(id) {
231 that.info("limitCategory(id=" + id + ")");
232 // Only one category filter at a time
233 m_filterSet.removeMatching(function(f) { return f.type === 'category' });
234 if (id !== '') m_filterSet.add(categoryFilter(id));
235 if (m_query) triggerSearch();
240 that.delimitTarget = function(id) {
241 that.info("delimitTarget(id=" + id + ")");
242 m_filterSet.removeMatching(function(f) { return f.type === 'target' });
243 if (m_query) triggerSearch();
248 that.delimitQuery = function(field, value) {
249 that.info("delimitQuery(field=" + field + ", value=" + value + ")");
250 m_filterSet.removeMatching(function(f) { return f.type == 'field' &&
251 field == f.field && value == f.value });
252 if (m_query) triggerSearch();
257 that.showPage = function(pageNum) {
258 m_currentPage = pageNum;
259 m_paz.showPage(m_currentPage - 1);
263 that.pagerNext = function() {
264 if (m_totalRecordCount - m_perpage*m_currentPage > 0) {
271 that.pagerPrev = function() {
272 if (m_paz.showPrev() != false)
277 that.reShow = function() {
279 m_paz.show(0, m_perpage, m_sortOrder);
283 function resetPage() {
285 m_totalRecordCount = 0;
286 m_gotRecords = false;
288 that.resetPage = resetPage;
291 function newSearch(widget, query, sortOrder, maxrecs, perpage, limit, targets, torusquery) {
292 that.info("newSearch: " + query);
294 if (config.use_service_proxy && !mkws.authenticated) {
295 alert("searching before authentication");
300 if (!sortOrder) sortOrder = that.config.sort;
301 if (!maxrecs) maxrecs = that.config.maxrecs;
302 if (!perpage) perpage = that.config.perpage;
303 if (!limit) limit = that.config.limit;
304 if (!targets) targets = that.config.targets;
305 if (!torusquery) torusquery = that.config.targetfilter;
306 var target = that.config.target;
307 if (target) torusquery = 'udb=="' + target + '"';
309 var s = "running search: '" + query + "'";
310 if (sortOrder) s += " sorted by '" + sortOrder + "'";
311 if (maxrecs) s += " restricted to " + maxrecs + " records";
312 if (perpage) s += " with " + perpage + " per page";
313 if (limit) s += " limited by '" + limit + "'";
314 if (targets) s += " in targets '" + targets + "'";
315 if (torusquery) s += " constrained by torusquery '" + torusquery + "'";
319 m_filterSet.removeMatching(function(f) { return f.type !== 'category' });
320 triggerSearch(query, sortOrder, maxrecs, perpage, limit, targets, torusquery);
321 switchView('records'); // In case it's configured to start off as hidden
324 that.newSearch = newSearch;
327 function triggerSearch(query, sortOrder, maxrecs, perpage, limit, targets, torusquery) {
330 // Continue to use previous query/sort-order unless new ones are specified
331 if (query) m_query = query;
332 if (sortOrder) m_sortOrder = sortOrder;
333 if (perpage) m_perpage = perpage;
334 if (targets) m_filterSet.add(targetFilter(targets, targets));
336 var pp2filter = m_filterSet.pp2filter();
337 var pp2limit = m_filterSet.pp2limit(limit);
338 var pp2catLimit = m_filterSet.pp2catLimit();
340 pp2filter = pp2filter ? pp2filter + "," + pp2catLimit : pp2catLimit;
344 if (pp2limit) params.limit = pp2limit;
345 if (maxrecs) params.maxrecs = maxrecs;
347 if (!mkws.config.use_service_proxy)
348 alert("can't narrow search by torusquery when not authenticated");
349 params.torusquery = torusquery;
352 that.info("triggerSearch(" + m_query + "): filters = " + m_filterSet.toJSON() + ", " +
353 "pp2filter = " + pp2filter + ", params = " + $.toJSON(params));
355 m_paz.search(m_query, m_perpage, m_sortOrder, pp2filter, undefined, params);
356 queue("searchtriggered").publish();
359 // fetch record details to be retrieved from the record queue
360 that.fetchDetails = function(recId) {
361 that.info("fetchDetails() requesting record '" + recId + "'");
366 // switching view between targets and records
367 function switchView(view) {
368 var targets = widgetNode('targets');
369 var results = widgetNode('results') || widgetNode('records');
370 var blanket = widgetNode('blanket');
371 var motd = widgetNode('motd');
375 if (targets) $(targets).show();
376 if (results) $(results).hide();
377 if (blanket) $(blanket).hide();
378 if (motd) $(motd).hide();
381 if (targets) $(targets).hide();
382 if (results) $(results).show();
383 if (blanket) $(blanket).show();
384 if (motd) $(motd).hide();
387 alert("Unknown view '" + view + "'");
390 that.switchView = switchView;
393 // detailed record drawing
394 that.showDetails = function(recId) {
395 var oldRecordId = m_currentRecordId;
396 m_currentRecordId = recId;
398 // remove current detailed view if any
399 findnode('#' + recordDetailsId(oldRecordId)).remove();
401 // if the same clicked, just hide
402 if (recId == oldRecordId) {
403 m_currentRecordId = '';
404 m_currentRecordData = null;
407 // request the record
408 that.info("showDetails() requesting record '" + recId + "'");
413 // Finds the node of the specified class within the current team
414 function findnode(selector, teamName) {
415 teamName = teamName || m_teamName;
417 if (teamName === 'AUTO') {
418 selector = (selector + '.mkws-team-' + teamName + ',' +
419 selector + ':not([class^="mkws-team"],[class*=" mkws-team"])');
421 selector = selector + '.mkws-team-' + teamName;
424 var node = $(selector);
425 //that.debug('findnode(' + selector + ') found ' + node.length + ' nodes');
430 function widgetNode(type) {
431 var w = that.widget(type);
432 return w ? w.node : undefined;
435 function renderDetails(data, marker) {
436 var template = loadTemplate("details");
437 var details = template(data);
438 return '<div class="mkws-details mkwsDetails mkwsTeam_' + m_teamName + '" ' +
439 'id="' + recordDetailsId(data.recid[0]) + '">' + details + '</div>';
441 that.renderDetails = renderDetails;
444 that.registerTemplate = function(name, text) {
445 if(mkws._old2new.hasOwnProperty(name)) {
446 that.warn("registerTemplate: old widget name: " + name + " => " + mkws._old2new[name]);
447 name = mkws._old2new[name];
449 m_templateText[name] = text;
453 function loadTemplate(name, fallbackString) {
454 if(mkws._old2new.hasOwnProperty(name)) {
455 that.warn("loadTemplate: old widget name: " + name + " => " + mkws._old2new[name]);
456 name = mkws._old2new[name];
459 var template = m_template[name];
460 if (template === undefined && Handlebars.compile) {
462 var node = $(".mkws-template-" + name + " .mkws-team-" + that.name());
463 if (node && node.length < 1) {
464 node = $(".mkws-template-" + name);
466 if (node) source = node.html();
467 if (!source) source = m_templateText[name];
469 template = Handlebars.compile(source);
470 that.info("compiled template '" + name + "'");
473 //if (template === undefined) template = mkws_templatesbyteam[m_teamName][name];
474 if (template === undefined && Handlebars.templates) {
475 template = Handlebars.templates["mkws-template-" + name];
477 if (template === undefined && mkws.defaultTemplates) {
478 template = mkws.defaultTemplates[name];
481 m_template[name] = template;
485 that.info("No MKWS template for " + name);
489 that.loadTemplate = loadTemplate;
492 that.addWidget = function(w) {
493 if (m_widgets[w.type] === undefined) {
494 m_widgets[w.type] = [ w ];
496 m_widgets[w.type].push(w);
500 that.widget = function(type) {
501 var list = m_widgets[type];
505 if (list.length > 1) {
506 alert("widget('" + type + "') finds " + list.length + " widgets: using first");
511 that.visitWidgets = function(callback) {
512 for (var type in m_widgets) {
513 var list = m_widgets[type];
514 for (var i = 0; i < list.length; i++) {
515 var res = callback(type, list[i]);
516 if (res !== undefined) {