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_widgets = {}; // Maps widget-type to array of widget objects
32 var m_gotRecords = false;
34 var config = mkws.objectInheritingFrom(mkws.config);
37 that.toString = function() { return '[Team ' + teamName + ']'; };
39 // Accessor methods for individual widgets: readers
40 that.name = function() { return m_teamName; };
41 that.submitted = function() { return m_submitted; };
42 that.sortOrder = function() { return m_sortOrder; };
43 that.perpage = function() { return m_perpage; };
44 that.totalRecordCount = function() { return m_totalRecordCount; };
45 that.currentPage = function() { return m_currentPage; };
46 that.currentRecordId = function() { return m_currentRecordId; };
47 that.currentRecordData = function() { return m_currentRecordData; };
48 that.filters = function() { return m_filterSet; };
50 // Accessor methods for individual widgets: writers
51 that.set_sortOrder = function(val) { m_sortOrder = val };
52 that.set_perpage = function(val) { m_perpage = val };
55 // The following PubSub code is modified from the jQuery manual:
56 // http://api.jquery.com/jQuery.Callbacks/
59 // team.queue("eventName").subscribe(function(param1, param2 ...) { ... });
60 // team.queue("eventName").publish(arg1, arg2, ...);
65 var callbacks = $.Callbacks();
67 publish: callbacks.fire,
68 subscribe: callbacks.add,
69 unsubscribe: callbacks.remove
79 var timestamp = (((now - m_logTime.start)/1000).toFixed(3) + " (+" +
80 ((now - m_logTime.last)/1000).toFixed(3) + ") ");
82 mkws.log(m_teamName + ": " + timestamp + s);
83 that.queue("log").publish(m_teamName, timestamp, s);
88 log("making new widget team");
90 m_sortOrder = config.sort_default;
91 m_perpage = config.perpage_default;
93 // create a parameters array and pass it to the pz2's constructor
94 // then register the form submit event with the pz2.search function
95 // autoInit is set to true on default
96 m_paz = new pz2({ "windowid": teamName,
97 "pazpar2path": mkws.pazpar2_url(),
98 "usesessions" : config.use_service_proxy ? false : true,
100 "onbytarget": onBytarget,
102 "onterm": (config.facets.length ? onTerm : undefined),
104 "onrecord": onRecord,
105 "showtime": 500, //each timer (show, stat, term, bytarget) can be specified this way
106 "termlist": config.facets.join(',')
108 log("created main pz2 object");
110 // pz2.js event handlers:
117 function onBytarget(data) {
119 queue("targets").publish(data);
122 function onStat(data) {
123 queue("stat").publish(data);
124 var hitcount = parseInt(data.hits[0], 10);
125 if (!m_gotRecords && hitcount > 0) {
127 queue("firstrecords").publish(hitcount);
129 if (parseInt(data.activeclients[0], 10) === 0) {
131 queue("complete").publish(hitcount);
135 function onTerm(data) {
137 queue("termlists").publish(data);
140 function onShow(data, teamName) {
142 m_totalRecordCount = data.merged;
143 log("found " + m_totalRecordCount + " records");
144 queue("pager").publish(data);
145 queue("records").publish(data);
148 function onRecord(data, args, teamName) {
150 // FIXME: record is async!!
151 clearTimeout(m_paz.recordTimer);
152 var detRecordDiv = findnode(recordDetailsId(data.recid[0]));
153 if (detRecordDiv.length) {
154 // in case on_show was faster to redraw element
157 m_currentRecordData = data;
158 var recordDiv = findnode('.' + recordElementId(m_currentRecordData.recid[0]));
159 var html = renderDetails(m_currentRecordData);
160 $(recordDiv).append(html);
164 // Used by the Records widget and onRecord()
165 function recordElementId(s) {
166 return 'mkwsRec_' + s.replace(/[^a-z0-9]/ig, '_');
168 that.recordElementId = recordElementId;
170 // Used by onRecord(), showDetails() and renderDetails()
171 function recordDetailsId(s) {
172 return 'mkwsDet_' + s.replace(/[^a-z0-9]/ig, '_');
176 that.targetFiltered = function(id) {
177 return m_filterSet.targetFiltered(id);
181 that.limitTarget = function(id, name) {
182 log("limitTarget(id=" + id + ", name=" + name + ")");
183 m_filterSet.add(targetFilter(id, name));
184 if (m_query) triggerSearch();
189 that.limitQuery = function(field, value) {
190 log("limitQuery(field=" + field + ", value=" + value + ")");
191 m_filterSet.add(fieldFilter(field, value));
192 if (m_query) triggerSearch();
197 that.limitCategory = function(id) {
198 log("limitCategory(id=" + id + ")");
199 // Only one category filter at a time
200 m_filterSet.removeMatching(function(f) { return f.type === 'category' });
201 if (id !== '') m_filterSet.add(categoryFilter(id));
202 if (m_query) triggerSearch();
207 that.delimitTarget = function(id) {
208 log("delimitTarget(id=" + id + ")");
209 m_filterSet.removeMatching(function(f) { return f.type === 'target' });
210 if (m_query) triggerSearch();
215 that.delimitQuery = function(field, value) {
216 log("delimitQuery(field=" + field + ", value=" + value + ")");
217 m_filterSet.removeMatching(function(f) { return f.type == 'field' &&
218 field == f.field && value == f.value });
219 if (m_query) triggerSearch();
224 that.showPage = function(pageNum) {
225 m_currentPage = pageNum;
226 m_paz.showPage(m_currentPage - 1);
230 that.pagerNext = function() {
231 if (m_totalRecordCount - m_perpage*m_currentPage > 0) {
238 that.pagerPrev = function() {
239 if (m_paz.showPrev() != false)
244 that.reShow = function() {
246 m_paz.show(0, m_perpage, m_sortOrder);
250 function resetPage() {
252 m_totalRecordCount = 0;
253 m_gotRecords = false;
255 that.resetPage = resetPage;
258 function newSearch(query, sortOrder, maxrecs, perpage, limit, targets, torusquery) {
259 log("newSearch: " + query);
261 if (config.use_service_proxy && !mkws.authenticated) {
262 alert("searching before authentication");
266 m_filterSet.removeMatching(function(f) { return f.type !== 'category' });
267 triggerSearch(query, sortOrder, maxrecs, perpage, limit, targets, torusquery);
268 switchView('records'); // In case it's configured to start off as hidden
271 that.newSearch = newSearch;
274 function triggerSearch(query, sortOrder, maxrecs, perpage, limit, targets, torusquery) {
276 queue("navi").publish();
278 // Continue to use previous query/sort-order unless new ones are specified
279 if (query) m_query = query;
280 if (sortOrder) m_sortOrder = sortOrder;
281 if (perpage) m_perpage = perpage;
282 if (targets) m_filterSet.add(targetFilter(targets, targets));
284 var pp2filter = m_filterSet.pp2filter();
285 var pp2limit = m_filterSet.pp2limit(limit);
286 var pp2catLimit = m_filterSet.pp2catLimit();
288 pp2filter = pp2filter ? pp2filter + "," + pp2catLimit : pp2catLimit;
292 if (pp2limit) params.limit = pp2limit;
293 if (maxrecs) params.maxrecs = maxrecs;
295 if (!mkws.config.use_service_proxy)
296 alert("can't narrow search by torusquery when not authenticated");
297 params.torusquery = torusquery;
300 log("triggerSearch(" + m_query + "): filters = " + m_filterSet.toJSON() + ", " +
301 "pp2filter = " + pp2filter + ", params = " + $.toJSON(params));
303 m_paz.search(m_query, m_perpage, m_sortOrder, pp2filter, undefined, params);
307 // switching view between targets and records
308 function switchView(view) {
309 var targets = widgetNode('Targets');
310 var results = widgetNode('Results') || widgetNode('Records');
311 var blanket = widgetNode('Blanket');
312 var motd = widgetNode('MOTD');
316 if (targets) $(targets).show();
317 if (results) $(results).hide();
318 if (blanket) $(blanket).hide();
319 if (motd) $(motd).hide();
322 if (targets) $(targets).hide();
323 if (results) $(results).show();
324 if (blanket) $(blanket).show();
325 if (motd) $(motd).hide();
328 alert("Unknown view '" + view + "'");
331 that.switchView = switchView;
334 // detailed record drawing
335 that.showDetails = function(recId) {
336 var oldRecordId = m_currentRecordId;
337 m_currentRecordId = recId;
339 // remove current detailed view if any
340 findnode('#' + recordDetailsId(oldRecordId)).remove();
342 // if the same clicked, just hide
343 if (recId == oldRecordId) {
344 m_currentRecordId = '';
345 m_currentRecordData = null;
348 // request the record
349 log("showDetails() requesting record '" + recId + "'");
354 // Finds the node of the specified class within the current team
355 function findnode(selector, teamName) {
356 teamName = teamName || m_teamName;
358 if (teamName === 'AUTO') {
359 selector = (selector + '.mkwsTeam_' + teamName + ',' +
360 selector + ':not([class^="mkwsTeam"],[class*=" mkwsTeam"])');
362 selector = selector + '.mkwsTeam_' + teamName;
365 var node = $(selector);
366 //log('findnode(' + selector + ') found ' + node.length + ' nodes');
371 function widgetNode(type) {
372 var w = that.widget(type);
373 return w ? w.node : undefined;
376 function renderDetails(data, marker) {
377 var template = loadTemplate("Record");
378 var details = template(data);
379 return '<div class="mkwsDetails mkwsTeam_' + m_teamName + '" ' +
380 'id="' + recordDetailsId(data.recid[0]) + '">' + details + '</div>';
382 that.renderDetails = renderDetails;
385 that.registerTemplate = function(name, text) {
386 m_templateText[name] = text;
390 function loadTemplate(name, fallbackString) {
391 var template = m_template[name];
393 if (template === undefined) {
394 // Fall back to generic template if there is no team-specific one
396 var node = $(".mkwsTemplate_" + name + " .mkwsTeam_" + that.name());
397 if (node && node.length < 1) {
398 node = $(".mkwsTemplate_" + name);
401 source = node.html();
404 // If the template is not defined in HTML, check the following
405 // in order: template registered in the team by a widget;
406 // fallback string provided on this invocation; global default.
408 source = m_templateText[name];
411 source = fallbackString;
414 source = mkws.defaultTemplate(name);
417 if (!source) return null;
418 template = Handlebars.compile(source);
419 log("compiled template '" + name + "'");
420 m_template[name] = template;
425 that.loadTemplate = loadTemplate;
428 that.addWidget = function(w) {
429 if (m_widgets[w.type] === undefined) {
430 m_widgets[w.type] = [ w ];
432 m_widgets[w.type].push(w);
436 that.widget = function(type) {
437 var list = m_widgets[type];
441 if (list.length > 1) {
442 alert("widget('" + type + "') finds " + list.length + " widgets: using first");
447 that.visitWidgets = function(callback) {
448 for (var type in m_widgets) {
449 var list = m_widgets[type];
450 for (var i = 0; i < list.length; i++) {
451 var res = callback(type, list[i]);
452 if (res !== undefined) {