2 // Factory function for team objects. As much as possible, this uses
3 // only member variables (prefixed "m_") and inner functions with
6 // Some functions are visible as member-functions to be called from
7 // outside code -- specifically, from generated HTML. These functions
8 // are that.switchView(), showDetails(), limitTarget(), limitQuery(),
9 // limitCategory(), delimitTarget(), delimitQuery(), showPage(),
10 // pagerPrev(), pagerNext().
12 // Before the team can be used for searching and related operations,
13 // its pz2 object must be created by calling team.makePz2().
15 mkws.makeTeam = function($, teamName) {
18 // Member variables are separated into two categories
20 // 1. Persistent state (to be coded in URL fragment)
22 query: null, // initially undefined
23 sort: null, // will be set below
24 size: null, // will be set below
27 filters: filterSet(that)
30 // 2. Internal state (not to be coded)
31 var m_teamName = teamName;
32 var m_paz; // will be initialised below
33 var m_submitted = false;
34 var m_totalRecordCount = 0;
35 var m_currentRecordData = null;
37 // Timestamps for logging
41 var m_templateText = {}; // widgets can register templates to be compiled
42 var m_template = {}; // compiled templates, from any source
43 var m_widgets = {}; // Maps widget-type to array of widget objects
44 var m_gotRecords = false;
46 var config = mkws.objectInheritingFrom(mkws.config);
49 that.toString = function() { return '[Team ' + teamName + ']'; };
51 // Accessor methods for individual widgets: readers
52 that.name = function() { return m_teamName; };
53 that.submitted = function() { return m_submitted; };
54 that.sortOrder = function() { return m_state.sort; };
55 that.perpage = function() { return m_state.size; };
56 that.query = function() { return m_state.query; };
57 that.totalRecordCount = function() { return m_totalRecordCount; };
58 that.currentPage = function() { return m_state.page; };
59 that.currentRecordId = function() { return m_state.recid; };
60 that.currentRecordData = function() { return m_currentRecordData; };
61 that.filters = function() { return m_state.filters; };
62 that.gotRecords = function() { return m_gotRecords; };
64 // Accessor methods for individual widgets: writers
65 that.set_sortOrder = function(val) { m_state.sort = val };
66 that.set_perpage = function(val) { m_state.size = val };
68 m_state.sort = config.sort_default;
69 m_state.size = config.perpage_default;
71 var m_default = $.extend(true, {}, m_state);
72 var tmp = m_default.filters;
73 delete m_default.filters;
74 $.extend(m_default, tmp.fragmentItems());
76 that.urlFragment = function(overrides) {
79 that.warn("making urlFragment with overrides " + mkws.$.toJSON(overrides));
80 // Expand the filterSet into a set of key=value properties
81 var state = $.extend(true, {}, m_state, overrides ? overrides : {});
82 var tmp = state.filters;
84 $.extend(state, tmp.fragmentItems());
86 for (var key in state) {
87 if (state.hasOwnProperty(key) &&
88 state[key] != m_default[key]) {
91 if (m_teamName !== 'AUTO') s += m_teamName;
97 // ### how do we need to quote this?
98 s += key + '=' + state[key];
106 // The following PubSub code is modified from the jQuery manual:
107 // http://api.jquery.com/jQuery.Callbacks/
110 // team.queue("eventName").subscribe(function(param1, param2 ...) { ... });
111 // team.queue("eventName").publish(arg1, arg2, ...);
116 var callbacks = $.Callbacks();
118 publish: callbacks.fire,
119 subscribe: callbacks.add,
120 unsubscribe: callbacks.remove
128 function _log(fn, s) {
130 var timestamp = (((now - m_logTime.start)/1000).toFixed(3) + " (+" +
131 ((now - m_logTime.last)/1000).toFixed(3) + ") ");
132 m_logTime.last = now;
133 fn.call(mkws.log, m_teamName + ": " + timestamp + s);
134 that.queue("log").publish(m_teamName, timestamp, s);
137 that.trace = function(x) { _log(mkws.trace, x) };
138 that.debug = function(x) { _log(mkws.debug, x) };
139 that.info = function(x) { _log(mkws.info, x) };
140 that.warn = function(x) { _log(mkws.warn, x) };
141 that.error = function(x) { _log(mkws.error, x) };
142 that.fatal = function(x) { _log(mkws.fatal, x) };
144 that.info("making new widget team");
146 // pz2.js event handlers:
153 function onBytarget(data) {
154 that.info("bytarget");
155 queue("targets").publish(data);
158 function onStat(data) {
159 queue("stat").publish(data);
160 var hitcount = parseInt(data.hits[0], 10);
161 if (!m_gotRecords && hitcount > 0) {
163 queue("firstrecords").publish(hitcount);
165 if (parseInt(data.activeclients[0], 10) === 0) {
166 that.info("complete");
167 queue("complete").publish(hitcount);
171 function onTerm(data) {
173 queue("facets").publish(data);
176 function onShow(data, teamName) {
178 m_totalRecordCount = data.merged;
179 that.info("found " + m_totalRecordCount + " records");
180 queue("pager").publish(data);
181 queue("records").publish(data);
184 function onRecord(data, args, teamName) {
186 // FIXME: record is async!!
187 clearTimeout(m_paz.recordTimer);
188 queue("record").publish(data);
189 var detRecordDiv = findnode(recordDetailsId(data.recid[0]));
190 if (detRecordDiv.length) {
191 // in case on_show was faster to redraw element
194 m_currentRecordData = data;
195 var recordDiv = findnode('.' + recordElementId(m_currentRecordData.recid[0]));
196 var html = renderDetails(m_currentRecordData);
197 $(recordDiv).append(html);
201 // create a parameters array and pass it to the pz2's constructor
202 // then register the form submit event with the pz2.search function
203 // autoInit is set to true on default
204 that.makePz2 = function() {
205 that.debug("m_queues=" + $.toJSON(m_queues));
207 "windowid": teamName,
208 "pazpar2path": mkws.pazpar2_url(),
209 "usesessions" : config.use_service_proxy ? false : true,
210 "showtime": 500, //each timer (show, stat, term, bytarget) can be specified this way
211 "termlist": config.facets.join(',')
214 params.oninit = onInit;
215 if (m_queues.targets) {
216 params.onbytarget = onBytarget;
217 that.info("setting bytarget callback");
219 if (m_queues.stat || m_queues.firstrecords || m_queues.complete) {
220 params.onstat = onStat;
221 that.info("setting stat callback");
223 if (m_queues.facets && config.facets.length) {
224 params.onterm = onTerm;
225 that.info("setting term callback");
227 if (m_queues.records) {
228 that.info("setting show callback");
229 params.onshow = onShow;
230 // Record callback is subscribed from records callback
231 that.info("setting record callback");
232 params.onrecord = onRecord;
235 m_paz = new pz2(params);
236 that.info("created main pz2 object");
240 // Used by the Records widget and onRecord()
241 function recordElementId(s) {
242 return 'mkws-rec_' + s.replace(/[^a-z0-9]/ig, '_');
244 that.recordElementId = recordElementId;
246 // Used by onRecord(), showDetails() and renderDetails()
247 function recordDetailsId(s) {
248 return 'mkws-det_' + s.replace(/[^a-z0-9]/ig, '_');
252 that.targetFiltered = function(id) {
253 return m_state.filters.targetFiltered(id);
257 that.limitTarget = function(id, name) {
258 that.info("limitTarget(id=" + id + ", name=" + name + ")");
259 m_state.filters.add(targetFilter(id, name));
260 if (m_state.query) triggerSearch();
265 that.limitQuery = function(field, value) {
266 that.info("limitQuery(field=" + field + ", value=" + value + ")");
267 m_state.filters.add(fieldFilter(field, value));
268 if (m_state.query) triggerSearch();
273 that.limitCategory = function(id) {
274 that.info("limitCategory(id=" + id + ")");
275 // Only one category filter at a time
276 m_state.filters.removeMatching(function(f) { return f.type === 'category' });
277 if (id !== '') m_state.filters.add(categoryFilter(id));
278 if (m_state.query) triggerSearch();
283 that.delimitTarget = function(id) {
284 that.info("delimitTarget(id=" + id + ")");
285 m_state.filters.removeMatching(function(f) { return f.type === 'target' });
286 if (m_state.query) triggerSearch();
291 that.delimitQuery = function(field, value) {
292 that.info("delimitQuery(field=" + field + ", value=" + value + ")");
293 m_state.filters.removeMatching(function(f) { return f.type == 'field' &&
294 field == f.field && value == f.value });
295 if (m_state.query) triggerSearch();
300 that.showPage = function(pageNum) {
301 m_state.page = pageNum;
302 m_paz.showPage(m_state.page - 1);
303 that.warn("fragment: " + that.urlFragment());
307 that.pagerNext = function() {
308 if (m_totalRecordCount - m_state.size * m_state.page > 0) {
311 that.warn("fragment: " + that.urlFragment());
316 that.pagerPrev = function() {
317 if (m_paz.showPrev() != false) {
319 that.warn("fragment: " + that.urlFragment());
324 that.reShow = function() {
326 m_paz.show(0, m_state.size, m_state.sort);
327 // ### not really the right place for this but it will do for now.
328 that.warn("fragment: " + that.urlFragment());
332 function resetPage() {
334 m_totalRecordCount = 0;
335 m_gotRecords = false;
337 that.resetPage = resetPage;
340 function newSearch(query, sortOrder, maxrecs, perpage, limit, targets, torusquery) {
341 that.info("newSearch: " + query);
343 if (config.use_service_proxy && !mkws.authenticated) {
344 alert("searching before authentication");
348 m_state.filters.removeMatching(function(f) { return f.type !== 'category' });
349 triggerSearch(query, sortOrder, maxrecs, perpage, limit, targets, torusquery);
350 switchView('records'); // In case it's configured to start off as hidden
353 that.newSearch = newSearch;
356 function triggerSearch(query, sortOrder, maxrecs, perpage, limit, targets, torusquery) {
359 // Continue to use previous query/sort-order unless new ones are specified
360 if (query) m_state.query = query;
361 if (sortOrder) m_state.sort = sortOrder;
362 if (perpage) m_state.size = perpage;
363 if (targets) m_state.filters.add(targetFilter(targets, targets));
365 var pp2filter = m_state.filters.pp2filter();
366 var pp2limit = m_state.filters.pp2limit(limit);
367 var pp2catLimit = m_state.filters.pp2catLimit();
369 pp2filter = pp2filter ? pp2filter + "," + pp2catLimit : pp2catLimit;
373 if (pp2limit) params.limit = pp2limit;
374 if (maxrecs) params.maxrecs = maxrecs;
376 if (!mkws.config.use_service_proxy)
377 alert("can't narrow search by torusquery when not authenticated");
378 params.torusquery = torusquery;
381 that.info("triggerSearch(" + m_state.query + "): filters = " + m_state.filters.toJSON() + ", " +
382 "pp2filter = " + pp2filter + ", params = " + $.toJSON(params));
384 m_paz.search(m_state.query, m_state.size, m_state.sort, pp2filter, undefined, params);
385 queue("searchtriggered").publish();
387 // ### not really the right place for this but it will do for now.
388 that.warn("fragment: " + that.urlFragment());
391 // fetch record details to be retrieved from the record queue
392 that.fetchDetails = function(recId) {
393 that.info("fetchDetails() requesting record '" + recId + "'");
395 that.warn("fragment: " + that.urlFragment());
399 // switching view between targets and records
400 function switchView(view) {
401 var targets = widgetNode('targets');
402 var results = widgetNode('results') || widgetNode('records');
403 var blanket = widgetNode('blanket');
404 var motd = widgetNode('motd');
408 if (targets) $(targets).show();
409 if (results) $(results).hide();
410 if (blanket) $(blanket).hide();
411 if (motd) $(motd).hide();
414 if (targets) $(targets).hide();
415 if (results) $(results).show();
416 if (blanket) $(blanket).show();
417 if (motd) $(motd).hide();
420 alert("Unknown view '" + view + "'");
423 that.switchView = switchView;
426 // detailed record drawing
427 that.showDetails = function(recId) {
428 var oldRecordId = m_state.recid;
429 m_state.recid = recId;
431 // remove current detailed view if any
432 findnode('#' + recordDetailsId(oldRecordId)).remove();
434 // if the same clicked, just hide
435 if (recId == oldRecordId) {
437 m_currentRecordData = null;
440 // request the record
441 that.info("showDetails() requesting record '" + recId + "'");
446 // Finds the node of the specified class within the current team
447 function findnode(selector, teamName) {
448 teamName = teamName || m_teamName;
450 if (teamName === 'AUTO') {
451 selector = (selector + '.mkws-team-' + teamName + ',' +
452 selector + ':not([class^="mkws-team"],[class*=" mkws-team"])');
454 selector = selector + '.mkws-team-' + teamName;
457 var node = $(selector);
458 //that.debug('findnode(' + selector + ') found ' + node.length + ' nodes');
463 function widgetNode(type) {
464 var w = that.widget(type);
465 return w ? w.node : undefined;
468 function renderDetails(data, marker) {
469 var template = loadTemplate("details");
470 var details = template(data);
471 return '<div class="mkws-details mkwsDetails mkwsTeam_' + m_teamName + '" ' +
472 'id="' + recordDetailsId(data.recid[0]) + '">' + details + '</div>';
474 that.renderDetails = renderDetails;
477 that.registerTemplate = function(name, text) {
478 if(mkws._old2new.hasOwnProperty(name)) {
479 that.warn("registerTemplate: old widget name: " + name + " => " + mkws._old2new[name]);
480 name = mkws._old2new[name];
482 m_templateText[name] = text;
486 function loadTemplate(name, fallbackString) {
487 if(mkws._old2new.hasOwnProperty(name)) {
488 that.warn("loadTemplate: old widget name: " + name + " => " + mkws._old2new[name]);
489 name = mkws._old2new[name];
492 var template = m_template[name];
493 if (template === undefined && Handlebars.compile) {
495 var node = $(".mkws-template-" + name + " .mkws-team-" + that.name());
496 if (node && node.length < 1) {
497 node = $(".mkws-template-" + name);
499 if (node) source = node.html();
500 if (!source) source = m_templateText[name];
502 template = Handlebars.compile(source);
503 that.info("compiled template '" + name + "'");
506 //if (template === undefined) template = mkws_templatesbyteam[m_teamName][name];
507 if (template === undefined && Handlebars.templates) {
508 template = Handlebars.templates["mkws-template-" + name];
510 if (template === undefined && mkws.defaultTemplates) {
511 template = mkws.defaultTemplates[name];
514 m_template[name] = template;
518 that.info("No MKWS template for " + name);
522 that.loadTemplate = loadTemplate;
525 that.addWidget = function(w) {
526 if (m_widgets[w.type] === undefined) {
527 m_widgets[w.type] = [ w ];
529 m_widgets[w.type].push(w);
533 that.widget = function(type) {
534 var list = m_widgets[type];
538 if (list.length > 1) {
539 alert("widget('" + type + "') finds " + list.length + " widgets: using first");
544 that.visitWidgets = function(callback) {
545 for (var type in m_widgets) {
546 var list = m_widgets[type];
547 for (var i = 0; i < list.length; i++) {
548 var res = callback(type, list[i]);
549 if (res !== undefined) {