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(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");
299 m_filterSet.removeMatching(function(f) { return f.type !== 'category' });
300 triggerSearch(query, sortOrder, maxrecs, perpage, limit, targets, torusquery);
301 switchView('records'); // In case it's configured to start off as hidden
304 that.newSearch = newSearch;
307 function triggerSearch(query, sortOrder, maxrecs, perpage, limit, targets, torusquery) {
310 // Continue to use previous query/sort-order unless new ones are specified
311 if (query) m_query = query;
312 if (sortOrder) m_sortOrder = sortOrder;
313 if (perpage) m_perpage = perpage;
314 if (targets) m_filterSet.add(targetFilter(targets, targets));
316 var pp2filter = m_filterSet.pp2filter();
317 var pp2limit = m_filterSet.pp2limit(limit);
318 var pp2catLimit = m_filterSet.pp2catLimit();
320 pp2filter = pp2filter ? pp2filter + "," + pp2catLimit : pp2catLimit;
324 if (pp2limit) params.limit = pp2limit;
325 if (maxrecs) params.maxrecs = maxrecs;
327 if (!mkws.config.use_service_proxy)
328 alert("can't narrow search by torusquery when not authenticated");
329 params.torusquery = torusquery;
332 that.info("triggerSearch(" + m_query + "): filters = " + m_filterSet.toJSON() + ", " +
333 "pp2filter = " + pp2filter + ", params = " + $.toJSON(params));
335 m_paz.search(m_query, m_perpage, m_sortOrder, pp2filter, undefined, params);
336 queue("searchtriggered").publish();
339 // fetch record details to be retrieved from the record queue
340 that.fetchDetails = function(recId) {
341 that.info("fetchDetails() requesting record '" + recId + "'");
346 // switching view between targets and records
347 function switchView(view) {
348 var targets = widgetNode('targets');
349 var results = widgetNode('results') || widgetNode('records');
350 var blanket = widgetNode('blanket');
351 var motd = widgetNode('motd');
355 if (targets) $(targets).show();
356 if (results) $(results).hide();
357 if (blanket) $(blanket).hide();
358 if (motd) $(motd).hide();
361 if (targets) $(targets).hide();
362 if (results) $(results).show();
363 if (blanket) $(blanket).show();
364 if (motd) $(motd).hide();
367 alert("Unknown view '" + view + "'");
370 that.switchView = switchView;
373 // detailed record drawing
374 that.showDetails = function(recId) {
375 var oldRecordId = m_currentRecordId;
376 m_currentRecordId = recId;
378 // remove current detailed view if any
379 findnode('#' + recordDetailsId(oldRecordId)).remove();
381 // if the same clicked, just hide
382 if (recId == oldRecordId) {
383 m_currentRecordId = '';
384 m_currentRecordData = null;
387 // request the record
388 that.info("showDetails() requesting record '" + recId + "'");
393 // Finds the node of the specified class within the current team
394 function findnode(selector, teamName) {
395 teamName = teamName || m_teamName;
397 if (teamName === 'AUTO') {
398 selector = (selector + '.mkws-team-' + teamName + ',' +
399 selector + ':not([class^="mkws-team"],[class*=" mkws-team"])');
401 selector = selector + '.mkws-team-' + teamName;
404 var node = $(selector);
405 //that.debug('findnode(' + selector + ') found ' + node.length + ' nodes');
410 function widgetNode(type) {
411 var w = that.widget(type);
412 return w ? w.node : undefined;
415 function renderDetails(data, marker) {
416 var template = loadTemplate("details");
417 var details = template(data);
418 return '<div class="mkws-details mkwsDetails mkwsTeam_' + m_teamName + '" ' +
419 'id="' + recordDetailsId(data.recid[0]) + '">' + details + '</div>';
421 that.renderDetails = renderDetails;
424 that.registerTemplate = function(name, text) {
425 if(mkws._old2new.hasOwnProperty(name)) {
426 that.warn("registerTemplate: old widget name: " + name + " => " + mkws._old2new[name]);
427 name = mkws._old2new[name];
429 m_templateText[name] = text;
433 function loadTemplate(name, fallbackString) {
434 if(mkws._old2new.hasOwnProperty(name)) {
435 that.warn("loadTemplate: old widget name: " + name + " => " + mkws._old2new[name]);
436 name = mkws._old2new[name];
439 var template = m_template[name];
440 if (template === undefined && Handlebars.compile) {
442 var node = $(".mkws-template-" + name + " .mkws-team-" + that.name());
443 if (node && node.length < 1) {
444 node = $(".mkws-template-" + name);
446 if (node) source = node.html();
447 if (!source) source = m_templateText[name];
449 template = Handlebars.compile(source);
450 that.info("compiled template '" + name + "'");
453 //if (template === undefined) template = mkws_templatesbyteam[m_teamName][name];
454 if (template === undefined && Handlebars.templates) {
455 template = Handlebars.templates["mkws-template-" + name];
457 if (template === undefined && mkws.defaultTemplates) {
458 template = mkws.defaultTemplates[name];
461 m_template[name] = template;
465 that.info("No MKWS template for " + name);
469 that.loadTemplate = loadTemplate;
472 that.addWidget = function(w) {
473 if (m_widgets[w.type] === undefined) {
474 m_widgets[w.type] = [ w ];
476 m_widgets[w.type].push(w);
480 that.widget = function(type) {
481 var list = m_widgets[type];
485 if (list.length > 1) {
486 alert("widget('" + type + "') finds " + list.length + " widgets: using first");
491 that.visitWidgets = function(callback) {
492 for (var type in m_widgets) {
493 var list = m_widgets[type];
494 for (var i = 0; i < list.length; i++) {
495 var res = callback(type, list[i]);
496 if (res !== undefined) {