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) {
17 // Member variables are separated into two categories
19 // 1. Persistent state (to be coded in URL fragment)
20 var m_query; // initially undefined
21 var m_sortOrder; // will be set below
22 var m_perpage; // will be set below
23 var m_filterSet = filterSet(that);
24 var m_currentPage = 1;
25 var m_currentRecordId = '';
27 // 2. Internal state (not to be coded)
28 var m_teamName = teamName;
29 var m_paz; // will be initialised below
30 var m_submitted = false;
31 var m_totalRecordCount = 0;
32 var m_currentRecordData = null;
34 // Timestamps for logging
38 var m_templateText = {}; // widgets can register templates to be compiled
39 var m_template = {}; // compiled templates, from any source
40 var m_widgets = {}; // Maps widget-type to array of widget objects
41 var m_gotRecords = false;
43 var config = mkws.objectInheritingFrom(mkws.config);
46 that.toString = function() { return '[Team ' + teamName + ']'; };
48 // Accessor methods for individual widgets: readers
49 that.name = function() { return m_teamName; };
50 that.submitted = function() { return m_submitted; };
51 that.sortOrder = function() { return m_sortOrder; };
52 that.perpage = function() { return m_perpage; };
53 that.query = function() { return m_query; };
54 that.totalRecordCount = function() { return m_totalRecordCount; };
55 that.currentPage = function() { return m_currentPage; };
56 that.currentRecordId = function() { return m_currentRecordId; };
57 that.currentRecordData = function() { return m_currentRecordData; };
58 that.filters = function() { return m_filterSet; };
59 that.gotRecords = function() { return m_gotRecords; };
61 // Accessor methods for individual widgets: writers
62 that.set_sortOrder = function(val) { m_sortOrder = val };
63 that.set_perpage = function(val) { m_perpage = val };
66 // The following PubSub code is modified from the jQuery manual:
67 // http://api.jquery.com/jQuery.Callbacks/
70 // team.queue("eventName").subscribe(function(param1, param2 ...) { ... });
71 // team.queue("eventName").publish(arg1, arg2, ...);
76 var callbacks = $.Callbacks();
78 publish: callbacks.fire,
79 subscribe: callbacks.add,
80 unsubscribe: callbacks.remove
88 function _log(fn, s) {
90 var timestamp = (((now - m_logTime.start)/1000).toFixed(3) + " (+" +
91 ((now - m_logTime.last)/1000).toFixed(3) + ") ");
93 fn.call(mkws.log, m_teamName + ": " + timestamp + s);
94 that.queue("log").publish(m_teamName, timestamp, s);
97 that.trace = function(x) { _log(mkws.trace, x) };
98 that.debug = function(x) { _log(mkws.debug, x) };
99 that.info = function(x) { _log(mkws.info, x) };
100 that.warn = function(x) { _log(mkws.warn, x) };
101 that.error = function(x) { _log(mkws.error, x) };
102 that.fatal = function(x) { _log(mkws.fatal, x) };
104 that.info("making new widget team");
106 m_sortOrder = config.sort_default;
107 m_perpage = config.perpage_default;
109 // pz2.js event handlers:
116 function onBytarget(data) {
117 that.info("bytarget");
118 queue("targets").publish(data);
121 function onStat(data) {
122 queue("stat").publish(data);
123 var hitcount = parseInt(data.hits[0], 10);
124 if (!m_gotRecords && hitcount > 0) {
126 queue("firstrecords").publish(hitcount);
128 if (parseInt(data.activeclients[0], 10) === 0) {
129 that.info("complete");
130 queue("complete").publish(hitcount);
134 function onTerm(data) {
136 queue("facets").publish(data);
139 function onShow(data, teamName) {
141 m_totalRecordCount = data.merged;
142 that.info("found " + m_totalRecordCount + " records");
143 queue("pager").publish(data);
144 queue("records").publish(data);
147 function onRecord(data, args, teamName) {
149 // FIXME: record is async!!
150 clearTimeout(m_paz.recordTimer);
151 queue("record").publish(data);
152 var detRecordDiv = findnode(recordDetailsId(data.recid[0]));
153 if (detRecordDiv.length) {
154 // in case on_show was faster to redraw element
157 m_currentRecordData = data;
158 var recordDiv = findnode('.' + recordElementId(m_currentRecordData.recid[0]));
159 var html = renderDetails(m_currentRecordData);
160 $(recordDiv).append(html);
164 // create a parameters array and pass it to the pz2's constructor
165 // then register the form submit event with the pz2.search function
166 // autoInit is set to true on default
167 that.makePz2 = function() {
168 that.debug("m_queues=" + $.toJSON(m_queues));
170 "windowid": teamName,
171 "pazpar2path": mkws.pazpar2_url(),
172 "usesessions" : config.use_service_proxy ? false : true,
173 "showtime": 500, //each timer (show, stat, term, bytarget) can be specified this way
174 "termlist": config.facets.join(',')
177 params.oninit = onInit;
178 if (m_queues.targets) {
179 params.onbytarget = onBytarget;
180 that.info("setting bytarget callback");
182 if (m_queues.stat || m_queues.firstrecords || m_queues.complete) {
183 params.onstat = onStat;
184 that.info("setting stat callback");
186 if (m_queues.facets && config.facets.length) {
187 params.onterm = onTerm;
188 that.info("setting term callback");
190 if (m_queues.records) {
191 that.info("setting show callback");
192 params.onshow = onShow;
193 // Record callback is subscribed from records callback
194 that.info("setting record callback");
195 params.onrecord = onRecord;
198 m_paz = new pz2(params);
199 that.info("created main pz2 object");
203 // Used by the Records widget and onRecord()
204 function recordElementId(s) {
205 return 'mkws-rec_' + s.replace(/[^a-z0-9]/ig, '_');
207 that.recordElementId = recordElementId;
209 // Used by onRecord(), showDetails() and renderDetails()
210 function recordDetailsId(s) {
211 return 'mkws-det_' + s.replace(/[^a-z0-9]/ig, '_');
215 that.targetFiltered = function(id) {
216 return m_filterSet.targetFiltered(id);
220 that.limitTarget = function(id, name) {
221 that.info("limitTarget(id=" + id + ", name=" + name + ")");
222 m_filterSet.add(targetFilter(id, name));
223 if (m_query) triggerSearch();
228 that.limitQuery = function(field, value) {
229 that.info("limitQuery(field=" + field + ", value=" + value + ")");
230 m_filterSet.add(fieldFilter(field, value));
231 if (m_query) triggerSearch();
236 that.limitCategory = function(id) {
237 that.info("limitCategory(id=" + id + ")");
238 // Only one category filter at a time
239 m_filterSet.removeMatching(function(f) { return f.type === 'category' });
240 if (id !== '') m_filterSet.add(categoryFilter(id));
241 if (m_query) triggerSearch();
246 that.delimitTarget = function(id) {
247 that.info("delimitTarget(id=" + id + ")");
248 m_filterSet.removeMatching(function(f) { return f.type === 'target' });
249 if (m_query) triggerSearch();
254 that.delimitQuery = function(field, value) {
255 that.info("delimitQuery(field=" + field + ", value=" + value + ")");
256 m_filterSet.removeMatching(function(f) { return f.type == 'field' &&
257 field == f.field && value == f.value });
258 if (m_query) triggerSearch();
263 that.showPage = function(pageNum) {
264 m_currentPage = pageNum;
265 m_paz.showPage(m_currentPage - 1);
269 that.pagerNext = function() {
270 if (m_totalRecordCount - m_perpage*m_currentPage > 0) {
277 that.pagerPrev = function() {
278 if (m_paz.showPrev() != false)
283 that.reShow = function() {
285 m_paz.show(0, m_perpage, m_sortOrder);
289 function resetPage() {
291 m_totalRecordCount = 0;
292 m_gotRecords = false;
294 that.resetPage = resetPage;
297 function newSearch(query, sortOrder, maxrecs, perpage, limit, targets, torusquery) {
298 that.info("newSearch: " + query);
300 if (config.use_service_proxy && !mkws.authenticated) {
301 alert("searching before authentication");
305 m_filterSet.removeMatching(function(f) { return f.type !== 'category' });
306 triggerSearch(query, sortOrder, maxrecs, perpage, limit, targets, torusquery);
307 switchView('records'); // In case it's configured to start off as hidden
310 that.newSearch = newSearch;
313 function triggerSearch(query, sortOrder, maxrecs, perpage, limit, targets, torusquery) {
316 // Continue to use previous query/sort-order unless new ones are specified
317 if (query) m_query = query;
318 if (sortOrder) m_sortOrder = sortOrder;
319 if (perpage) m_perpage = perpage;
320 if (targets) m_filterSet.add(targetFilter(targets, targets));
322 var pp2filter = m_filterSet.pp2filter();
323 var pp2limit = m_filterSet.pp2limit(limit);
324 var pp2catLimit = m_filterSet.pp2catLimit();
326 pp2filter = pp2filter ? pp2filter + "," + pp2catLimit : pp2catLimit;
330 if (pp2limit) params.limit = pp2limit;
331 if (maxrecs) params.maxrecs = maxrecs;
333 if (!mkws.config.use_service_proxy)
334 alert("can't narrow search by torusquery when not authenticated");
335 params.torusquery = torusquery;
338 that.info("triggerSearch(" + m_query + "): filters = " + m_filterSet.toJSON() + ", " +
339 "pp2filter = " + pp2filter + ", params = " + $.toJSON(params));
341 m_paz.search(m_query, m_perpage, m_sortOrder, pp2filter, undefined, params);
342 queue("searchtriggered").publish();
345 // fetch record details to be retrieved from the record queue
346 that.fetchDetails = function(recId) {
347 that.info("fetchDetails() requesting record '" + recId + "'");
352 // switching view between targets and records
353 function switchView(view) {
354 var targets = widgetNode('targets');
355 var results = widgetNode('results') || widgetNode('records');
356 var blanket = widgetNode('blanket');
357 var motd = widgetNode('motd');
361 if (targets) $(targets).show();
362 if (results) $(results).hide();
363 if (blanket) $(blanket).hide();
364 if (motd) $(motd).hide();
367 if (targets) $(targets).hide();
368 if (results) $(results).show();
369 if (blanket) $(blanket).show();
370 if (motd) $(motd).hide();
373 alert("Unknown view '" + view + "'");
376 that.switchView = switchView;
379 // detailed record drawing
380 that.showDetails = function(recId) {
381 var oldRecordId = m_currentRecordId;
382 m_currentRecordId = recId;
384 // remove current detailed view if any
385 findnode('#' + recordDetailsId(oldRecordId)).remove();
387 // if the same clicked, just hide
388 if (recId == oldRecordId) {
389 m_currentRecordId = '';
390 m_currentRecordData = null;
393 // request the record
394 that.info("showDetails() requesting record '" + recId + "'");
399 // Finds the node of the specified class within the current team
400 function findnode(selector, teamName) {
401 teamName = teamName || m_teamName;
403 if (teamName === 'AUTO') {
404 selector = (selector + '.mkws-team-' + teamName + ',' +
405 selector + ':not([class^="mkws-team"],[class*=" mkws-team"])');
407 selector = selector + '.mkws-team-' + teamName;
410 var node = $(selector);
411 //that.debug('findnode(' + selector + ') found ' + node.length + ' nodes');
416 function widgetNode(type) {
417 var w = that.widget(type);
418 return w ? w.node : undefined;
421 function renderDetails(data, marker) {
422 var template = loadTemplate("details");
423 var details = template(data);
424 return '<div class="mkws-details mkwsDetails mkwsTeam_' + m_teamName + '" ' +
425 'id="' + recordDetailsId(data.recid[0]) + '">' + details + '</div>';
427 that.renderDetails = renderDetails;
430 that.registerTemplate = function(name, text) {
431 if(mkws._old2new.hasOwnProperty(name)) {
432 that.warn("registerTemplate: old widget name: " + name + " => " + mkws._old2new[name]);
433 name = mkws._old2new[name];
435 m_templateText[name] = text;
439 function loadTemplate(name, fallbackString) {
440 if(mkws._old2new.hasOwnProperty(name)) {
441 that.warn("loadTemplate: old widget name: " + name + " => " + mkws._old2new[name]);
442 name = mkws._old2new[name];
445 var template = m_template[name];
446 if (template === undefined && Handlebars.compile) {
448 var node = $(".mkws-template-" + name + " .mkws-team-" + that.name());
449 if (node && node.length < 1) {
450 node = $(".mkws-template-" + name);
452 if (node) source = node.html();
453 if (!source) source = m_templateText[name];
455 template = Handlebars.compile(source);
456 that.info("compiled template '" + name + "'");
459 //if (template === undefined) template = mkws_templatesbyteam[m_teamName][name];
460 if (template === undefined && Handlebars.templates) {
461 template = Handlebars.templates["mkws-template-" + name];
463 if (template === undefined && mkws.defaultTemplates) {
464 template = mkws.defaultTemplates[name];
467 m_template[name] = template;
471 that.info("No MKWS template for " + name);
475 that.loadTemplate = loadTemplate;
478 that.addWidget = function(w) {
479 if (m_widgets[w.type] === undefined) {
480 m_widgets[w.type] = [ w ];
482 m_widgets[w.type].push(w);
486 that.widget = function(type) {
487 var list = m_widgets[type];
491 if (list.length > 1) {
492 alert("widget('" + type + "') finds " + list.length + " widgets: using first");
497 that.visitWidgets = function(callback) {
498 for (var type in m_widgets) {
499 var list = m_widgets[type];
500 for (var i = 0; i < list.length; i++) {
501 var res = callback(type, list[i]);
502 if (res !== undefined) {