Fix closing tag in iphone details. Remove the div navi.
[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 querys = {'su': '', 'au': '', 'xt': ''};
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
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_iphone(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
117         if (tab == "subjects") {
118                 document.getElementById("term_subjects").style.display = '';
119                 showtermlist = true;
120         }
121         else
122                 document.getElementById("term_subjects").style.display = 'none';
123
124         if (tab == "authors") {
125                 document.getElementById("term_authors").style.display = '';
126                 showtermlist = true;
127         }
128         else
129                 document.getElementById("term_authors").style.display = 'none';
130
131         if (showtermlist == false) 
132                 document.getElementById("termlist").style.display = 'none';
133         else 
134                 document.getElementById("termlist").style.display = '';
135 }
136
137 function my_onterm(data) {
138     var termlists = [];
139     
140     termlists.push('<div id="term_xtargets" >');
141     termlists.push('<h4 class="termtitle">Sources</h4>');
142     termlists.push('<ul>');
143     termlists.push('<li><a href="#" target_id="reset_xt" onclick="limitOrResetTarget(\'reset_xt\',\'All\');return false;">All</a></li>');
144     for (var i = 0; i < data.xtargets.length && i < SourceMax; i++ ) {
145         termlists.push('<li><a href="#" target_id='+data.xtargets[i].id
146             + ' onclick="limitOrResetTarget(this.getAttribute(\'target_id\'), \'' + data.xtargets[i].name + '\');return false;">' 
147             + data.xtargets[i].name + ' (' + data.xtargets[i].freq + ')</a></li>');
148     }
149     termlists.push('</ul>');
150     termlists.push('</div>');
151      
152     termlists.push('<div id="term_subjects" >');
153     termlists.push('<h4>Subjects</h4>');
154     termlists.push('<ul>');
155     termlists.push('<li><a href="#" target_id="reset_su" onclick="limitOrResetQuery(\'reset_su\',\'All\');return false;">All</a></li>');
156     for (var i = 0; i < data.subject.length && i < SubjectMax; i++ ) {
157         termlists.push('<li><a href="#" onclick="limitOrResetQuery(\'su\', \'' + data.subject[i].name + '\');return false;">' 
158                        + data.subject[i].name + ' (' + data.subject[i].freq + ')</a></li>');
159     }
160     termlists.push('</ul>');
161     termlists.push('</div>');
162             
163     termlists.push('<div id="term_authors" >');
164     termlists.push('<h4 class="termtitle">Authors</h4>');
165     termlists.push('<ul>');
166     termlists.push('<li><a href="#" onclick="limitOrResetQuery(\'reset_au\',\'All\');return false;">All<a></li>');
167     for (var i = 0; i < data.author.length && i < AuthorMax; i++ ) {
168         termlists.push('<li><a href="#" onclick="limitQuery(\'au\', \'' + data.author[i].name +'\');return false;">' 
169                             + data.author[i].name 
170                             + '  (' 
171                             + data.author[i].freq 
172                             + ')</a></li>');
173     }
174     termlists.push('</ul>');
175     termlists.push('</div>');
176     var termlist = document.getElementById("termlist");
177     replaceHtml(termlist, termlists.join(''));
178     showhide();
179 }
180
181 function serialize(array) {
182         var t = typeof (obj);
183         if (t != "object" || obj === null) {
184                 // simple data type
185                 return String(obj);
186         } else {
187                 // recurse array or object
188                 var n, v, json = [], arr = (obj && obj.constructor == Array);
189                 for (n in obj) {
190                         v = obj[n];
191                         t = typeof (v);
192                         if (t == "string")
193                                 v = '"' + v + '"';
194                         else if (t == "object" && v !== null)
195                                 v = JSON.stringify(v);
196                         json.push((arr ? "" : '"' + n + '":') + String(v));
197                 }
198                 return (arr ? "" : "") + String(json) + (arr ? "]" : "}");
199         }
200 }
201
202 var termlist = {};
203 function my_onterm_iphone(data) {
204     my_onterm(data);
205     var targets = "reset_xt|All\n";
206     
207     for (var i = 0; i < data.xtargets.length; i++ ) {
208         
209         targets = targets + data.xtargets[i].id + "|" + data.xtargets[i].name + "|" + data.xtargets[i].freq + "\n";
210     }
211     termlist["xtargets"] = targets;
212     var subjects = "reset_su|All\n";
213     for (var i = 0; i < data.subject.length; i++ ) {
214         subjects = subjects + "su" + "|" + data.subject[i].name + "|" + data.subject[i].freq + "\n";
215     }
216     termlist["subjects"] = subjects;
217     var authors = "reset_au|All\n";
218     for (var i = 0; i < data.author.length; i++ ) {
219         authors = authors + "au" + "|" + data.author[i].name + "|" + data.author[i].freq + "\n";
220     }
221     termlist["authors"] = authors;
222     //document.getElementById("log").innerHTML = targets + "\n" + subjects + "\n" + authors;
223     callback.send("termlist", "refresh");
224 }
225
226 function getTargets() {
227         return termlist['xtargets'];
228 }
229
230 function getSubjects() {
231         return termlist['subjects'];
232 }
233
234 function getAuthors() {
235         return termlist['authors'];
236 }
237
238 function my_onrecord(data) {
239     // FIXME: record is async!!
240     clearTimeout(my_paz.recordTimer);
241     // in case on_show was faster to redraw element
242     var detRecordDiv = document.getElementById('det_'+data.recid);
243     if (detRecordDiv) return;
244     curDetRecData = data;
245     var recordDiv = document.getElementById('recdiv_'+curDetRecData.recid);
246     var html = renderDetails_iphone(curDetRecData);
247     recordDiv.innerHTML += html;
248 }
249
250 function my_onrecord_iphone(data) {
251     my_onrecord(data);
252     callback.send("record", data.recid, data, data.xtargets[i].freq);
253 }
254
255
256 function my_onbytarget(data) {
257     var targetDiv = document.getElementById("bytarget");
258     var table ='<table><thead><tr><td>Target ID</td><td>Hits</td><td>Diags</td>'
259         +'<td>Records</td><td>State</td></tr></thead><tbody>';
260     
261     for (var i = 0; i < data.length; i++ ) {
262         table += "<tr><td>" + data[i].id +
263             "</td><td>" + data[i].hits +
264             "</td><td>" + data[i].diagnostic +
265             "</td><td>" + data[i].records +
266             "</td><td>" + data[i].state + "</td></tr>";
267     }
268
269     table += '</tbody></table>';
270     targetDiv.innerHTML = table;
271 }
272
273 ////////////////////////////////////////////////////////////////////////////////
274 ////////////////////////////////////////////////////////////////////////////////
275
276 // wait until the DOM is ready
277 function domReady () 
278
279     document.search.onsubmit = onFormSubmitEventHandler;
280     document.search.query.value = '';
281     document.select.sort.onchange = onSelectDdChange;
282     document.select.perpage.onchange = onSelectDdChange;
283     if (document.location.search.match("inApp=true")) 
284         applicationMode(true);
285 }
286  
287 function applicationMode(newmode) 
288 {
289         var searchdiv = document.getElementById("searchForm");
290         if (newmode)
291                 inApp = newmode;
292         if (inApp) {
293         document.getElementById("heading").style.display="none";
294         searchdiv.style.display = 'none';
295         }
296         else { 
297                 searchdiv.style.display = '';
298                 document.search.onsubmit = onFormSubmit;
299         }
300         callback.init();
301 }
302 // when search button pressed
303 function onFormSubmitEventHandler() 
304 {
305     resetPage();
306     loadSelect();
307     triggerSearch();
308     submitted = true;
309     return false;
310 }
311
312 function onSelectDdChange()
313 {
314     if (!submitted) return false;
315     resetPage();
316     loadSelect();
317     my_paz.show(0, recPerPage, curSort);
318     return false;
319 }
320
321 function resetPage()
322 {
323     curPage = 1;
324     totalRec = 0;
325 }
326
327 function triggerSearch ()
328 {
329     my_paz.search(document.search.query.value, recPerPage, curSort, curFilter);
330 }
331
332 function loadSelect ()
333 {
334     curSort = document.select.sort.value;
335     recPerPage = document.select.perpage.value;
336 }
337
338 // limit the query after clicking the facet
339 function limitQuery(field, value)
340 {
341         var newQuery = ' and ' + field + '="' + value + '"';
342         querys[field] += newQuery;
343     document.search.query.value += newQuery;
344     onFormSubmitEventHandler();
345     showhide("recordview");
346 }
347
348 //limit the query after clicking the facet
349 function removeQuery (field, value) {
350         document.search.query.value.replace(' and ' + field + '="' + value + '"', '');
351     onFormSubmitEventHandler();
352     showhide("recordview");
353 }
354
355 //limit the query after clicking the facet
356 function limitOrResetQuery (field, value, selected) {
357         if (field == 'reset_su' || field == 'reset_au') {
358                 var reset_field = field.substring(6);
359                 document.search.query.value = document.search.query.value.replace(querys[reset_field], '');
360                 querys[reset_field] = '';
361             onFormSubmitEventHandler();
362             showhide("recordview");
363         }
364         else 
365                 limitQuery(field, value);
366         //alert("limitOrResetQuerry: query after: " + document.search.query.value);
367 }
368
369 // limit by target functions
370 function limitTarget (id, name)
371 {
372     curFilter = 'pz:id=' + id;
373     resetPage();
374     loadSelect();
375     triggerSearch();
376     showhide("recordview");
377     return false;
378 }
379
380 function delimitTarget ()
381 {
382     curFilter = null; 
383     resetPage();
384     loadSelect();
385     triggerSearch();
386     return false;
387 }
388
389 function limitOrResetTarget(id, name) {
390         if (id == 'reset_xt') {
391                 delimitTarget();
392         }
393         else {
394                 limitTarget(id,name);
395         }
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: none">' 
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
549 function renderLine(title, value) {
550     if (value != undefined)
551         return '<li><h3>' + title + '</h3> <big>' + value + '</big></li>';
552     return '';
553 }
554
555 function renderLineURL(title, URL, display) {
556     if (URL != undefined)
557         return '<li><h3>' + title + '</h3> <a href="' + URL + '" target="_blank">' + display + '</a></li>';
558     return '';
559 }
560
561 function renderLineEmail(dtitle, email, display) {
562     if (email != undefined)
563         return '<li><h3>' + title + '</h3> <a href="mailto:' + email + '" target="_blank">' + display + '</a></li>';
564     return '';
565 }
566
567 function renderDetails_iphone(data, marker)
568 {
569         //return renderDetails(data,marker);
570
571
572     var details = ''
573 /*
574     details = '<div id="header" id="det_'+data.recid+'">' 
575         + '<h1>Detailed Info</h1>' 
576         + '<a id="backbutton" href="hidedetail(\'det_' + data.recid + '\')">Back</a>' 
577         + '</div>';
578 */
579     if (marker) 
580         details += '<h4>'+ marker + '</h4>'; 
581     details += '<ul class="field">';
582     if (data["md-title"] != undefined) {
583         details += '<li><h3>Title</h3> <big> ' + data["md-title"];
584         if (data["md-title-remainder"] !== undefined) {
585               details += ' ' + data["md-title-remainder"] + ' ';
586         }
587         if (data["md-title-responsibility"] !== undefined) {
588               details += '<i>'+ data["md-title-responsibility"] +'</i>';
589         }
590         details += '</big>'
591         details += '</li>'
592     }
593     details 
594         +=renderLine('Date',    data["md-date"])
595         + renderLine('Author',  data["md-author"])
596         + renderLineURL('URL',  data["md-electronic-url"], data["md-electronic-url"])
597         + renderLine('Subject', data["location"][0]["md-subject"]);
598     
599     if (data["location"][0]["@name"] != undefined)
600         details += renderLine('Location', data["location"][0]["@name"] + " (" +data["location"][0]["@id"] + ")");
601     details += '</ul>';
602     return details;
603 }
604
605 //EOF