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) {
129 queue("complete").publish(hitcount);
133 function onTerm(data) {
135 queue("termlists").publish(data);
138 function onShow(data, teamName) {
140 m_totalRecordCount = data.merged;
141 log("found " + m_totalRecordCount + " records");
142 queue("pager").publish(data);
143 queue("records").publish(data);
146 function onRecord(data, args, teamName) {
148 // FIXME: record is async!!
149 clearTimeout(m_paz.recordTimer);
150 var detRecordDiv = findnode(recordDetailsId(data.recid[0]));
151 if (detRecordDiv.length) {
152 // in case on_show was faster to redraw element
155 m_currentRecordData = data;
156 var recordDiv = findnode('.' + recordElementId(m_currentRecordData.recid[0]));
157 var html = renderDetails(m_currentRecordData);
158 $(recordDiv).append(html);
162 // Used by the Records widget and onRecord()
163 function recordElementId(s) {
164 return 'mkwsRec_' + s.replace(/[^a-z0-9]/ig, '_');
166 that.recordElementId = recordElementId;
168 // Used by onRecord(), showDetails() and renderDetails()
169 function recordDetailsId(s) {
170 return 'mkwsDet_' + s.replace(/[^a-z0-9]/ig, '_');
174 that.targetFiltered = function(id) {
175 return m_filterSet.targetFiltered(id);
179 that.limitTarget = function(id, name) {
180 log("limitTarget(id=" + id + ", name=" + name + ")");
181 m_filterSet.add(targetFilter(id, name));
182 if (m_query) triggerSearch();
187 that.limitQuery = function(field, value) {
188 log("limitQuery(field=" + field + ", value=" + value + ")");
189 m_filterSet.add(fieldFilter(field, value));
190 if (m_query) triggerSearch();
195 that.limitCategory = function(id) {
196 log("limitCategory(id=" + id + ")");
197 // Only one category filter at a time
198 m_filterSet.removeMatching(function(f) { return f.type === 'category' });
199 if (id !== '') m_filterSet.add(categoryFilter(id));
200 if (m_query) triggerSearch();
205 that.delimitTarget = function(id) {
206 log("delimitTarget(id=" + id + ")");
207 m_filterSet.removeMatching(function(f) { return f.type === 'target' });
208 if (m_query) triggerSearch();
213 that.delimitQuery = function(field, value) {
214 log("delimitQuery(field=" + field + ", value=" + value + ")");
215 m_filterSet.removeMatching(function(f) { return f.type == 'field' &&
216 field == f.field && value == f.value });
217 if (m_query) triggerSearch();
222 that.showPage = function(pageNum) {
223 m_currentPage = pageNum;
224 m_paz.showPage(m_currentPage - 1);
228 that.pagerNext = function() {
229 if (m_totalRecordCount - m_perpage*m_currentPage > 0) {
236 that.pagerPrev = function() {
237 if (m_paz.showPrev() != false)
242 that.reShow = function() {
244 m_paz.show(0, m_perpage, m_sortOrder);
248 function resetPage() {
250 m_totalRecordCount = 0;
252 that.resetPage = resetPage;
255 function newSearch(query, sortOrder, maxrecs, perpage, limit, targets, torusquery) {
256 log("newSearch: " + query);
258 if (m_config.use_service_proxy && !mkws.authenticated) {
259 alert("searching before authentication");
263 m_filterSet.removeMatching(function(f) { return f.type !== 'category' });
264 triggerSearch(query, sortOrder, maxrecs, perpage, limit, targets, torusquery);
265 switchView('records'); // In case it's configured to start off as hidden
268 that.newSearch = newSearch;
271 function triggerSearch(query, sortOrder, maxrecs, perpage, limit, targets, torusquery) {
273 queue("navi").publish();
275 // Continue to use previous query/sort-order unless new ones are specified
276 if (query) m_query = query;
277 if (sortOrder) m_sortOrder = sortOrder;
278 if (perpage) m_perpage = perpage;
279 if (targets) m_filterSet.add(targetFilter(targets, targets));
281 var pp2filter = m_filterSet.pp2filter();
282 var pp2limit = m_filterSet.pp2limit(limit);
283 var pp2catLimit = m_filterSet.pp2catLimit();
285 pp2filter = pp2filter ? pp2filter + "," + pp2catLimit : pp2catLimit;
289 if (pp2limit) params.limit = pp2limit;
290 if (maxrecs) params.maxrecs = maxrecs;
292 if (!mkws.config.use_service_proxy)
293 alert("can't narrow search by torusquery when Service Proxy is not in use");
294 params.torusquery = torusquery;
297 log("triggerSearch(" + m_query + "): filters = " + m_filterSet.toJSON() + ", " +
298 "pp2filter = " + pp2filter + ", params = " + $.toJSON(params));
300 m_paz.search(m_query, m_perpage, m_sortOrder, pp2filter, undefined, params);
304 // switching view between targets and records
305 function switchView(view) {
306 var targets = widgetNode('Targets');
307 var results = widgetNode('Results') || widgetNode('Records');
308 var blanket = widgetNode('Blanket');
309 var motd = widgetNode('MOTD');
313 if (targets) $(targets).show();
314 if (results) $(results).hide();
315 if (blanket) $(blanket).hide();
316 if (motd) $(motd).hide();
319 if (targets) $(targets).hide();
320 if (results) $(results).show();
321 if (blanket) $(blanket).show();
322 if (motd) $(motd).hide();
325 alert("Unknown view '" + view + "'");
328 that.switchView = switchView;
331 // detailed record drawing
332 that.showDetails = function(recId) {
333 var oldRecordId = m_currentRecordId;
334 m_currentRecordId = recId;
336 // remove current detailed view if any
337 findnode('#' + recordDetailsId(oldRecordId)).remove();
339 // if the same clicked, just hide
340 if (recId == oldRecordId) {
341 m_currentRecordId = '';
342 m_currentRecordData = null;
345 // request the record
346 log("showDetails() requesting record '" + recId + "'");
351 // Finds the node of the specified class within the current team
352 function findnode(selector, teamName) {
353 teamName = teamName || m_teamName;
355 if (teamName === 'AUTO') {
356 selector = (selector + '.mkwsTeam_' + teamName + ',' +
357 selector + ':not([class^="mkwsTeam"],[class*=" mkwsTeam"])');
359 selector = selector + '.mkwsTeam_' + teamName;
362 var node = $(selector);
363 //log('findnode(' + selector + ') found ' + node.length + ' nodes');
368 function widgetNode(type) {
369 var w = that.widget(type);
370 return w ? w.node : undefined;
373 function renderDetails(data, marker) {
374 var template = loadTemplate("Record");
375 var details = template(data);
376 return '<div class="mkwsDetails mkwsTeam_' + m_teamName + '" ' +
377 'id="' + recordDetailsId(data.recid[0]) + '">' + details + '</div>';
379 that.renderDetails = renderDetails;
382 that.registerTemplate = function(name, text) {
383 m_templateText[name] = text;
387 function loadTemplate(name) {
388 var template = m_template[name];
390 if (template === undefined) {
391 // Fall back to generic template if there is no team-specific one
393 var node = $(".mkwsTemplate_" + name + " .mkwsTeam_" + that.name());
394 if (node && node.length < 1) {
395 node = $(".mkwsTemplate_" + name);
398 source = node.html();
402 source = m_templateText[name];
405 source = mkws.defaultTemplate(name);
408 template = Handlebars.compile(source);
409 log("compiled template '" + name + "'");
410 m_template[name] = template;
415 that.loadTemplate = loadTemplate;
418 that.addWidget = function(w) {
419 if (m_widgets[w.type] === undefined) {
420 m_widgets[w.type] = [ w ];
422 m_widgets[w.type].push(w);
426 that.widget = function(type) {
427 var list = m_widgets[type];
431 if (list.length > 1) {
432 alert("widget('" + type + "') finds " + list.length + " widgets: using first");
437 that.visitWidgets = function(callback) {
438 for (var type in m_widgets) {
439 var list = m_widgets[type];
440 for (var i = 0; i < list.length; i++) {
441 var res = callback(type, list[i]);
442 if (res !== undefined) {