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 mkws.makeTeam = function($, 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.query = function() { return m_query; };
45 that.totalRecordCount = function() { return m_totalRecordCount; };
46 that.currentPage = function() { return m_currentPage; };
47 that.currentRecordId = function() { return m_currentRecordId; };
48 that.currentRecordData = function() { return m_currentRecordData; };
49 that.filters = function() { return m_filterSet; };
50 that.gotRecords = function() { return m_gotRecords; };
52 // Accessor methods for individual widgets: writers
53 that.set_sortOrder = function(val) { m_sortOrder = val };
54 that.set_perpage = function(val) { m_perpage = val };
57 // The following PubSub code is modified from the jQuery manual:
58 // http://api.jquery.com/jQuery.Callbacks/
61 // team.queue("eventName").subscribe(function(param1, param2 ...) { ... });
62 // team.queue("eventName").publish(arg1, arg2, ...);
67 var callbacks = $.Callbacks();
69 publish: callbacks.fire,
70 subscribe: callbacks.add,
71 unsubscribe: callbacks.remove
81 var timestamp = (((now - m_logTime.start)/1000).toFixed(3) + " (+" +
82 ((now - m_logTime.last)/1000).toFixed(3) + ") ");
84 mkws.log(m_teamName + ": " + timestamp + s);
85 that.queue("log").publish(m_teamName, timestamp, s);
90 log("making new widget team");
92 m_sortOrder = config.sort_default;
93 m_perpage = config.perpage_default;
95 // create a parameters array and pass it to the pz2's constructor
96 // then register the form submit event with the pz2.search function
97 // autoInit is set to true on default
98 that.makePz2 = function() {
99 m_paz = new pz2({ "windowid": teamName,
100 "pazpar2path": mkws.pazpar2_url(),
101 "usesessions" : config.use_service_proxy ? false : true,
103 "onbytarget": onBytarget,
105 "onterm": (config.facets.length ? onTerm : undefined),
107 "onrecord": onRecord,
108 "showtime": 500, //each timer (show, stat, term, bytarget) can be specified this way
109 "termlist": config.facets.join(',')
111 log("created main pz2 object");
114 // pz2.js event handlers:
121 function onBytarget(data) {
123 queue("targets").publish(data);
126 function onStat(data) {
127 queue("stat").publish(data);
128 var hitcount = parseInt(data.hits[0], 10);
129 if (!m_gotRecords && hitcount > 0) {
131 queue("firstrecords").publish(hitcount);
133 if (parseInt(data.activeclients[0], 10) === 0) {
135 queue("complete").publish(hitcount);
139 function onTerm(data) {
141 queue("termlists").publish(data);
144 function onShow(data, teamName) {
146 m_totalRecordCount = data.merged;
147 log("found " + m_totalRecordCount + " records");
148 queue("pager").publish(data);
149 queue("records").publish(data);
152 function onRecord(data, args, teamName) {
154 // FIXME: record is async!!
155 clearTimeout(m_paz.recordTimer);
156 queue("record").publish(data);
157 var detRecordDiv = findnode(recordDetailsId(data.recid[0]));
158 if (detRecordDiv.length) {
159 // in case on_show was faster to redraw element
162 m_currentRecordData = data;
163 var recordDiv = findnode('.' + recordElementId(m_currentRecordData.recid[0]));
164 var html = renderDetails(m_currentRecordData);
165 $(recordDiv).append(html);
169 // Used by the Records widget and onRecord()
170 function recordElementId(s) {
171 return 'mkwsRec_' + s.replace(/[^a-z0-9]/ig, '_');
173 that.recordElementId = recordElementId;
175 // Used by onRecord(), showDetails() and renderDetails()
176 function recordDetailsId(s) {
177 return 'mkwsDet_' + s.replace(/[^a-z0-9]/ig, '_');
181 that.targetFiltered = function(id) {
182 return m_filterSet.targetFiltered(id);
186 that.limitTarget = function(id, name) {
187 log("limitTarget(id=" + id + ", name=" + name + ")");
188 m_filterSet.add(targetFilter(id, name));
189 if (m_query) triggerSearch();
194 that.limitQuery = function(field, value) {
195 log("limitQuery(field=" + field + ", value=" + value + ")");
196 m_filterSet.add(fieldFilter(field, value));
197 if (m_query) triggerSearch();
202 that.limitCategory = function(id) {
203 log("limitCategory(id=" + id + ")");
204 // Only one category filter at a time
205 m_filterSet.removeMatching(function(f) { return f.type === 'category' });
206 if (id !== '') m_filterSet.add(categoryFilter(id));
207 if (m_query) triggerSearch();
212 that.delimitTarget = function(id) {
213 log("delimitTarget(id=" + id + ")");
214 m_filterSet.removeMatching(function(f) { return f.type === 'target' });
215 if (m_query) triggerSearch();
220 that.delimitQuery = function(field, value) {
221 log("delimitQuery(field=" + field + ", value=" + value + ")");
222 m_filterSet.removeMatching(function(f) { return f.type == 'field' &&
223 field == f.field && value == f.value });
224 if (m_query) triggerSearch();
229 that.showPage = function(pageNum) {
230 m_currentPage = pageNum;
231 m_paz.showPage(m_currentPage - 1);
235 that.pagerNext = function() {
236 if (m_totalRecordCount - m_perpage*m_currentPage > 0) {
243 that.pagerPrev = function() {
244 if (m_paz.showPrev() != false)
249 that.reShow = function() {
251 m_paz.show(0, m_perpage, m_sortOrder);
255 function resetPage() {
257 m_totalRecordCount = 0;
258 m_gotRecords = false;
260 that.resetPage = resetPage;
263 function newSearch(query, sortOrder, maxrecs, perpage, limit, targets, torusquery) {
264 log("newSearch: " + query);
266 if (config.use_service_proxy && !mkws.authenticated) {
267 alert("searching before authentication");
271 m_filterSet.removeMatching(function(f) { return f.type !== 'category' });
272 triggerSearch(query, sortOrder, maxrecs, perpage, limit, targets, torusquery);
273 switchView('records'); // In case it's configured to start off as hidden
276 that.newSearch = newSearch;
279 function triggerSearch(query, sortOrder, maxrecs, perpage, limit, targets, torusquery) {
281 queue("navi").publish();
283 // Continue to use previous query/sort-order unless new ones are specified
284 if (query) m_query = query;
285 if (sortOrder) m_sortOrder = sortOrder;
286 if (perpage) m_perpage = perpage;
287 if (targets) m_filterSet.add(targetFilter(targets, targets));
289 var pp2filter = m_filterSet.pp2filter();
290 var pp2limit = m_filterSet.pp2limit(limit);
291 var pp2catLimit = m_filterSet.pp2catLimit();
293 pp2filter = pp2filter ? pp2filter + "," + pp2catLimit : pp2catLimit;
297 if (pp2limit) params.limit = pp2limit;
298 if (maxrecs) params.maxrecs = maxrecs;
300 if (!mkws.config.use_service_proxy)
301 alert("can't narrow search by torusquery when not authenticated");
302 params.torusquery = torusquery;
305 log("triggerSearch(" + m_query + "): filters = " + m_filterSet.toJSON() + ", " +
306 "pp2filter = " + pp2filter + ", params = " + $.toJSON(params));
308 m_paz.search(m_query, m_perpage, m_sortOrder, pp2filter, undefined, params);
311 // fetch record details to be retrieved from the record queue
312 that.fetchDetails = function(recId) {
313 log("fetchDetails() requesting record '" + recId + "'");
318 // switching view between targets and records
319 function switchView(view) {
320 var targets = widgetNode('Targets');
321 var results = widgetNode('Results') || widgetNode('Records');
322 var blanket = widgetNode('Blanket');
323 var motd = widgetNode('MOTD');
327 if (targets) $(targets).show();
328 if (results) $(results).hide();
329 if (blanket) $(blanket).hide();
330 if (motd) $(motd).hide();
333 if (targets) $(targets).hide();
334 if (results) $(results).show();
335 if (blanket) $(blanket).show();
336 if (motd) $(motd).hide();
339 alert("Unknown view '" + view + "'");
342 that.switchView = switchView;
345 // detailed record drawing
346 that.showDetails = function(recId) {
347 var oldRecordId = m_currentRecordId;
348 m_currentRecordId = recId;
350 // remove current detailed view if any
351 findnode('#' + recordDetailsId(oldRecordId)).remove();
353 // if the same clicked, just hide
354 if (recId == oldRecordId) {
355 m_currentRecordId = '';
356 m_currentRecordData = null;
359 // request the record
360 log("showDetails() requesting record '" + recId + "'");
365 // Finds the node of the specified class within the current team
366 function findnode(selector, teamName) {
367 teamName = teamName || m_teamName;
369 if (teamName === 'AUTO') {
370 selector = (selector + '.mkwsTeam_' + teamName + ',' +
371 selector + ':not([class^="mkwsTeam"],[class*=" mkwsTeam"])');
373 selector = selector + '.mkwsTeam_' + teamName;
376 var node = $(selector);
377 //log('findnode(' + selector + ') found ' + node.length + ' nodes');
382 function widgetNode(type) {
383 var w = that.widget(type);
384 return w ? w.node : undefined;
387 function renderDetails(data, marker) {
388 var template = loadTemplate("Record");
389 var details = template(data);
390 return '<div class="mkwsDetails mkwsTeam_' + m_teamName + '" ' +
391 'id="' + recordDetailsId(data.recid[0]) + '">' + details + '</div>';
393 that.renderDetails = renderDetails;
396 that.registerTemplate = function(name, text) {
397 m_templateText[name] = text;
401 function loadTemplate(name, fallbackString) {
402 var template = m_template[name];
403 if (template === undefined && Handlebars.compile) {
405 var node = $(".mkwsTemplate_" + name + " .mkwsTeam_" + that.name());
406 if (node && node.length < 1) {
407 node = $(".mkwsTemplate_" + name);
409 if (node) source = node.html();
410 if (!source) source = m_templateText[name];
412 template = Handlebars.compile(source);
413 log("compiled template '" + name + "'");
416 //if (template === undefined) template = mkws_templatesbyteam[m_teamName][name];
417 if (template === undefined && Handlebars.templates) {
418 template = Handlebars.templates[name];
420 if (template === undefined && mkws.defaultTemplates) {
421 template = mkws.defaultTemplates[name];
424 m_template[name] = template;
428 mkws.log("No MKWS template for " + name);
432 that.loadTemplate = loadTemplate;
435 that.addWidget = function(w) {
436 if (m_widgets[w.type] === undefined) {
437 m_widgets[w.type] = [ w ];
439 m_widgets[w.type].push(w);
443 that.widget = function(type) {
444 var list = m_widgets[type];
448 if (list.length > 1) {
449 alert("widget('" + type + "') finds " + list.length + " widgets: using first");
454 that.visitWidgets = function(callback) {
455 for (var type in m_widgets) {
456 var list = m_widgets[type];
457 for (var i = 0; i < list.length; i++) {
458 var res = callback(type, list[i]);
459 if (res !== undefined) {