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 function team($, teamName) {
13 var m_teamName = teamName;
14 var m_submitted = false;
15 var m_query; // initially undefined
16 var m_sortOrder; // will be set below
17 var m_perpage; // will be set below
18 var m_filterSet = filterSet(that);
19 var m_totalRecordCount = 0;
20 var m_currentPage = 1;
21 var m_currentRecordId = '';
22 var m_currentRecordData = null;
24 // Timestamps for logging
28 var m_paz; // will be initialised below
29 var m_templateText = {}; // widgets can register templates to be compiled
30 var m_template = {}; // compiled templates, from any source
31 var m_config = mkws.objectInheritingFrom(mkws.config);
32 var m_widgets = {}; // Maps widget-type to array of widget objects
33 var m_gotRecords = false;
35 that.toString = function() { return '[Team ' + teamName + ']'; };
37 // Accessor methods for individual widgets: readers
38 that.name = function() { return m_teamName; };
39 that.submitted = function() { return m_submitted; };
40 that.sortOrder = function() { return m_sortOrder; };
41 that.perpage = function() { return m_perpage; };
42 that.totalRecordCount = function() { return m_totalRecordCount; };
43 that.currentPage = function() { return m_currentPage; };
44 that.currentRecordId = function() { return m_currentRecordId; };
45 that.currentRecordData = function() { return m_currentRecordData; };
46 that.filters = function() { return m_filterSet; };
47 that.config = function() { return m_config; };
49 // Accessor methods for individual widgets: writers
50 that.set_sortOrder = function(val) { m_sortOrder = val };
51 that.set_perpage = function(val) { m_perpage = val };
54 // The following PubSub code is modified from the jQuery manual:
55 // http://api.jquery.com/jQuery.Callbacks/
58 // team.queue("eventName").subscribe(function(param1, param2 ...) { ... });
59 // team.queue("eventName").publish(arg1, arg2, ...);
64 var callbacks = $.Callbacks();
66 publish: callbacks.fire,
67 subscribe: callbacks.add,
68 unsubscribe: callbacks.remove
78 var timestamp = (((now - m_logTime.start)/1000).toFixed(3) + " (+" +
79 ((now - m_logTime.last)/1000).toFixed(3) + ") ");
81 mkws.log(m_teamName + ": " + timestamp + s);
82 that.queue("log").publish(m_teamName, timestamp, s);
87 log("making new widget team");
89 m_sortOrder = m_config.sort_default;
90 m_perpage = m_config.perpage_default;
92 // create a parameters array and pass it to the pz2's constructor
93 // then register the form submit event with the pz2.search function
94 // autoInit is set to true on default
95 m_paz = new pz2({ "windowid": teamName,
96 "pazpar2path": m_config.pazpar2_url,
97 "usesessions" : m_config.use_service_proxy ? false : true,
99 "onbytarget": onBytarget,
101 "onterm": (m_config.facets.length ? onTerm : undefined),
103 "onrecord": onRecord,
104 "showtime": 500, //each timer (show, stat, term, bytarget) can be specified this way
105 "termlist": m_config.facets.join(',')
107 log("created main pz2 object");
109 // pz2.js event handlers:
116 function onBytarget(data) {
118 queue("targets").publish(data);
121 function onStat(data) {
122 queue("stat").publish(data);
123 var hitcount = parseInt(data.hits[0], 10);
124 if (!m_gotRecords && hitcount > 0) {
126 queue("firstrecords").publish(hitcount);
128 if (parseInt(data.activeclients[0], 10) === 0) {
130 queue("complete").publish(hitcount);
134 function onTerm(data) {
136 queue("termlists").publish(data);
139 function onShow(data, teamName) {
141 m_totalRecordCount = data.merged;
142 log("found " + m_totalRecordCount + " records");
143 queue("pager").publish(data);
144 queue("records").publish(data);
147 function onRecord(data, args, teamName) {
149 // FIXME: record is async!!
150 clearTimeout(m_paz.recordTimer);
151 var detRecordDiv = findnode(recordDetailsId(data.recid[0]));
152 if (detRecordDiv.length) {
153 // in case on_show was faster to redraw element
156 m_currentRecordData = data;
157 var recordDiv = findnode('.' + recordElementId(m_currentRecordData.recid[0]));
158 var html = renderDetails(m_currentRecordData);
159 $(recordDiv).append(html);
163 // Used by the Records widget and onRecord()
164 function recordElementId(s) {
165 return 'mkwsRec_' + s.replace(/[^a-z0-9]/ig, '_');
167 that.recordElementId = recordElementId;
169 // Used by onRecord(), showDetails() and renderDetails()
170 function recordDetailsId(s) {
171 return 'mkwsDet_' + s.replace(/[^a-z0-9]/ig, '_');
175 that.targetFiltered = function(id) {
176 return m_filterSet.targetFiltered(id);
180 that.limitTarget = function(id, name) {
181 log("limitTarget(id=" + id + ", name=" + name + ")");
182 m_filterSet.add(targetFilter(id, name));
183 if (m_query) triggerSearch();
188 that.limitQuery = function(field, value) {
189 log("limitQuery(field=" + field + ", value=" + value + ")");
190 m_filterSet.add(fieldFilter(field, value));
191 if (m_query) triggerSearch();
196 that.limitCategory = function(id) {
197 log("limitCategory(id=" + id + ")");
198 // Only one category filter at a time
199 m_filterSet.removeMatching(function(f) { return f.type === 'category' });
200 if (id !== '') m_filterSet.add(categoryFilter(id));
201 if (m_query) triggerSearch();
206 that.delimitTarget = function(id) {
207 log("delimitTarget(id=" + id + ")");
208 m_filterSet.removeMatching(function(f) { return f.type === 'target' });
209 if (m_query) triggerSearch();
214 that.delimitQuery = function(field, value) {
215 log("delimitQuery(field=" + field + ", value=" + value + ")");
216 m_filterSet.removeMatching(function(f) { return f.type == 'field' &&
217 field == f.field && value == f.value });
218 if (m_query) triggerSearch();
223 that.showPage = function(pageNum) {
224 m_currentPage = pageNum;
225 m_paz.showPage(m_currentPage - 1);
229 that.pagerNext = function() {
230 if (m_totalRecordCount - m_perpage*m_currentPage > 0) {
237 that.pagerPrev = function() {
238 if (m_paz.showPrev() != false)
243 that.reShow = function() {
245 m_paz.show(0, m_perpage, m_sortOrder);
249 function resetPage() {
251 m_totalRecordCount = 0;
252 m_gotRecords = false;
254 that.resetPage = resetPage;
257 function newSearch(query, sortOrder, maxrecs, perpage, limit, targets, torusquery) {
258 log("newSearch: " + query);
260 if (m_config.use_service_proxy && !mkws.authenticated) {
261 alert("searching before authentication");
265 m_filterSet.removeMatching(function(f) { return f.type !== 'category' });
266 triggerSearch(query, sortOrder, maxrecs, perpage, limit, targets, torusquery);
267 switchView('records'); // In case it's configured to start off as hidden
270 that.newSearch = newSearch;
273 function triggerSearch(query, sortOrder, maxrecs, perpage, limit, targets, torusquery) {
275 queue("navi").publish();
277 // Continue to use previous query/sort-order unless new ones are specified
278 if (query) m_query = query;
279 if (sortOrder) m_sortOrder = sortOrder;
280 if (perpage) m_perpage = perpage;
281 if (targets) m_filterSet.add(targetFilter(targets, targets));
283 var pp2filter = m_filterSet.pp2filter();
284 var pp2limit = m_filterSet.pp2limit(limit);
285 var pp2catLimit = m_filterSet.pp2catLimit();
287 pp2filter = pp2filter ? pp2filter + "," + pp2catLimit : pp2catLimit;
291 if (pp2limit) params.limit = pp2limit;
292 if (maxrecs) params.maxrecs = maxrecs;
294 if (!mkws.config.use_service_proxy)
295 alert("can't narrow search by torusquery when Service Proxy is not in use");
296 params.torusquery = torusquery;
299 log("triggerSearch(" + m_query + "): filters = " + m_filterSet.toJSON() + ", " +
300 "pp2filter = " + pp2filter + ", params = " + $.toJSON(params));
302 m_paz.search(m_query, m_perpage, m_sortOrder, pp2filter, undefined, params);
306 // switching view between targets and records
307 function switchView(view) {
308 var targets = widgetNode('Targets');
309 var results = widgetNode('Results') || widgetNode('Records');
310 var blanket = widgetNode('Blanket');
311 var motd = widgetNode('MOTD');
315 if (targets) $(targets).show();
316 if (results) $(results).hide();
317 if (blanket) $(blanket).hide();
318 if (motd) $(motd).hide();
321 if (targets) $(targets).hide();
322 if (results) $(results).show();
323 if (blanket) $(blanket).show();
324 if (motd) $(motd).hide();
327 alert("Unknown view '" + view + "'");
330 that.switchView = switchView;
333 // detailed record drawing
334 that.showDetails = function(recId) {
335 var oldRecordId = m_currentRecordId;
336 m_currentRecordId = recId;
338 // remove current detailed view if any
339 findnode('#' + recordDetailsId(oldRecordId)).remove();
341 // if the same clicked, just hide
342 if (recId == oldRecordId) {
343 m_currentRecordId = '';
344 m_currentRecordData = null;
347 // request the record
348 log("showDetails() requesting record '" + recId + "'");
353 // Finds the node of the specified class within the current team
354 function findnode(selector, teamName) {
355 teamName = teamName || m_teamName;
357 if (teamName === 'AUTO') {
358 selector = (selector + '.mkwsTeam_' + teamName + ',' +
359 selector + ':not([class^="mkwsTeam"],[class*=" mkwsTeam"])');
361 selector = selector + '.mkwsTeam_' + teamName;
364 var node = $(selector);
365 //log('findnode(' + selector + ') found ' + node.length + ' nodes');
370 function widgetNode(type) {
371 var w = that.widget(type);
372 return w ? w.node : undefined;
375 function renderDetails(data, marker) {
376 var template = loadTemplate("Record");
377 var details = template(data);
378 return '<div class="mkwsDetails mkwsTeam_' + m_teamName + '" ' +
379 'id="' + recordDetailsId(data.recid[0]) + '">' + details + '</div>';
381 that.renderDetails = renderDetails;
384 that.registerTemplate = function(name, text) {
385 m_templateText[name] = text;
389 function loadTemplate(name, fallbackString) {
390 var template = m_template[name];
392 if (template === undefined) {
393 // Fall back to generic template if there is no team-specific one
395 var node = $(".mkwsTemplate_" + name + " .mkwsTeam_" + that.name());
396 if (node && node.length < 1) {
397 node = $(".mkwsTemplate_" + name);
400 source = node.html();
403 // If the template is not defined in HTML, check the following
404 // in order: template registered in the team by a widget;
405 // fallback string provided on this invocation; global default.
407 source = m_templateText[name];
410 source = fallbackString;
413 source = mkws.defaultTemplate(name);
416 template = Handlebars.compile(source);
417 log("compiled template '" + name + "'");
418 m_template[name] = template;
423 that.loadTemplate = loadTemplate;
426 that.addWidget = function(w) {
427 if (m_widgets[w.type] === undefined) {
428 m_widgets[w.type] = [ w ];
430 m_widgets[w.type].push(w);
434 that.widget = function(type) {
435 var list = m_widgets[type];
439 if (list.length > 1) {
440 alert("widget('" + type + "') finds " + list.length + " widgets: using first");
445 that.visitWidgets = function(callback) {
446 for (var type in m_widgets) {
447 var list = m_widgets[type];
448 for (var i = 0; i < list.length; i++) {
449 var res = callback(type, list[i]);
450 if (res !== undefined) {