new config mkws_switch: show/hide Records|Targets menu
[mkws-moved-to-github.git] / experiments / spclient / mkws.js
1 /* A very simple client that shows a basic usage of the pz2.js
2 */
3
4 // create a parameters array and pass it to the pz2's constructor
5 // then register the form submit event with the pz2.search function
6 // autoInit is set to true on default
7 var my_paz = new pz2( { "onshow": my_onshow,
8                     "showtime": 500,            //each timer (show, stat, term, bytarget) can be specified this way
9                     "pazpar2path": '/service-proxy/',
10                     "oninit": my_oninit,
11                     "onstat": my_onstat,
12                     "onterm": my_onterm,
13                     "termlist": "xtargets,subject,author",
14                     "onbytarget": my_onbytarget,
15                     "usesessions" : false,
16                     "showResponseType": '', // or "json" (for debugging?)
17                     "onrecord": my_onrecord } );
18 // some state vars
19 var curPage = 1;
20 var recPerPage = 20;
21 var totalRec = 0;
22 var curDetRecId = '';
23 var curDetRecData = null;
24 var curSort = 'relevance';
25 var curFilter = null;
26 var submitted = false;
27 var SourceMax = 16;
28 var SubjectMax = 10;
29 var AuthorMax = 10;
30
31 //
32 // pz2.js event handlers:
33 //
34 function my_oninit() {
35     my_paz.stat();
36     my_paz.bytarget();
37 }
38
39 function my_onshow(data) {
40     totalRec = data.merged;
41     // move it out
42     var pager = document.getElementById("pager");
43     pager.innerHTML = "";
44     pager.innerHTML +='<hr/><div style="float: right">Displaying: '
45                     + (data.start + 1) + ' to ' + (data.start + data.num) +
46                      ' of ' + data.merged + ' (found: '
47                      + data.total + ')</div>';
48     drawPager(pager);
49     // navi
50     var results = document.getElementById("results");
51
52     var html = [];
53     for (var i = 0; i < data.hits.length; i++) {
54         var hit = data.hits[i];
55               html.push('<div class="record" id="recdiv_'+hit.recid+'" >'
56             +'<span>'+ (i + 1 + recPerPage * (curPage - 1)) +'. </span>'
57             +'<a href="#" id="rec_'+hit.recid
58             +'" onclick="showDetails(this.id);return false;"><b>'
59             + hit["md-title"] +' </b></a>');
60               if (hit["md-title-remainder"] !== undefined) {
61                 html.push('<span>' + hit["md-title-remainder"] + ' </span>');
62               }
63               if (hit["md-title-responsibility"] !== undefined) {
64             html.push('<span><i>'+hit["md-title-responsibility"]+'</i></span>');
65         }
66         if (hit.recid == curDetRecId) {
67             html.push(renderDetails(curDetRecData));
68         }
69         html.push('</div>');
70     }
71     replaceHtml(results, html.join(''));
72 }
73
74 function my_onstat(data) {
75     var stat = document.getElementById("mkwsStat");
76     if (stat == null)
77         return;
78
79     stat.innerHTML = '<b>STATUS INFO</b> -- Active clients: '
80                         + data.activeclients
81                         + '/' + data.clients + ' -- </span>'
82                         + '<span>Retrieved records: ' + data.records
83                         + '/' + data.hits + ' :.</span>';
84 }
85
86 function my_onterm(data) {
87     var termlists = [];
88     termlists.push('<hr/><b>TERMLISTS:</b><hr/><div class="termtitle">Sources</div>');
89     for (var i = 0; i < data.xtargets.length && i < SourceMax; i++ ) {
90         termlists.push('<a href="#" target_id='+data.xtargets[i].id
91             + ' onclick="limitTarget(this.getAttribute(\'target_id\'), this.firstChild.nodeValue);return false;">' + data.xtargets[i].name
92         + ' </a><span> (' + data.xtargets[i].freq + ')</span><br/>');
93     }
94
95     termlists.push('<hr/><div class="termtitle">Subjects</div>');
96     for (var i = 0; i < data.subject.length && i < SubjectMax; i++ ) {
97         termlists.push('<a href="#" onclick="limitQuery(\'su\', this.firstChild.nodeValue);return false;">' + data.subject[i].name + '</a><span>  ('
98               + data.subject[i].freq + ')</span><br/>');
99     }
100
101     termlists.push('<hr/><div class="termtitle">Authors</div>');
102     for (var i = 0; i < data.author.length && i < AuthorMax; i++ ) {
103         termlists.push('<a href="#" onclick="limitQuery(\'au\', this.firstChild.nodeValue);return false;">'
104                             + data.author[i].name
105                             + ' </a><span> ('
106                             + data.author[i].freq
107                             + ')</span><br/>');
108     }
109     var termlist = document.getElementById("termlist");
110     replaceHtml(termlist, termlists.join(''));
111 }
112
113 function my_onrecord(data) {
114     // FIXME: record is async!!
115     clearTimeout(my_paz.recordTimer);
116     // in case on_show was faster to redraw element
117     var detRecordDiv = document.getElementById('det_'+data.recid);
118     if (detRecordDiv) return;
119     curDetRecData = data;
120     var recordDiv = document.getElementById('recdiv_'+curDetRecData.recid);
121     var html = renderDetails(curDetRecData);
122     recordDiv.innerHTML += html;
123 }
124
125 function my_onbytarget(data) {
126     var targetDiv = document.getElementById("bytarget");
127     var table ='<table><thead><tr><td>Target ID</td><td>Hits</td><td>Diags</td>'
128         +'<td>Records</td><td>State</td></tr></thead><tbody>';
129
130     for (var i = 0; i < data.length; i++ ) {
131         table += "<tr><td>" + data[i].id +
132             "</td><td>" + data[i].hits +
133             "</td><td>" + data[i].diagnostic +
134             "</td><td>" + data[i].records +
135             "</td><td>" + data[i].state + "</td></tr>";
136     }
137
138     table += '</tbody></table>';
139     targetDiv.innerHTML = table;
140 }
141
142 ////////////////////////////////////////////////////////////////////////////////
143 ////////////////////////////////////////////////////////////////////////////////
144
145 // wait until the DOM is ready
146 function domReady ()
147 {
148     document.search.onsubmit = onFormSubmitEventHandler;
149     document.search.query.value = '';
150     document.select.sort.onchange = onSelectDdChange;
151     document.select.perpage.onchange = onSelectDdChange;
152 }
153
154 // when search button pressed
155 function onFormSubmitEventHandler()
156 {
157     resetPage();
158     loadSelect();
159     triggerSearch();
160     submitted = true;
161     return false;
162 }
163
164 function onSelectDdChange()
165 {
166     if (!submitted) return false;
167     resetPage();
168     loadSelect();
169     my_paz.show(0, recPerPage, curSort);
170     return false;
171 }
172
173 function resetPage()
174 {
175     curPage = 1;
176     totalRec = 0;
177 }
178
179 function triggerSearch ()
180 {
181     my_paz.search(document.search.query.value, recPerPage, curSort, curFilter);
182 }
183
184 function loadSelect ()
185 {
186     curSort = document.select.sort.value;
187     recPerPage = document.select.perpage.value;
188 }
189
190 // limit the query after clicking the facet
191 function limitQuery (field, value)
192 {
193     document.search.query.value += ' and ' + field + '="' + value + '"';
194     onFormSubmitEventHandler();
195 }
196
197 // limit by target functions
198 function limitTarget (id, name)
199 {
200     var navi = document.getElementById('navi');
201     navi.innerHTML =
202         'Source: <a class="crossout" href="#" onclick="delimitTarget();return false;">'
203         + name + '</a>';
204     navi.innerHTML += '<hr/>';
205     curFilter = 'pz:id=' + id;
206     resetPage();
207     loadSelect();
208     triggerSearch();
209     return false;
210 }
211
212 function delimitTarget ()
213 {
214     var navi = document.getElementById('navi');
215     navi.innerHTML = '';
216     curFilter = null;
217     resetPage();
218     loadSelect();
219     triggerSearch();
220     return false;
221 }
222
223 function drawPager (pagerDiv)
224 {
225     //client indexes pages from 1 but pz2 from 0
226     var onsides = 6;
227     var pages = Math.ceil(totalRec / recPerPage);
228
229     var firstClkbl = ( curPage - onsides > 0 )
230         ? curPage - onsides
231         : 1;
232
233     var lastClkbl = firstClkbl + 2*onsides < pages
234         ? firstClkbl + 2*onsides
235         : pages;
236
237     var prev = '<span id="prev">&#60;&#60; Prev</span><b> | </b>';
238     if (curPage > 1)
239         prev = '<a href="#" id="prev" onclick="pagerPrev();">'
240         +'&#60;&#60; Prev</a><b> | </b>';
241
242     var middle = '';
243     for(var i = firstClkbl; i <= lastClkbl; i++) {
244         var numLabel = i;
245         if(i == curPage)
246             numLabel = '<b>' + i + '</b>';
247
248         middle += '<a href="#" onclick="showPage(' + i + ')"> '
249             + numLabel + ' </a>';
250     }
251
252     var next = '<b> | </b><span id="next">Next &#62;&#62;</span>';
253     if (pages - curPage > 0)
254         next = '<b> | </b><a href="#" id="next" onclick="pagerNext()">'
255         +'Next &#62;&#62;</a>';
256
257     var predots = '';
258     if (firstClkbl > 1)
259         predots = '...';
260
261     var postdots = '';
262     if (lastClkbl < pages)
263         postdots = '...';
264
265     pagerDiv.innerHTML += '<div style="float: clear">'
266         + prev + predots + middle + postdots + next + '</div><hr/>';
267 }
268
269 function showPage (pageNum)
270 {
271     curPage = pageNum;
272     my_paz.showPage( curPage - 1 );
273 }
274
275 // simple paging functions
276
277 function pagerNext() {
278     if ( totalRec - recPerPage*curPage > 0) {
279         my_paz.showNext();
280         curPage++;
281     }
282 }
283
284 function pagerPrev() {
285     if ( my_paz.showPrev() != false )
286         curPage--;
287 }
288
289 // swithing view between targets and records
290
291 function switchView(view) {
292
293     var targets = document.getElementById('mkwsTargets');
294     var records = document.getElementById('mkwsRecords');
295
296     switch(view) {
297         case 'targets':
298             targets.style.display = "block";
299             records.style.display = "none";
300             break;
301         case 'records':
302             targets.style.display = "none";
303             records.style.display = "block";
304             break;
305         default:
306             alert('Unknown view.');
307     }
308 }
309
310 // detailed record drawing
311 function showDetails (prefixRecId) {
312     var recId = prefixRecId.replace('rec_', '');
313     var oldRecId = curDetRecId;
314     curDetRecId = recId;
315
316     // remove current detailed view if any
317     var detRecordDiv = document.getElementById('det_'+oldRecId);
318     // lovin DOM!
319     if (detRecordDiv)
320       detRecordDiv.parentNode.removeChild(detRecordDiv);
321
322     // if the same clicked, just hide
323     if (recId == oldRecId) {
324         curDetRecId = '';
325         curDetRecData = null;
326         return;
327     }
328     // request the record
329     my_paz.record(recId);
330 }
331
332 function replaceHtml(el, html) {
333   var oldEl = typeof el === "string" ? document.getElementById(el) : el;
334   /*@cc_on // Pure innerHTML is slightly faster in IE
335     oldEl.innerHTML = html;
336     return oldEl;
337     @*/
338   var newEl = oldEl.cloneNode(false);
339   newEl.innerHTML = html;
340   oldEl.parentNode.replaceChild(newEl, oldEl);
341   /* Since we just removed the old element from the DOM, return a reference
342      to the new element, which can be used to restore variable references. */
343   return newEl;
344 };
345
346 function renderDetails(data, marker)
347 {
348     var details = '<div class="details" id="det_'+data.recid+'"><table>';
349     if (marker) details += '<tr><td>'+ marker + '</td></tr>';
350     if (data["md-title"] != undefined) {
351         details += '<tr><td><b>Title</b></td><td><b>:</b> '+data["md-title"];
352         if (data["md-title-remainder"] !== undefined) {
353               details += ' : <span>' + data["md-title-remainder"] + ' </span>';
354         }
355         if (data["md-title-responsibility"] !== undefined) {
356               details += ' <span><i>'+ data["md-title-responsibility"] +'</i></span>';
357         }
358           details += '</td></tr>';
359     }
360     if (data["md-date"] != undefined)
361         details += '<tr><td><b>Date</b></td><td><b>:</b> ' + data["md-date"] + '</td></tr>';
362     if (data["md-author"] != undefined)
363         details += '<tr><td><b>Author</b></td><td><b>:</b> ' + data["md-author"] + '</td></tr>';
364     if (data["md-electronic-url"] != undefined)
365         details += '<tr><td><b>URL</b></td><td><b>:</b> <a href="' + data["md-electronic-url"] + '" target="_blank">' + data["md-electronic-url"] + '</a>' + '</td></tr>';
366     if (data["location"][0]["md-subject"] != undefined)
367         details += '<tr><td><b>Subject</b></td><td><b>:</b> ' + data["location"][0]["md-subject"] + '</td></tr>';
368     if (data["location"][0]["@name"] != undefined)
369         details += '<tr><td><b>Location</b></td><td><b>:</b> ' + data["location"][0]["@name"] + " (" +data["location"][0]["@id"] + ")" + '</td></tr>';
370     details += '</table></div>';
371     return details;
372 }
373
374 /*
375  * All the HTML stuff to render the search forms and
376  * result pages.
377  */
378 function mkws_html_all(data) {
379
380     var config = {
381         sort: [ ["relevance"], ["title:1", "title"], ["date:0", "newest"], ["date:1", "oldest"]],
382         perpage: [10, 20, 30, 50],
383         sort_default: "relevance",
384         perpage_default: 20,
385         query_width: 50,
386         mkws_switch: true, /* show/hide Records|Targets menu */
387
388         dummy: "dummy"
389     };
390
391     $("#mkwsSwitch").html($("<a/>", {
392         href: '#',
393         onclick: "switchView(\'records\')",
394         text: "Records",
395     }));
396     $("#mkwsSwitch").append($("<span/>", { text: " | " }));
397     $("#mkwsSwitch").append($("<a/>", {
398         href: '#',
399         onclick: "switchView(\'targets\')",
400         text: "Targets",
401     }));
402
403     if (!config.mkws_switch) {
404         $("#mkwsSwitch").css("display", "none");
405     }
406
407     // For some reason, doing this programmatically results in
408     // document.search.query being undefined, hence the raw HTML.
409     $("#mkwsSearch").html('\
410     <form id="searchForm" name="search">\
411       <input id="query" type="text" size="50" />\
412       <input id="button" type="submit" value="Search" />\
413     </form>');
414
415     $("#mkwsRecords").html('\
416       <table width="100%" border="0" cellpadding="6" cellspacing="0">\
417         <tr>\
418           <td width="250" valign="top">\
419             <div id="termlist"></div>\
420           </td>\
421           <td valign="top">\
422             <div id="ranking">\
423               <form name="select" id="select">\
424         Sort by\
425         <select name="sort" id="sort"><option value="relevance" selected="selected">relevance</option><option value="title:1">title</option><option value="date:0">newest</option><option value="date:1">oldest</option></select>\
426         and show \
427         <select name="perpage" id="perpage"><option value="10">10</option><option value="20" selected="selected">20</option><option value="30">30</option><option value="50">50</option></select>\
428         per page.\
429        </form>\
430             </div>\
431             <div id="pager"></div>\
432             <div id="navi"></div>\
433             <div id="results"></div>\
434           </td>\
435         </tr>\
436       </table>\
437     </div>');
438
439     $("#mkwsTargets").html('\
440       <div id="bytarget">\
441        No information available yet.\
442       </div>');
443     $("#mkwsTargets").css("display", "none");
444
445     domReady();
446 }
447
448 /* 
449  * Run service-proxy authentication in background (after page load).
450  * The username/password is configured in the apache config file
451  * for the site.
452  */
453 function mkws_service_proxy_auth() {
454     var jqxhr = jQuery.get("/service-proxy-auth")
455         .fail(function() {
456             alert("service proxy authentication failed, give up!");
457         })
458         .success(function(data) {
459             if (!jQuery.isXMLDoc(data)) {
460                 alert("service proxy auth response document is not valid XML document, give up!");
461                 return;
462             }
463             var status = $(data).find("status");
464             if (status.text() != "OK") {
465                 alert("service proxy auth repsonse status: " + status.text() + ", give up!");
466                 return;
467             }
468         });
469 }
470
471 $(document).ready(function() { mkws_html_all(); });
472 $(document).ready(function() { mkws_service_proxy_auth(); });
473