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
24 var m_sortOrder; // will be set below
25 var m_perpage; // will be set below
26 var m_filterSet = filterSet(that);
27 var m_currentPage = 1;
28 var m_currentRecordId = '';
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_sortOrder; };
55 that.perpage = function() { return m_perpage; };
56 that.query = function() { return m_state.query; };
57 that.totalRecordCount = function() { return m_totalRecordCount; };
58 that.currentPage = function() { return m_currentPage; };
59 that.currentRecordId = function() { return m_currentRecordId; };
60 that.currentRecordData = function() { return m_currentRecordData; };
61 that.filters = function() { return m_filterSet; };
62 that.gotRecords = function() { return m_gotRecords; };
64 // Accessor methods for individual widgets: writers
65 that.set_sortOrder = function(val) { m_sortOrder = val };
66 that.set_perpage = function(val) { m_perpage = val };
69 // The following PubSub code is modified from the jQuery manual:
70 // http://api.jquery.com/jQuery.Callbacks/
73 // team.queue("eventName").subscribe(function(param1, param2 ...) { ... });
74 // team.queue("eventName").publish(arg1, arg2, ...);
79 var callbacks = $.Callbacks();
81 publish: callbacks.fire,
82 subscribe: callbacks.add,
83 unsubscribe: callbacks.remove
91 function _log(fn, s) {
93 var timestamp = (((now - m_logTime.start)/1000).toFixed(3) + " (+" +
94 ((now - m_logTime.last)/1000).toFixed(3) + ") ");
96 fn.call(mkws.log, m_teamName + ": " + timestamp + s);
97 that.queue("log").publish(m_teamName, timestamp, s);
100 that.trace = function(x) { _log(mkws.trace, x) };
101 that.debug = function(x) { _log(mkws.debug, x) };
102 that.info = function(x) { _log(mkws.info, x) };
103 that.warn = function(x) { _log(mkws.warn, x) };
104 that.error = function(x) { _log(mkws.error, x) };
105 that.fatal = function(x) { _log(mkws.fatal, x) };
107 that.info("making new widget team");
109 m_sortOrder = config.sort_default;
110 m_perpage = config.perpage_default;
112 // pz2.js event handlers:
119 function onBytarget(data) {
120 that.info("bytarget");
121 queue("targets").publish(data);
124 function onStat(data) {
125 queue("stat").publish(data);
126 var hitcount = parseInt(data.hits[0], 10);
127 if (!m_gotRecords && hitcount > 0) {
129 queue("firstrecords").publish(hitcount);
131 if (parseInt(data.activeclients[0], 10) === 0) {
132 that.info("complete");
133 queue("complete").publish(hitcount);
137 function onTerm(data) {
139 queue("facets").publish(data);
142 function onShow(data, teamName) {
144 m_totalRecordCount = data.merged;
145 that.info("found " + m_totalRecordCount + " records");
146 queue("pager").publish(data);
147 queue("records").publish(data);
150 function onRecord(data, args, teamName) {
152 // FIXME: record is async!!
153 clearTimeout(m_paz.recordTimer);
154 queue("record").publish(data);
155 var detRecordDiv = findnode(recordDetailsId(data.recid[0]));
156 if (detRecordDiv.length) {
157 // in case on_show was faster to redraw element
160 m_currentRecordData = data;
161 var recordDiv = findnode('.' + recordElementId(m_currentRecordData.recid[0]));
162 var html = renderDetails(m_currentRecordData);
163 $(recordDiv).append(html);
167 // create a parameters array and pass it to the pz2's constructor
168 // then register the form submit event with the pz2.search function
169 // autoInit is set to true on default
170 that.makePz2 = function() {
171 that.debug("m_queues=" + $.toJSON(m_queues));
173 "windowid": teamName,
174 "pazpar2path": mkws.pazpar2_url(),
175 "usesessions" : config.use_service_proxy ? false : true,
176 "showtime": 500, //each timer (show, stat, term, bytarget) can be specified this way
177 "termlist": config.facets.join(',')
180 params.oninit = onInit;
181 if (m_queues.targets) {
182 params.onbytarget = onBytarget;
183 that.info("setting bytarget callback");
185 if (m_queues.stat || m_queues.firstrecords || m_queues.complete) {
186 params.onstat = onStat;
187 that.info("setting stat callback");
189 if (m_queues.facets && config.facets.length) {
190 params.onterm = onTerm;
191 that.info("setting term callback");
193 if (m_queues.records) {
194 that.info("setting show callback");
195 params.onshow = onShow;
196 // Record callback is subscribed from records callback
197 that.info("setting record callback");
198 params.onrecord = onRecord;
201 m_paz = new pz2(params);
202 that.info("created main pz2 object");
206 // Used by the Records widget and onRecord()
207 function recordElementId(s) {
208 return 'mkws-rec_' + s.replace(/[^a-z0-9]/ig, '_');
210 that.recordElementId = recordElementId;
212 // Used by onRecord(), showDetails() and renderDetails()
213 function recordDetailsId(s) {
214 return 'mkws-det_' + s.replace(/[^a-z0-9]/ig, '_');
218 that.targetFiltered = function(id) {
219 return m_filterSet.targetFiltered(id);
223 that.limitTarget = function(id, name) {
224 that.info("limitTarget(id=" + id + ", name=" + name + ")");
225 m_filterSet.add(targetFilter(id, name));
226 if (m_state.query) triggerSearch();
231 that.limitQuery = function(field, value) {
232 that.info("limitQuery(field=" + field + ", value=" + value + ")");
233 m_filterSet.add(fieldFilter(field, value));
234 if (m_state.query) triggerSearch();
239 that.limitCategory = function(id) {
240 that.info("limitCategory(id=" + id + ")");
241 // Only one category filter at a time
242 m_filterSet.removeMatching(function(f) { return f.type === 'category' });
243 if (id !== '') m_filterSet.add(categoryFilter(id));
244 if (m_state.query) triggerSearch();
249 that.delimitTarget = function(id) {
250 that.info("delimitTarget(id=" + id + ")");
251 m_filterSet.removeMatching(function(f) { return f.type === 'target' });
252 if (m_state.query) triggerSearch();
257 that.delimitQuery = function(field, value) {
258 that.info("delimitQuery(field=" + field + ", value=" + value + ")");
259 m_filterSet.removeMatching(function(f) { return f.type == 'field' &&
260 field == f.field && value == f.value });
261 if (m_state.query) triggerSearch();
266 that.showPage = function(pageNum) {
267 m_currentPage = pageNum;
268 m_paz.showPage(m_currentPage - 1);
272 that.pagerNext = function() {
273 if (m_totalRecordCount - m_perpage*m_currentPage > 0) {
280 that.pagerPrev = function() {
281 if (m_paz.showPrev() != false)
286 that.reShow = function() {
288 m_paz.show(0, m_perpage, m_sortOrder);
292 function resetPage() {
294 m_totalRecordCount = 0;
295 m_gotRecords = false;
297 that.resetPage = resetPage;
300 function newSearch(query, sortOrder, maxrecs, perpage, limit, targets, torusquery) {
301 that.info("newSearch: " + query);
303 if (config.use_service_proxy && !mkws.authenticated) {
304 alert("searching before authentication");
308 m_filterSet.removeMatching(function(f) { return f.type !== 'category' });
309 triggerSearch(query, sortOrder, maxrecs, perpage, limit, targets, torusquery);
310 switchView('records'); // In case it's configured to start off as hidden
313 that.newSearch = newSearch;
316 function triggerSearch(query, sortOrder, maxrecs, perpage, limit, targets, torusquery) {
319 // Continue to use previous query/sort-order unless new ones are specified
320 if (query) m_state.query = query;
321 if (sortOrder) m_sortOrder = sortOrder;
322 if (perpage) m_perpage = perpage;
323 if (targets) m_filterSet.add(targetFilter(targets, targets));
325 var pp2filter = m_filterSet.pp2filter();
326 var pp2limit = m_filterSet.pp2limit(limit);
327 var pp2catLimit = m_filterSet.pp2catLimit();
329 pp2filter = pp2filter ? pp2filter + "," + pp2catLimit : pp2catLimit;
333 if (pp2limit) params.limit = pp2limit;
334 if (maxrecs) params.maxrecs = maxrecs;
336 if (!mkws.config.use_service_proxy)
337 alert("can't narrow search by torusquery when not authenticated");
338 params.torusquery = torusquery;
341 that.info("triggerSearch(" + m_state.query + "): filters = " + m_filterSet.toJSON() + ", " +
342 "pp2filter = " + pp2filter + ", params = " + $.toJSON(params));
344 m_paz.search(m_state.query, m_perpage, m_sortOrder, pp2filter, undefined, params);
345 queue("searchtriggered").publish();
348 // fetch record details to be retrieved from the record queue
349 that.fetchDetails = function(recId) {
350 that.info("fetchDetails() requesting record '" + recId + "'");
355 // switching view between targets and records
356 function switchView(view) {
357 var targets = widgetNode('targets');
358 var results = widgetNode('results') || widgetNode('records');
359 var blanket = widgetNode('blanket');
360 var motd = widgetNode('motd');
364 if (targets) $(targets).show();
365 if (results) $(results).hide();
366 if (blanket) $(blanket).hide();
367 if (motd) $(motd).hide();
370 if (targets) $(targets).hide();
371 if (results) $(results).show();
372 if (blanket) $(blanket).show();
373 if (motd) $(motd).hide();
376 alert("Unknown view '" + view + "'");
379 that.switchView = switchView;
382 // detailed record drawing
383 that.showDetails = function(recId) {
384 var oldRecordId = m_currentRecordId;
385 m_currentRecordId = recId;
387 // remove current detailed view if any
388 findnode('#' + recordDetailsId(oldRecordId)).remove();
390 // if the same clicked, just hide
391 if (recId == oldRecordId) {
392 m_currentRecordId = '';
393 m_currentRecordData = null;
396 // request the record
397 that.info("showDetails() requesting record '" + recId + "'");
402 // Finds the node of the specified class within the current team
403 function findnode(selector, teamName) {
404 teamName = teamName || m_teamName;
406 if (teamName === 'AUTO') {
407 selector = (selector + '.mkws-team-' + teamName + ',' +
408 selector + ':not([class^="mkws-team"],[class*=" mkws-team"])');
410 selector = selector + '.mkws-team-' + teamName;
413 var node = $(selector);
414 //that.debug('findnode(' + selector + ') found ' + node.length + ' nodes');
419 function widgetNode(type) {
420 var w = that.widget(type);
421 return w ? w.node : undefined;
424 function renderDetails(data, marker) {
425 var template = loadTemplate("details");
426 var details = template(data);
427 return '<div class="mkws-details mkwsDetails mkwsTeam_' + m_teamName + '" ' +
428 'id="' + recordDetailsId(data.recid[0]) + '">' + details + '</div>';
430 that.renderDetails = renderDetails;
433 that.registerTemplate = function(name, text) {
434 if(mkws._old2new.hasOwnProperty(name)) {
435 that.warn("registerTemplate: old widget name: " + name + " => " + mkws._old2new[name]);
436 name = mkws._old2new[name];
438 m_templateText[name] = text;
442 function loadTemplate(name, fallbackString) {
443 if(mkws._old2new.hasOwnProperty(name)) {
444 that.warn("loadTemplate: old widget name: " + name + " => " + mkws._old2new[name]);
445 name = mkws._old2new[name];
448 var template = m_template[name];
449 if (template === undefined && Handlebars.compile) {
451 var node = $(".mkws-template-" + name + " .mkws-team-" + that.name());
452 if (node && node.length < 1) {
453 node = $(".mkws-template-" + name);
455 if (node) source = node.html();
456 if (!source) source = m_templateText[name];
458 template = Handlebars.compile(source);
459 that.info("compiled template '" + name + "'");
462 //if (template === undefined) template = mkws_templatesbyteam[m_teamName][name];
463 if (template === undefined && Handlebars.templates) {
464 template = Handlebars.templates["mkws-template-" + name];
466 if (template === undefined && mkws.defaultTemplates) {
467 template = mkws.defaultTemplates[name];
470 m_template[name] = template;
474 that.info("No MKWS template for " + name);
478 that.loadTemplate = loadTemplate;
481 that.addWidget = function(w) {
482 if (m_widgets[w.type] === undefined) {
483 m_widgets[w.type] = [ w ];
485 m_widgets[w.type].push(w);
489 that.widget = function(type) {
490 var list = m_widgets[type];
494 if (list.length > 1) {
495 alert("widget('" + type + "') finds " + list.length + " widgets: using first");
500 that.visitWidgets = function(callback) {
501 for (var type in m_widgets) {
502 var list = m_widgets[type];
503 for (var i = 0; i < list.length; i++) {
504 var res = callback(type, list[i]);
505 if (res !== undefined) {