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_tempateText = {}; // widgets can register tempates 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
34 that.toString = function() { return '[Team ' + teamName + ']'; };
36 // Accessor methods for individual widgets: readers
37 that.name = function() { return m_teamName; };
38 that.submitted = function() { return m_submitted; };
39 that.sortOrder = function() { return m_sortOrder; };
40 that.perpage = function() { return m_perpage; };
41 that.totalRecordCount = function() { return m_totalRecordCount; };
42 that.currentPage = function() { return m_currentPage; };
43 that.currentRecordId = function() { return m_currentRecordId; };
44 that.currentRecordData = function() { return m_currentRecordData; };
45 that.filters = function() { return m_filterSet; };
46 that.config = function() { return m_config; };
48 // Accessor methods for individual widgets: writers
49 that.set_sortOrder = function(val) { m_sortOrder = val };
50 that.set_perpage = function(val) { m_perpage = val };
53 // The following PubSub code is modified from the jQuery manual:
54 // http://api.jquery.com/jQuery.Callbacks/
57 // team.queue("eventName").subscribe(function(param1, param2 ...) { ... });
58 // team.queue("eventName").publish(arg1, arg2, ...);
63 var callbacks = $.Callbacks();
65 publish: callbacks.fire,
66 subscribe: callbacks.add,
67 unsubscribe: callbacks.remove
77 var timestamp = (((now - m_logTime.start)/1000).toFixed(3) + " (+" +
78 ((now - m_logTime.last)/1000).toFixed(3) + ") ");
80 mkws.log(m_teamName + ": " + timestamp + s);
81 that.queue("log").publish(m_teamName, timestamp, s);
86 log("start running MKWS");
88 m_sortOrder = m_config.sort_default;
89 m_perpage = m_config.perpage_default;
91 log("Create main pz2 object");
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(',')
108 // pz2.js event handlers:
115 function onBytarget(data) {
117 queue("targets").publish(data);
120 function onStat(data) {
121 queue("stat").publish(data);
122 if (parseInt(data.activeclients[0], 10) === 0)
123 queue("complete").publish(parseInt(data.hits[0], 10));
126 function onTerm(data) {
128 queue("termlists").publish(data);
131 function onShow(data, teamName) {
133 m_totalRecordCount = data.merged;
134 log("found " + m_totalRecordCount + " records");
135 queue("pager").publish(data);
136 queue("records").publish(data);
139 function onRecord(data, args, teamName) {
141 // FIXME: record is async!!
142 clearTimeout(m_paz.recordTimer);
143 var detRecordDiv = findnode(recordDetailsId(data.recid[0]));
144 if (detRecordDiv.length) {
145 // in case on_show was faster to redraw element
148 m_currentRecordData = data;
149 var recordDiv = findnode('.' + recordElementId(m_currentRecordData.recid[0]));
150 var html = renderDetails(m_currentRecordData);
151 $(recordDiv).append(html);
155 // Used by the Records widget and onRecord()
156 function recordElementId(s) {
157 return 'mkwsRec_' + s.replace(/[^a-z0-9]/ig, '_');
159 that.recordElementId = recordElementId;
161 // Used by onRecord(), showDetails() and renderDetails()
162 function recordDetailsId(s) {
163 return 'mkwsDet_' + s.replace(/[^a-z0-9]/ig, '_');
167 that.targetFiltered = function(id) {
168 return m_filterSet.targetFiltered(id);
172 that.limitTarget = function(id, name) {
173 log("limitTarget(id=" + id + ", name=" + name + ")");
174 m_filterSet.add(targetFilter(id, name));
175 if (m_query) triggerSearch();
180 that.limitQuery = function(field, value) {
181 log("limitQuery(field=" + field + ", value=" + value + ")");
182 m_filterSet.add(fieldFilter(field, value));
183 if (m_query) triggerSearch();
188 that.limitCategory = function(id) {
189 log("limitCategory(id=" + id + ")");
190 // Only one category filter at a time
191 m_filterSet.removeMatching(function(f) { return f.type === 'category' });
192 if (id !== '') m_filterSet.add(categoryFilter(id));
193 if (m_query) triggerSearch();
198 that.delimitTarget = function(id) {
199 log("delimitTarget(id=" + id + ")");
200 m_filterSet.removeMatching(function(f) { return f.type === 'target' });
201 if (m_query) triggerSearch();
206 that.delimitQuery = function(field, value) {
207 log("delimitQuery(field=" + field + ", value=" + value + ")");
208 m_filterSet.removeMatching(function(f) { return f.type == 'field' &&
209 field == f.field && value == f.value });
210 if (m_query) triggerSearch();
215 that.showPage = function(pageNum) {
216 m_currentPage = pageNum;
217 m_paz.showPage(m_currentPage - 1);
221 that.pagerNext = function() {
222 if (m_totalRecordCount - m_perpage*m_currentPage > 0) {
229 that.pagerPrev = function() {
230 if (m_paz.showPrev() != false)
235 that.reShow = function() {
237 m_paz.show(0, m_perpage, m_sortOrder);
241 function resetPage() {
243 m_totalRecordCount = 0;
245 that.resetPage = resetPage;
248 function newSearch(query, sortOrder, maxrecs, perpage, limit, targets, torusquery) {
249 log("newSearch: " + query);
251 if (m_config.use_service_proxy && !mkws.authenticated) {
252 alert("searching before authentication");
256 m_filterSet.removeMatching(function(f) { return f.type !== 'category' });
257 triggerSearch(query, sortOrder, maxrecs, perpage, limit, targets, torusquery);
258 switchView('records'); // In case it's configured to start off as hidden
261 that.newSearch = newSearch;
264 function triggerSearch(query, sortOrder, maxrecs, perpage, limit, targets, torusquery) {
266 queue("navi").publish();
268 // Continue to use previous query/sort-order unless new ones are specified
269 if (query) m_query = query;
270 if (sortOrder) m_sortOrder = sortOrder;
271 if (perpage) m_perpage = perpage;
272 if (targets) m_filterSet.add(targetFilter(targets, targets));
274 var pp2filter = m_filterSet.pp2filter();
275 var pp2limit = m_filterSet.pp2limit(limit);
276 var pp2catLimit = m_filterSet.pp2catLimit();
278 pp2filter = pp2filter ? pp2filter + "," + pp2catLimit : pp2catLimit;
282 if (pp2limit) params.limit = pp2limit;
283 if (maxrecs) params.maxrecs = maxrecs;
285 if (!mkws.config.use_service_proxy)
286 alert("can't narrow search by torusquery when Service Proxy is not in use");
287 params.torusquery = torusquery;
290 log("triggerSearch(" + m_query + "): filters = " + m_filterSet.toJSON() + ", " +
291 "pp2filter = " + pp2filter + ", params = " + $.toJSON(params));
293 m_paz.search(m_query, m_perpage, m_sortOrder, pp2filter, undefined, params);
297 // switching view between targets and records
298 function switchView(view) {
299 var targets = widgetNode('Targets');
300 var results = widgetNode('Results') || widgetNode('Records');
301 var blanket = widgetNode('Blanket');
302 var motd = widgetNode('MOTD');
306 if (targets) targets.css('display', 'block');
307 if (results) results.css('display', 'none');
308 if (blanket) blanket.css('display', 'none');
309 if (motd) motd.css('display', 'none');
312 if (targets) targets.css('display', 'none');
313 if (results) results.css('display', 'block');
314 if (blanket) blanket.css('display', 'block');
315 if (motd) motd.css('display', 'none');
318 alert("Unknown view '" + view + "'");
321 that.switchView = switchView;
324 // detailed record drawing
325 that.showDetails = function(recId) {
326 var oldRecordId = m_currentRecordId;
327 m_currentRecordId = recId;
329 // remove current detailed view if any
330 findnode('#' + recordDetailsId(oldRecordId)).remove();
332 // if the same clicked, just hide
333 if (recId == oldRecordId) {
334 m_currentRecordId = '';
335 m_currentRecordData = null;
338 // request the record
339 log("showDetails() requesting record '" + recId + "'");
344 // Translation function.
345 mkws.M = function (word) {
346 var lang = mkws.config.lang;
347 log("in M('" + word + "'), lang=" + lang);
349 if (!lang || !mkws.locale_lang[lang])
352 return mkws.locale_lang[lang][word] || word;
356 // Finds the node of the specified class within the current team
357 function findnode(selector, teamName) {
358 teamName = teamName || m_teamName;
360 if (teamName === 'AUTO') {
361 selector = (selector + '.mkwsTeam_' + teamName + ',' +
362 selector + ':not([class^="mkwsTeam"],[class*=" mkwsTeam"])');
364 selector = selector + '.mkwsTeam_' + teamName;
367 var node = $(selector);
368 //log('findnode(' + selector + ') found ' + node.length + ' nodes');
373 function widgetNode(type) {
374 var w = that.widget(type);
375 return w ? $(w.node) : undefined;
378 function renderDetails(data, marker) {
379 var template = loadTemplate("Record");
380 var details = template(data);
381 return '<div class="details mkwsTeam_' + m_teamName + '" ' +
382 'id="' + recordDetailsId(data.recid[0]) + '">' + details + '</div>';
384 that.renderDetails = renderDetails;
387 that.registerTemplate = function(name, text) {
388 m_tempateText[name] = text;
392 function loadTemplate(name) {
393 var template = m_template[name];
395 if (template === undefined) {
396 // Fall back to generic template if there is no team-specific one
398 var node = widgetNode("Template_" + name);
400 node = widgetNode("Template_" + name, "ALL");
403 source = node.html();
407 source = m_tempateText[name];
410 source = mkws.defaultTemplate(name);
413 template = Handlebars.compile(source);
414 log("compiled template '" + name + "'");
415 m_template[name] = template;
420 that.loadTemplate = loadTemplate;
423 that.addWidget = function(w) {
424 if (m_widgets[w.type] === undefined) {
425 m_widgets[w.type] = [ w ];
426 log("Added '" + w.type + "' widget to team '" + m_teamName + "'");
428 m_widgets[w.type].push(w);
429 log("Added '" + w.type + "' widget #" + m_widgets[w.type].length + "' to team '" + m_teamName + "'");
433 that.visitWidgets = function(callback) {
434 for (var type in m_widgets) {
435 var list = m_widgets[type];
436 for (var i = 0; i < list.length; i++) {
437 var res = callback(type, list[i]);
438 if (res !== undefined) {
446 that.widget = function(type) {
447 var list = m_widgets[type];
451 if (list.length > 1) {
452 alert("widget('" + type + "') finds " + list.length + " widgets: using first");
458 var lang = mkws.getParameterByName("lang") || mkws.config.lang;
459 if (!lang || !mkws.locale_lang[lang]) {
460 mkws.config.lang = ""
462 mkws.config.lang = lang;
465 log("Locale language: " + (mkws.config.lang ? mkws.config.lang : "none"));