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