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 // Note: separate constants from state, which should be in an object
17 var m_teamName = teamName;
18 var m_submitted = false;
19 var m_query; // initially undefined
20 var m_sortOrder; // will be set below
21 var m_perpage; // will be set below
22 var m_filterSet = filterSet(that);
23 var m_totalRecordCount = 0;
24 var m_currentPage = 1;
25 var m_currentRecordId = '';
26 var m_currentRecordData = null;
28 // Timestamps for logging
32 var m_paz; // will be initialised below
33 var m_templateText = {}; // widgets can register templates to be compiled
34 var m_template = {}; // compiled templates, from any source
35 var m_widgets = {}; // Maps widget-type to array of widget objects
36 var m_gotRecords = false;
38 var config = mkws.objectInheritingFrom(mkws.config);
41 that.toString = function() { return '[Team ' + teamName + ']'; };
43 // Accessor methods for individual widgets: readers
44 that.name = function() { return m_teamName; };
45 that.submitted = function() { return m_submitted; };
46 that.sortOrder = function() { return m_sortOrder; };
47 that.perpage = function() { return m_perpage; };
48 that.query = function() { return m_query; };
49 that.totalRecordCount = function() { return m_totalRecordCount; };
50 that.currentPage = function() { return m_currentPage; };
51 that.currentRecordId = function() { return m_currentRecordId; };
52 that.currentRecordData = function() { return m_currentRecordData; };
53 that.filters = function() { return m_filterSet; };
54 that.gotRecords = function() { return m_gotRecords; };
56 // Accessor methods for individual widgets: writers
57 that.set_sortOrder = function(val) { m_sortOrder = val };
58 that.set_perpage = function(val) { m_perpage = val };
61 // The following PubSub code is modified from the jQuery manual:
62 // http://api.jquery.com/jQuery.Callbacks/
65 // team.queue("eventName").subscribe(function(param1, param2 ...) { ... });
66 // team.queue("eventName").publish(arg1, arg2, ...);
71 var callbacks = $.Callbacks();
73 publish: callbacks.fire,
74 subscribe: callbacks.add,
75 unsubscribe: callbacks.remove
83 function _log(fn, s) {
85 var timestamp = (((now - m_logTime.start)/1000).toFixed(3) + " (+" +
86 ((now - m_logTime.last)/1000).toFixed(3) + ") ");
88 fn.call(mkws.log, m_teamName + ": " + timestamp + s);
89 that.queue("log").publish(m_teamName, timestamp, s);
92 that.trace = function(x) { _log(mkws.trace, x) };
93 that.debug = function(x) { _log(mkws.debug, x) };
94 that.info = function(x) { _log(mkws.info, x) };
95 that.warn = function(x) { _log(mkws.warn, x) };
96 that.error = function(x) { _log(mkws.error, x) };
97 that.fatal = function(x) { _log(mkws.fatal, x) };
99 that.info("making new widget team");
101 m_sortOrder = config.sort_default;
102 m_perpage = config.perpage_default;
104 // pz2.js event handlers:
111 function onBytarget(data) {
112 that.info("bytarget");
113 queue("targets").publish(data);
116 function onStat(data) {
117 queue("stat").publish(data);
118 var hitcount = parseInt(data.hits[0], 10);
119 if (!m_gotRecords && hitcount > 0) {
121 queue("firstrecords").publish(hitcount);
123 if (parseInt(data.activeclients[0], 10) === 0) {
124 that.info("complete");
125 queue("complete").publish(hitcount);
129 function onTerm(data) {
131 queue("facets").publish(data);
134 function onShow(data, teamName) {
136 m_totalRecordCount = data.merged;
137 that.info("found " + m_totalRecordCount + " records");
138 queue("pager").publish(data);
139 queue("records").publish(data);
142 function onRecord(data, args, teamName) {
144 // FIXME: record is async!!
145 clearTimeout(m_paz.recordTimer);
146 queue("record").publish(data);
147 var detRecordDiv = findnode(recordDetailsId(data.recid[0]));
148 if (detRecordDiv.length) {
149 // in case on_show was faster to redraw element
152 m_currentRecordData = data;
153 var recordDiv = findnode('.' + recordElementId(m_currentRecordData.recid[0]));
154 var html = renderDetails(m_currentRecordData);
155 $(recordDiv).append(html);
159 // create a parameters array and pass it to the pz2's constructor
160 // then register the form submit event with the pz2.search function
161 // autoInit is set to true on default
162 that.makePz2 = function() {
163 that.debug("m_queues=" + $.toJSON(m_queues));
165 "windowid": teamName,
166 "pazpar2path": mkws.pazpar2_url(),
167 "usesessions" : config.use_service_proxy ? false : true,
168 "showtime": 500, //each timer (show, stat, term, bytarget) can be specified this way
169 "termlist": config.facets.join(',')
172 params.oninit = onInit;
173 if (m_queues.targets) {
174 params.onbytarget = onBytarget;
175 that.info("setting bytarget callback");
177 if (m_queues.stat || m_queues.firstrecords || m_queues.complete) {
178 params.onstat = onStat;
179 that.info("setting stat callback");
181 if (m_queues.facets && config.facets.length) {
182 params.onterm = onTerm;
183 that.info("setting term callback");
185 if (m_queues.records) {
186 that.info("setting show callback");
187 params.onshow = onShow;
188 // Record callback is subscribed from records callback
189 that.info("setting record callback");
190 params.onrecord = onRecord;
193 m_paz = new pz2(params);
194 that.info("created main pz2 object");
198 // Used by the Records widget and onRecord()
199 function recordElementId(s) {
200 return 'mkws-rec_' + s.replace(/[^a-z0-9]/ig, '_');
202 that.recordElementId = recordElementId;
204 // Used by onRecord(), showDetails() and renderDetails()
205 function recordDetailsId(s) {
206 return 'mkws-det_' + s.replace(/[^a-z0-9]/ig, '_');
210 that.targetFiltered = function(id) {
211 return m_filterSet.targetFiltered(id);
215 that.limitTarget = function(id, name) {
216 that.info("limitTarget(id=" + id + ", name=" + name + ")");
217 m_filterSet.add(targetFilter(id, name));
218 if (m_query) triggerSearch();
223 that.limitQuery = function(field, value) {
224 that.info("limitQuery(field=" + field + ", value=" + value + ")");
225 m_filterSet.add(fieldFilter(field, value));
226 if (m_query) triggerSearch();
231 that.limitCategory = function(id) {
232 that.info("limitCategory(id=" + id + ")");
233 // Only one category filter at a time
234 m_filterSet.removeMatching(function(f) { return f.type === 'category' });
235 if (id !== '') m_filterSet.add(categoryFilter(id));
236 if (m_query) triggerSearch();
241 that.delimitTarget = function(id) {
242 that.info("delimitTarget(id=" + id + ")");
243 m_filterSet.removeMatching(function(f) { return f.type === 'target' });
244 if (m_query) triggerSearch();
249 that.delimitQuery = function(field, value) {
250 that.info("delimitQuery(field=" + field + ", value=" + value + ")");
251 m_filterSet.removeMatching(function(f) { return f.type == 'field' &&
252 field == f.field && value == f.value });
253 if (m_query) triggerSearch();
258 that.showPage = function(pageNum) {
259 m_currentPage = pageNum;
260 m_paz.showPage(m_currentPage - 1);
264 that.pagerNext = function() {
265 if (m_totalRecordCount - m_perpage*m_currentPage > 0) {
272 that.pagerPrev = function() {
273 if (m_paz.showPrev() != false)
278 that.reShow = function() {
280 m_paz.show(0, m_perpage, m_sortOrder);
284 function resetPage() {
286 m_totalRecordCount = 0;
287 m_gotRecords = false;
289 that.resetPage = resetPage;
292 function newSearch(query, sortOrder, maxrecs, perpage, limit, targets, torusquery) {
293 that.info("newSearch: " + query);
295 if (config.use_service_proxy && !mkws.authenticated) {
296 alert("searching before authentication");
300 m_filterSet.removeMatching(function(f) { return f.type !== 'category' });
301 triggerSearch(query, sortOrder, maxrecs, perpage, limit, targets, torusquery);
302 switchView('records'); // In case it's configured to start off as hidden
305 that.newSearch = newSearch;
308 function triggerSearch(query, sortOrder, maxrecs, perpage, limit, targets, torusquery) {
311 // Continue to use previous query/sort-order unless new ones are specified
312 if (query) m_query = query;
313 if (sortOrder) m_sortOrder = sortOrder;
314 if (perpage) m_perpage = perpage;
315 if (targets) m_filterSet.add(targetFilter(targets, targets));
317 var pp2filter = m_filterSet.pp2filter();
318 var pp2limit = m_filterSet.pp2limit(limit);
319 var pp2catLimit = m_filterSet.pp2catLimit();
321 pp2filter = pp2filter ? pp2filter + "," + pp2catLimit : pp2catLimit;
325 if (pp2limit) params.limit = pp2limit;
326 if (maxrecs) params.maxrecs = maxrecs;
328 if (!mkws.config.use_service_proxy)
329 alert("can't narrow search by torusquery when not authenticated");
330 params.torusquery = torusquery;
333 that.info("triggerSearch(" + m_query + "): filters = " + m_filterSet.toJSON() + ", " +
334 "pp2filter = " + pp2filter + ", params = " + $.toJSON(params));
336 m_paz.search(m_query, m_perpage, m_sortOrder, pp2filter, undefined, params);
337 queue("searchtriggered").publish();
340 // fetch record details to be retrieved from the record queue
341 that.fetchDetails = function(recId) {
342 that.info("fetchDetails() requesting record '" + recId + "'");
347 // switching view between targets and records
348 function switchView(view) {
349 var targets = widgetNode('targets');
350 var results = widgetNode('results') || widgetNode('records');
351 var blanket = widgetNode('blanket');
352 var motd = widgetNode('motd');
356 if (targets) $(targets).show();
357 if (results) $(results).hide();
358 if (blanket) $(blanket).hide();
359 if (motd) $(motd).hide();
362 if (targets) $(targets).hide();
363 if (results) $(results).show();
364 if (blanket) $(blanket).show();
365 if (motd) $(motd).hide();
368 alert("Unknown view '" + view + "'");
371 that.switchView = switchView;
374 // detailed record drawing
375 that.showDetails = function(recId) {
376 var oldRecordId = m_currentRecordId;
377 m_currentRecordId = recId;
379 // remove current detailed view if any
380 findnode('#' + recordDetailsId(oldRecordId)).remove();
382 // if the same clicked, just hide
383 if (recId == oldRecordId) {
384 m_currentRecordId = '';
385 m_currentRecordData = null;
388 // request the record
389 that.info("showDetails() requesting record '" + recId + "'");
394 // Finds the node of the specified class within the current team
395 function findnode(selector, teamName) {
396 teamName = teamName || m_teamName;
398 if (teamName === 'AUTO') {
399 selector = (selector + '.mkws-team-' + teamName + ',' +
400 selector + ':not([class^="mkws-team"],[class*=" mkws-team"])');
402 selector = selector + '.mkws-team-' + teamName;
405 var node = $(selector);
406 //that.debug('findnode(' + selector + ') found ' + node.length + ' nodes');
411 function widgetNode(type) {
412 var w = that.widget(type);
413 return w ? w.node : undefined;
416 function renderDetails(data, marker) {
417 var template = loadTemplate("details");
418 var details = template(data);
419 return '<div class="mkws-details mkwsDetails mkwsTeam_' + m_teamName + '" ' +
420 'id="' + recordDetailsId(data.recid[0]) + '">' + details + '</div>';
422 that.renderDetails = renderDetails;
425 that.registerTemplate = function(name, text) {
426 if(mkws._old2new.hasOwnProperty(name)) {
427 that.warn("registerTemplate: old widget name: " + name + " => " + mkws._old2new[name]);
428 name = mkws._old2new[name];
430 m_templateText[name] = text;
434 function loadTemplate(name, fallbackString) {
435 if(mkws._old2new.hasOwnProperty(name)) {
436 that.warn("loadTemplate: old widget name: " + name + " => " + mkws._old2new[name]);
437 name = mkws._old2new[name];
440 var template = m_template[name];
441 if (template === undefined && Handlebars.compile) {
443 var node = $(".mkws-template-" + name + " .mkws-team-" + that.name());
444 if (node && node.length < 1) {
445 node = $(".mkws-template-" + name);
447 if (node) source = node.html();
448 if (!source) source = m_templateText[name];
450 template = Handlebars.compile(source);
451 that.info("compiled template '" + name + "'");
454 //if (template === undefined) template = mkws_templatesbyteam[m_teamName][name];
455 if (template === undefined && Handlebars.templates) {
456 template = Handlebars.templates["mkws-template-" + name];
458 if (template === undefined && mkws.defaultTemplates) {
459 template = mkws.defaultTemplates[name];
462 m_template[name] = template;
466 that.info("No MKWS template for " + name);
470 that.loadTemplate = loadTemplate;
473 that.addWidget = function(w) {
474 if (m_widgets[w.type] === undefined) {
475 m_widgets[w.type] = [ w ];
477 m_widgets[w.type].push(w);
481 that.widget = function(type) {
482 var list = m_widgets[type];
486 if (list.length > 1) {
487 alert("widget('" + type + "') finds " + list.length + " widgets: using first");
492 that.visitWidgets = function(callback) {
493 for (var type in m_widgets) {
494 var list = m_widgets[type];
495 for (var i = 0; i < list.length; i++) {
496 var res = callback(type, list[i]);
497 if (res !== undefined) {