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 // Before the team can be used for searching and related operations,
12 // its pz2 object must be created by calling team.makePz2().
14 mkws.makeTeam = function($, teamName) {
16 var m_teamName = teamName;
17 var m_submitted = false;
18 var m_query; // initially undefined
19 var m_sortOrder; // will be set below
20 var m_perpage; // will be set below
21 var m_filterSet = filterSet(that);
22 var m_totalRecordCount = 0;
23 var m_currentPage = 1;
24 var m_currentRecordId = '';
25 var m_currentRecordData = null;
27 // Timestamps for logging
31 var m_paz; // will be initialised below
32 var m_templateText = {}; // widgets can register templates to be compiled
33 var m_template = {}; // compiled templates, from any source
34 var m_widgets = {}; // Maps widget-type to array of widget objects
35 var m_gotRecords = false;
37 var config = mkws.objectInheritingFrom(mkws.config);
40 that.toString = function() { return '[Team ' + teamName + ']'; };
42 // Accessor methods for individual widgets: readers
43 that.name = function() { return m_teamName; };
44 that.submitted = function() { return m_submitted; };
45 that.sortOrder = function() { return m_sortOrder; };
46 that.perpage = function() { return m_perpage; };
47 that.query = function() { return m_query; };
48 that.totalRecordCount = function() { return m_totalRecordCount; };
49 that.currentPage = function() { return m_currentPage; };
50 that.currentRecordId = function() { return m_currentRecordId; };
51 that.currentRecordData = function() { return m_currentRecordData; };
52 that.filters = function() { return m_filterSet; };
53 that.gotRecords = function() { return m_gotRecords; };
55 // Accessor methods for individual widgets: writers
56 that.set_sortOrder = function(val) { m_sortOrder = val };
57 that.set_perpage = function(val) { m_perpage = val };
60 // The following PubSub code is modified from the jQuery manual:
61 // http://api.jquery.com/jQuery.Callbacks/
64 // team.queue("eventName").subscribe(function(param1, param2 ...) { ... });
65 // team.queue("eventName").publish(arg1, arg2, ...);
70 var callbacks = $.Callbacks();
72 publish: callbacks.fire,
73 subscribe: callbacks.add,
74 unsubscribe: callbacks.remove
84 var timestamp = (((now - m_logTime.start)/1000).toFixed(3) + " (+" +
85 ((now - m_logTime.last)/1000).toFixed(3) + ") ");
87 mkws.log(m_teamName + ": " + timestamp + s);
88 that.queue("log").publish(m_teamName, timestamp, s);
93 log("making new widget team");
95 m_sortOrder = config.sort_default;
96 m_perpage = config.perpage_default;
98 // pz2.js event handlers:
105 function onBytarget(data) {
107 queue("targets").publish(data);
110 function onStat(data) {
111 queue("stat").publish(data);
112 var hitcount = parseInt(data.hits[0], 10);
113 if (!m_gotRecords && hitcount > 0) {
115 queue("firstrecords").publish(hitcount);
117 if (parseInt(data.activeclients[0], 10) === 0) {
119 queue("complete").publish(hitcount);
123 function onTerm(data) {
125 queue("termlists").publish(data);
128 function onShow(data, teamName) {
130 m_totalRecordCount = data.merged;
131 log("found " + m_totalRecordCount + " records");
132 queue("pager").publish(data);
133 queue("records").publish(data);
136 function onRecord(data, args, teamName) {
138 // FIXME: record is async!!
139 clearTimeout(m_paz.recordTimer);
140 queue("record").publish(data);
141 var detRecordDiv = findnode(recordDetailsId(data.recid[0]));
142 if (detRecordDiv.length) {
143 // in case on_show was faster to redraw element
146 m_currentRecordData = data;
147 var recordDiv = findnode('.' + recordElementId(m_currentRecordData.recid[0]));
148 var html = renderDetails(m_currentRecordData);
149 $(recordDiv).append(html);
153 // create a parameters array and pass it to the pz2's constructor
154 // then register the form submit event with the pz2.search function
155 // autoInit is set to true on default
156 that.makePz2 = function() {
157 m_paz = new pz2({ "windowid": teamName,
158 "pazpar2path": mkws.pazpar2_url(),
159 "usesessions" : config.use_service_proxy ? false : true,
161 "onbytarget": onBytarget,
163 "onterm": (config.facets.length ? onTerm : undefined),
165 "onrecord": onRecord,
166 "showtime": 500, //each timer (show, stat, term, bytarget) can be specified this way
167 "termlist": config.facets.join(',')
169 log("created main pz2 object");
173 // Used by the Records widget and onRecord()
174 function recordElementId(s) {
175 return 'mkwsRec_' + s.replace(/[^a-z0-9]/ig, '_');
177 that.recordElementId = recordElementId;
179 // Used by onRecord(), showDetails() and renderDetails()
180 function recordDetailsId(s) {
181 return 'mkwsDet_' + s.replace(/[^a-z0-9]/ig, '_');
185 that.targetFiltered = function(id) {
186 return m_filterSet.targetFiltered(id);
190 that.limitTarget = function(id, name) {
191 log("limitTarget(id=" + id + ", name=" + name + ")");
192 m_filterSet.add(targetFilter(id, name));
193 if (m_query) triggerSearch();
198 that.limitQuery = function(field, value) {
199 log("limitQuery(field=" + field + ", value=" + value + ")");
200 m_filterSet.add(fieldFilter(field, value));
201 if (m_query) triggerSearch();
206 that.limitCategory = function(id) {
207 log("limitCategory(id=" + id + ")");
208 // Only one category filter at a time
209 m_filterSet.removeMatching(function(f) { return f.type === 'category' });
210 if (id !== '') m_filterSet.add(categoryFilter(id));
211 if (m_query) triggerSearch();
216 that.delimitTarget = function(id) {
217 log("delimitTarget(id=" + id + ")");
218 m_filterSet.removeMatching(function(f) { return f.type === 'target' });
219 if (m_query) triggerSearch();
224 that.delimitQuery = function(field, value) {
225 log("delimitQuery(field=" + field + ", value=" + value + ")");
226 m_filterSet.removeMatching(function(f) { return f.type == 'field' &&
227 field == f.field && value == f.value });
228 if (m_query) triggerSearch();
233 that.showPage = function(pageNum) {
234 m_currentPage = pageNum;
235 m_paz.showPage(m_currentPage - 1);
239 that.pagerNext = function() {
240 if (m_totalRecordCount - m_perpage*m_currentPage > 0) {
247 that.pagerPrev = function() {
248 if (m_paz.showPrev() != false)
253 that.reShow = function() {
255 m_paz.show(0, m_perpage, m_sortOrder);
259 function resetPage() {
261 m_totalRecordCount = 0;
262 m_gotRecords = false;
264 that.resetPage = resetPage;
267 function newSearch(query, sortOrder, maxrecs, perpage, limit, targets, torusquery) {
268 log("newSearch: " + query);
270 if (config.use_service_proxy && !mkws.authenticated) {
271 alert("searching before authentication");
275 m_filterSet.removeMatching(function(f) { return f.type !== 'category' });
276 triggerSearch(query, sortOrder, maxrecs, perpage, limit, targets, torusquery);
277 switchView('records'); // In case it's configured to start off as hidden
280 that.newSearch = newSearch;
283 function triggerSearch(query, sortOrder, maxrecs, perpage, limit, targets, torusquery) {
285 queue("navi").publish();
287 // Continue to use previous query/sort-order unless new ones are specified
288 if (query) m_query = query;
289 if (sortOrder) m_sortOrder = sortOrder;
290 if (perpage) m_perpage = perpage;
291 if (targets) m_filterSet.add(targetFilter(targets, targets));
293 var pp2filter = m_filterSet.pp2filter();
294 var pp2limit = m_filterSet.pp2limit(limit);
295 var pp2catLimit = m_filterSet.pp2catLimit();
297 pp2filter = pp2filter ? pp2filter + "," + pp2catLimit : pp2catLimit;
301 if (pp2limit) params.limit = pp2limit;
302 if (maxrecs) params.maxrecs = maxrecs;
304 if (!mkws.config.use_service_proxy)
305 alert("can't narrow search by torusquery when not authenticated");
306 params.torusquery = torusquery;
309 log("triggerSearch(" + m_query + "): filters = " + m_filterSet.toJSON() + ", " +
310 "pp2filter = " + pp2filter + ", params = " + $.toJSON(params));
312 m_paz.search(m_query, m_perpage, m_sortOrder, pp2filter, undefined, params);
315 // fetch record details to be retrieved from the record queue
316 that.fetchDetails = function(recId) {
317 log("fetchDetails() requesting record '" + recId + "'");
322 // switching view between targets and records
323 function switchView(view) {
324 var targets = widgetNode('Targets');
325 var results = widgetNode('Results') || widgetNode('Records');
326 var blanket = widgetNode('Blanket');
327 var motd = widgetNode('MOTD');
331 if (targets) $(targets).show();
332 if (results) $(results).hide();
333 if (blanket) $(blanket).hide();
334 if (motd) $(motd).hide();
337 if (targets) $(targets).hide();
338 if (results) $(results).show();
339 if (blanket) $(blanket).show();
340 if (motd) $(motd).hide();
343 alert("Unknown view '" + view + "'");
346 that.switchView = switchView;
349 // detailed record drawing
350 that.showDetails = function(recId) {
351 var oldRecordId = m_currentRecordId;
352 m_currentRecordId = recId;
354 // remove current detailed view if any
355 findnode('#' + recordDetailsId(oldRecordId)).remove();
357 // if the same clicked, just hide
358 if (recId == oldRecordId) {
359 m_currentRecordId = '';
360 m_currentRecordData = null;
363 // request the record
364 log("showDetails() requesting record '" + recId + "'");
369 // Finds the node of the specified class within the current team
370 function findnode(selector, teamName) {
371 teamName = teamName || m_teamName;
373 if (teamName === 'AUTO') {
374 selector = (selector + '.mkwsTeam_' + teamName + ',' +
375 selector + ':not([class^="mkwsTeam"],[class*=" mkwsTeam"])');
377 selector = selector + '.mkwsTeam_' + teamName;
380 var node = $(selector);
381 //log('findnode(' + selector + ') found ' + node.length + ' nodes');
386 function widgetNode(type) {
387 var w = that.widget(type);
388 return w ? w.node : undefined;
391 function renderDetails(data, marker) {
392 var template = loadTemplate("Record");
393 var details = template(data);
394 return '<div class="mkwsDetails mkwsTeam_' + m_teamName + '" ' +
395 'id="' + recordDetailsId(data.recid[0]) + '">' + details + '</div>';
397 that.renderDetails = renderDetails;
400 that.registerTemplate = function(name, text) {
401 m_templateText[name] = text;
405 function loadTemplate(name, fallbackString) {
406 var template = m_template[name];
407 if (template === undefined && Handlebars.compile) {
409 var node = $(".mkwsTemplate_" + name + " .mkwsTeam_" + that.name());
410 if (node && node.length < 1) {
411 node = $(".mkwsTemplate_" + name);
413 if (node) source = node.html();
414 if (!source) source = m_templateText[name];
416 template = Handlebars.compile(source);
417 log("compiled template '" + name + "'");
420 //if (template === undefined) template = mkws_templatesbyteam[m_teamName][name];
421 if (template === undefined && Handlebars.templates) {
422 template = Handlebars.templates[name];
424 if (template === undefined && mkws.defaultTemplates) {
425 template = mkws.defaultTemplates[name];
428 m_template[name] = template;
432 mkws.log("No MKWS template for " + name);
436 that.loadTemplate = loadTemplate;
439 that.addWidget = function(w) {
440 if (m_widgets[w.type] === undefined) {
441 m_widgets[w.type] = [ w ];
443 m_widgets[w.type].push(w);
447 that.widget = function(type) {
448 var list = m_widgets[type];
452 if (list.length > 1) {
453 alert("widget('" + type + "') finds " + list.length + " widgets: using first");
458 that.visitWidgets = function(callback) {
459 for (var type in m_widgets) {
460 var list = m_widgets[type];
461 for (var i = 0; i < list.length; i++) {
462 var res = callback(type, list[i]);
463 if (res !== undefined) {