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