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 // ### transitional placeholder function until we have promoted all invocations
92 that.log = function (x) { _log(mkws.log, x) };
94 that.trace = function(x) { _log(mkws.trace, x) };
95 that.debug = function(x) { _log(mkws.debug, x) };
96 that.info = function(x) { _log(mkws.info, x) };
97 that.warn = function(x) { _log(mkws.warn, x) };
98 that.error = function(x) { _log(mkws.error, x) };
99 that.fatal = function(x) { _log(mkws.fatal, x) };
101 that.info("making new widget team");
103 m_sortOrder = config.sort_default;
104 m_perpage = config.perpage_default;
106 // pz2.js event handlers:
113 function onBytarget(data) {
114 that.info("bytarget");
115 queue("targets").publish(data);
118 function onStat(data) {
119 queue("stat").publish(data);
120 var hitcount = parseInt(data.hits[0], 10);
121 if (!m_gotRecords && hitcount > 0) {
123 queue("firstrecords").publish(hitcount);
125 if (parseInt(data.activeclients[0], 10) === 0) {
126 that.info("complete");
127 queue("complete").publish(hitcount);
131 function onTerm(data) {
133 queue("facets").publish(data);
136 function onShow(data, teamName) {
138 m_totalRecordCount = data.merged;
139 that.info("found " + m_totalRecordCount + " records");
140 queue("pager").publish(data);
141 queue("records").publish(data);
144 function onRecord(data, args, teamName) {
146 // FIXME: record is async!!
147 clearTimeout(m_paz.recordTimer);
148 queue("record").publish(data);
149 var detRecordDiv = findnode(recordDetailsId(data.recid[0]));
150 if (detRecordDiv.length) {
151 // in case on_show was faster to redraw element
154 m_currentRecordData = data;
155 var recordDiv = findnode('.' + recordElementId(m_currentRecordData.recid[0]));
156 var html = renderDetails(m_currentRecordData);
157 $(recordDiv).append(html);
161 // create a parameters array and pass it to the pz2's constructor
162 // then register the form submit event with the pz2.search function
163 // autoInit is set to true on default
164 that.makePz2 = function() {
165 that.debug("m_queues=" + $.toJSON(m_queues));
167 "windowid": teamName,
168 "pazpar2path": mkws.pazpar2_url(),
169 "usesessions" : config.use_service_proxy ? false : true,
170 "showtime": 500, //each timer (show, stat, term, bytarget) can be specified this way
171 "termlist": config.facets.join(',')
174 params.oninit = onInit;
175 if (m_queues.targets) {
176 params.onbytarget = onBytarget;
177 that.info("setting bytarget callback");
180 params.onstat = onStat;
181 that.info("setting stat callback");
183 if (m_queues.facets && config.facets.length) {
184 params.onterm = onTerm;
185 that.info("setting term callback");
187 if (m_queues.records) {
188 that.info("setting show callback");
189 params.onshow = onShow;
190 // Record callback is subscribed from records callback
191 that.info("setting record callback");
192 params.onrecord = onRecord;
195 m_paz = new pz2(params);
196 that.info("created main pz2 object");
200 // Used by the Records widget and onRecord()
201 function recordElementId(s) {
202 return 'mkws-rec_' + s.replace(/[^a-z0-9]/ig, '_');
204 that.recordElementId = recordElementId;
206 // Used by onRecord(), showDetails() and renderDetails()
207 function recordDetailsId(s) {
208 return 'mkws-det_' + s.replace(/[^a-z0-9]/ig, '_');
212 that.targetFiltered = function(id) {
213 return m_filterSet.targetFiltered(id);
217 that.limitTarget = function(id, name) {
218 that.info("limitTarget(id=" + id + ", name=" + name + ")");
219 m_filterSet.add(targetFilter(id, name));
220 if (m_query) triggerSearch();
225 that.limitQuery = function(field, value) {
226 that.info("limitQuery(field=" + field + ", value=" + value + ")");
227 m_filterSet.add(fieldFilter(field, value));
228 if (m_query) triggerSearch();
233 that.limitCategory = function(id) {
234 that.info("limitCategory(id=" + id + ")");
235 // Only one category filter at a time
236 m_filterSet.removeMatching(function(f) { return f.type === 'category' });
237 if (id !== '') m_filterSet.add(categoryFilter(id));
238 if (m_query) triggerSearch();
243 that.delimitTarget = function(id) {
244 that.info("delimitTarget(id=" + id + ")");
245 m_filterSet.removeMatching(function(f) { return f.type === 'target' });
246 if (m_query) triggerSearch();
251 that.delimitQuery = function(field, value) {
252 that.info("delimitQuery(field=" + field + ", value=" + value + ")");
253 m_filterSet.removeMatching(function(f) { return f.type == 'field' &&
254 field == f.field && value == f.value });
255 if (m_query) triggerSearch();
260 that.showPage = function(pageNum) {
261 m_currentPage = pageNum;
262 m_paz.showPage(m_currentPage - 1);
266 that.pagerNext = function() {
267 if (m_totalRecordCount - m_perpage*m_currentPage > 0) {
274 that.pagerPrev = function() {
275 if (m_paz.showPrev() != false)
280 that.reShow = function() {
282 m_paz.show(0, m_perpage, m_sortOrder);
286 function resetPage() {
288 m_totalRecordCount = 0;
289 m_gotRecords = false;
291 that.resetPage = resetPage;
294 function newSearch(query, sortOrder, maxrecs, perpage, limit, targets, torusquery) {
295 that.info("newSearch: " + query);
297 if (config.use_service_proxy && !mkws.authenticated) {
298 alert("searching before authentication");
302 m_filterSet.removeMatching(function(f) { return f.type !== 'category' });
303 triggerSearch(query, sortOrder, maxrecs, perpage, limit, targets, torusquery);
304 switchView('records'); // In case it's configured to start off as hidden
307 that.newSearch = newSearch;
310 function triggerSearch(query, sortOrder, maxrecs, perpage, limit, targets, torusquery) {
312 queue("navi").publish();
314 // Continue to use previous query/sort-order unless new ones are specified
315 if (query) m_query = query;
316 if (sortOrder) m_sortOrder = sortOrder;
317 if (perpage) m_perpage = perpage;
318 if (targets) m_filterSet.add(targetFilter(targets, targets));
320 var pp2filter = m_filterSet.pp2filter();
321 var pp2limit = m_filterSet.pp2limit(limit);
322 var pp2catLimit = m_filterSet.pp2catLimit();
324 pp2filter = pp2filter ? pp2filter + "," + pp2catLimit : pp2catLimit;
328 if (pp2limit) params.limit = pp2limit;
329 if (maxrecs) params.maxrecs = maxrecs;
331 if (!mkws.config.use_service_proxy)
332 alert("can't narrow search by torusquery when not authenticated");
333 params.torusquery = torusquery;
336 that.info("triggerSearch(" + m_query + "): filters = " + m_filterSet.toJSON() + ", " +
337 "pp2filter = " + pp2filter + ", params = " + $.toJSON(params));
339 m_paz.search(m_query, m_perpage, m_sortOrder, pp2filter, undefined, params);
342 // fetch record details to be retrieved from the record queue
343 that.fetchDetails = function(recId) {
344 that.info("fetchDetails() requesting record '" + recId + "'");
349 // switching view between targets and records
350 function switchView(view) {
351 var targets = widgetNode('targets');
352 var results = widgetNode('results') || widgetNode('records');
353 var blanket = widgetNode('blanket');
354 var motd = widgetNode('motd');
358 if (targets) $(targets).show();
359 if (results) $(results).hide();
360 if (blanket) $(blanket).hide();
361 if (motd) $(motd).hide();
364 if (targets) $(targets).hide();
365 if (results) $(results).show();
366 if (blanket) $(blanket).show();
367 if (motd) $(motd).hide();
370 alert("Unknown view '" + view + "'");
373 that.switchView = switchView;
376 // detailed record drawing
377 that.showDetails = function(recId) {
378 var oldRecordId = m_currentRecordId;
379 m_currentRecordId = recId;
381 // remove current detailed view if any
382 findnode('#' + recordDetailsId(oldRecordId)).remove();
384 // if the same clicked, just hide
385 if (recId == oldRecordId) {
386 m_currentRecordId = '';
387 m_currentRecordData = null;
390 // request the record
391 that.info("showDetails() requesting record '" + recId + "'");
396 // Finds the node of the specified class within the current team
397 function findnode(selector, teamName) {
398 teamName = teamName || m_teamName;
400 if (teamName === 'AUTO') {
401 selector = (selector + '.mkws-team-' + teamName + ',' +
402 selector + ':not([class^="mkws-team"],[class*=" mkws-team"])');
404 selector = selector + '.mkws-team-' + teamName;
407 var node = $(selector);
408 //that.debug('findnode(' + selector + ') found ' + node.length + ' nodes');
413 function widgetNode(type) {
414 var w = that.widget(type);
415 return w ? w.node : undefined;
418 function renderDetails(data, marker) {
419 var template = loadTemplate("details");
420 var details = template(data);
421 return '<div class="mkws-details mkwsDetails mkwsTeam_' + m_teamName + '" ' +
422 'id="' + recordDetailsId(data.recid[0]) + '">' + details + '</div>';
424 that.renderDetails = renderDetails;
427 that.registerTemplate = function(name, text) {
428 if(mkws._old2new.hasOwnProperty(name)) {
429 that.warn("Warning: registerTemplate old widget name: " + name + " => " + mkws._old2new[name]);
430 name = mkws._old2new[name];
432 m_templateText[name] = text;
436 function loadTemplate(name, fallbackString) {
437 if(mkws._old2new.hasOwnProperty(name)) {
438 that.warn("Warning loadTemplate: old widget name: " + name + " => " + mkws._old2new[name]);
439 name = mkws._old2new[name];
442 var template = m_template[name];
443 if (template === undefined && Handlebars.compile) {
445 var node = $(".mkws-template-" + name + " .mkws-team-" + that.name());
446 if (node && node.length < 1) {
447 node = $(".mkws-template-" + name);
449 if (node) source = node.html();
450 if (!source) source = m_templateText[name];
452 template = Handlebars.compile(source);
453 that.info("compiled template '" + name + "'");
456 //if (template === undefined) template = mkws_templatesbyteam[m_teamName][name];
457 if (template === undefined && Handlebars.templates) {
458 template = Handlebars.templates["mkws-template-" + name];
460 if (template === undefined && mkws.defaultTemplates) {
461 template = mkws.defaultTemplates[name];
464 m_template[name] = template;
468 that.info("No MKWS template for " + name);
472 that.loadTemplate = loadTemplate;
475 that.addWidget = function(w) {
476 if (m_widgets[w.type] === undefined) {
477 m_widgets[w.type] = [ w ];
479 m_widgets[w.type].push(w);
483 that.widget = function(type) {
484 var list = m_widgets[type];
488 if (list.length > 1) {
489 alert("widget('" + type + "') finds " + list.length + " widgets: using first");
494 that.visitWidgets = function(callback) {
495 for (var type in m_widgets) {
496 var list = m_widgets[type];
497 for (var i = 0; i < list.length; i++) {
498 var res = callback(type, list[i]);
499 if (res !== undefined) {