Handling different window size. URL is now set correct for SP to restart a stalled...
[pazpar2-moved-to-github.git] / www / mobile / mobile_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 = false;
8 var pazpar2path = '/service-proxy/';
9 var showResponseType = '';
10 // Facet configuration
11 var querys = {'su': '', 'au': '', 'xt': ''};
12 var query_client_server = {'su': 'subject', 'au': 'author', 'xt': 'xtargets'};
13 var querys_server = {};
14 var useLimit = 1;
15 var state = new State();
16 // Fail to get JSON working stabil.
17 var showResponseType = 'xml';
18 //some state vars
19 state.curPage = 1;
20 state.recPerPage = 5;
21 var recToShowPageSize = 20;
22 var recToShow = recToShowPageSize;
23 var recIDs = {};
24 var totalRec = 0;
25 var curDetRecId = '';
26 var curDetRecData = null;
27 var curSort = 'relevance';
28 var curFilter = 'ALL';
29 var submitted = false;
30 var SourceMax = 16;
31 var SubjectMax = 10;
32 var AuthorMax = 10;
33 var tab = "recordview"; 
34
35 var triedPass = "";
36 var triedUser = "";
37
38 var previousOrientation = 0;
39
40
41 window.addEventListener("load",function() {
42   // Set a timeout...
43   setTimeout(function(){
44     // Hide the address bar!
45     window.scrollTo(0, 1);
46   }, 0);
47 });
48
49 function calcRecPerPage() {
50   state.recPerPage = 5;
51   state.width = window.innerWidth;
52   state.height = window.innerHeight;
53   state.recPerPage = Math.max(Math.round((state.height - 88 - 40) / 60), 5) ; 
54   
55 }
56
57 function checkOrientation() {
58     if(window.orientation && window.orientation !== previousOrientation){
59         previousOrientation = window.orientation;
60         calcRecPerPage();
61     }
62 };
63
64 calcRecPerPage(); 
65
66 window.addEventListener("resize", checkOrientation, false);
67 window.addEventListener("orientationchange", checkOrientation, false);
68
69 // (optional) Android doesn't always fire orientationChange on 180 degree turns
70 setInterval(checkOrientation, 2000);
71
72 var imageHelper = new ImageHelper();
73
74 if (document.location.hash == '#pazpar2' || document.location.search.match("useproxy=false")) {
75     usesessions = true;
76     pazpar2path = '/pazpar2/search.pz2';
77     showResponseType = 'xml';
78 }
79
80 my_paz = new pz2( { "onshow": my_onshow,
81 //                    "showtime": 2000,            //each timer (show, stat, term, bytarget) can be specified this way
82                     "pazpar2path": pazpar2path,
83                     "oninit": my_oninit,
84                     "onstat": null,
85                     "onterm": my_onterm_iphone,
86                     "termlist": "xtargets,subject,author",
87                     "onbytarget": null,
88                     "usesessions" : usesessions,
89                     "showResponseType": showResponseType,
90                     "onrecord": my_onrecord,
91                     "errorhandler" : my_onerror} 
92 );
93
94 //
95 // pz2.js event handlers:
96 //
97 function my_onerror(error) {
98     switch(error.code) {
99         // No targets!
100     case "8": alert("No resources were selected for the search"); break;
101         // target not configured, this is a pazpar2 bug
102         // but for now simply research
103     case "9": 
104         triggerSearch(); 
105         break;
106         
107         // Already blocked 
108     case "13": 
109         // ignore
110         break
111         // authentication
112     case "100" : 
113         auth.check(loggedIn, login);
114         break;
115     default: 
116         alert("Unhandled error: " + error.code);
117         throw error; // display error in JavaScript console
118     }
119 }
120
121 //FF has a bug and un-escaped location.hash, don't use it
122 function getRealHash() {
123   var i = window.location.href.indexOf('#');
124   return i > -1 ? window.location.href.substr(i) : "";
125 }
126
127 function loginFormSubmit() {
128     triedUser = document.loginForm.username.value;
129     triedPass = document.loginForm.password.value;
130     auth.login( {"username": triedUser,
131                 "password": triedPass},
132         authCb, authCb);
133 }
134
135 function handleKeyPress(e)  
136 {  
137   var key;  
138   if(window.event)  
139     key = window.event.keyCode;  
140   else  
141     key = e.which;  
142
143   if(key == 13 || key == 10)  
144   {  
145       button = document.getElementById('button');
146       button.focus();
147       button.click();
148
149       return false;  
150   }  
151   else  
152     return true;  
153 }  
154
155 function authCb(authData) {
156     if (!authData.loginFailed) {
157         triedUser = "";
158         triedPass = "";
159     }
160
161     if (authData.loggedIn == true) {        
162         showhide("recordview");
163     }
164 }
165
166 function logOutClick() {
167     auth.logOut(authCb, authCb);
168 }
169
170 function loggedOut() {
171     var login = document.getElementById("login");
172     login.innerHTML = 'Login';
173 }
174
175 function loggingOutFailed() {
176     alert("Logging out failed");
177 }
178
179 function login() {
180     showhide("login");
181 }
182
183 function logout() {
184     auth.logOut(loggedOut, loggingOutFailed, true);
185 }
186
187 function logInOrOut() {
188     var loginElement = document.getElementById("login");
189     if (loginElement.innerHTML == 'Login')
190         login();
191     else
192         logout();
193 }
194 function loggedIn() {
195     var login = document.getElementById("login");
196     login.innerHTML = 'Logout';
197     document.getElementById("log").innerHTML = login.innerHTML;
198 }
199
200 function auth_check() {
201     auth.check(loggedIn, login);
202     domReady();
203 }
204
205
206 function auth_check_item(methods) {
207   auth.check(itemMain, function () { window.location = "login.html" + window.location.search + "&page="+window.location.pathname;}, methods );
208 }
209
210 //when page loads
211 function itemMain() {
212   mk_showPage();
213   if (auth.styleCss && document.getElementById("stylesheet")) {
214       document.getElementById("stylesheet").href = auth.styleCss;
215   }
216
217   // parse HTTP GET params (!!!)
218   window.location.parameters = parseQueryString(window.location.search);
219   var params = window.location.parameters;
220   // query params used by optional record_facets.js
221   if (window.RecordFacets != undefined) {
222     this.recordFacets = new RecordFacets();
223     this.recordFacets.setRequestParams(params);
224   }
225   prefixRecId = params["prefixrecid"];
226   query_state = params["query_state"];
227   recQuery = params["recordquery"];    
228   // load templating components
229 /*
230   loadComponents();
231   renderComponent("authLogoComp", auth);
232   renderComponent("authInfoComp", auth);
233   renderComponent("infoComp",null);    
234   renderComponent("backToSearchComp",query_state);
235 */
236   my_paz = new pz2( {"pazpar2path": auth.servicePath,
237                              "usesessions" : usesessions,
238                      "errorhandler" : my_onerror,
239                      "onrecord" : my_onrecord
240   });
241   
242   // http params have highest priority
243   showDetails(prefixRecId,recQuery);
244 }
245
246
247 //
248 // Pz2.js event handlers:
249 //
250 function my_oninit() {
251     my_paz.stat();
252     my_paz.bytarget();
253 }
254
255 function showMoreRecords() {
256     var i = recToShow;
257     recToShow += recToShowPageSize;
258     for ( ; i < recToShow && i < state.recPerPage; i++) {
259         var element = document.getElementById(recIDs[i]);
260         if (element)
261             element.style.display = '';
262     }
263     if (i == state.recPerPage) {
264         var element = document.getElementById('recdiv_END');
265         if (element)
266             element.style.display = 'none';
267     }
268 }
269
270 function hideRecords() {
271     for ( var i = 0; i < recToShow; i++) {
272         var element = document.getElementById(recIDs[i]);
273         if (element && recIDs != curDetRecId)
274             element.style.display = 'none';
275     }
276     var element = document.getElementById('recdiv_END');
277     if (element)
278         element.style.display = 'none';
279 }
280
281 function showRecords() {
282     for (var i = 0 ; i < recToShow && i < state.recPerPage; i++) {
283         var element = document.getElementById(recIDs[i]);
284         if (element)
285             element.style.display = '';
286     }
287     var element = document.getElementById('recdiv_END');
288     if (element) {
289         if (i == state.recPerPage)
290             element.style.display = 'none';
291         else
292             element.style.display = '';
293     }
294 }
295
296 function my_onshow(data) {
297   hideLogo();
298   totalRec = data.merged;
299     // move it out
300     var pager = document.getElementById("pager");
301     pager.innerHTML = "";
302     drawPager(pager);
303     pager.innerHTML +='<div class="status">Displaying: ' 
304                     + (data.start + 1) + ' to ' + (data.start + data.num) +
305                      ' of ' + data.merged + ' (found: ' 
306                      + data.total + ')</div>';
307
308     var results = document.getElementById("results");
309     
310     var html = [];
311     if (data.hits == undefined) 
312         return ;
313     var style = '';
314     for (var i = 0; i < data.hits.length; i++) {
315         var hit = data.hits[i];
316         var recDivID = "recdiv_" + hit.recid; 
317         recIDs[i] = recDivID;
318         var lines = 0;
319         if (i == recToShow)
320             style = ' style="display:none" ';
321         html.push('<li class="img" id="' + recDivID + '" ' + style +  '>' );
322         html.push('<a class="img" href="#' + i + '" id="rec_'+hit.recid + '" onclick="showDetails(this.id);return false;" >');
323         if (1) {
324             var useThumbnails = hit["md-use_thumbnails"];
325             var thumburls = hit["md-thumburl"];
326             if (thumburls && (useThumbnails == undefined || useThumbnails == "1")) {
327                 var thumbnailtag = imageHelper.getImageTagByRecId(hit.recid,"md-thumburl", 60, "S"); 
328                 html.push(thumbnailtag);
329             } else { 
330                 if (hit["md-isbn"] != undefined) { 
331                     var coverimagetag = imageHelper.getImageTagByRecId(hit.recid, "md-isbn", 60, "S"); 
332                     if (coverimagetag.length>0) { 
333                         html.push(coverimagetag);
334                     } else { 
335                         html.push("&nbsp;");
336                     }
337                 }
338             }
339         } 
340         html.push("</a>");
341         html.push('<a href="#" id="rec_'+hit.recid + '" onclick="showDetails(this.id);return false;">');
342         html.push(hit["md-title"]); 
343         html.push("</a>");
344
345         if (hit["md-title-remainder"] != undefined) {
346             html.push('<a href="#" id="rec_'+hit.recid + '" onclick="showDetails(this.id);return false;">');
347             html.push(hit["md-title-remainder"]);
348             html.push("</a>");
349             lines++;
350         }
351         if (hit["md-author"] != undefined) {
352             html.push('<a href="#" id="rec_'+hit.recid + '" onclick="showDetails(this.id);return false;">');
353             html.push(hit["md-author"]);
354             html.push("</a>");
355             lines++;
356         }
357         else if (hit["md-title-responsibility"] != undefined) {
358             html.push('<a href="#" id="rec_'+hit.recid + '" onclick="showDetails(this.id);return false;">');
359             html.push(hit["md-title-responsibility"]);
360             html.push("</a>");
361             lines++;
362         }
363         for (var idx = lines ; idx < 2 ; idx++) {
364             html.push('<a href="#" id="rec_'+hit.recid + '" onclick="showDetails(this.id);return false;">');
365             html.push("&nbsp;");            
366             html.push("</a>");
367         }
368 /*      
369         html.push('<a href="go.html" id="rec_'+ hit.recid + '" >');
370         html.push("item page;");            
371         html.push("</a>");
372 */
373 /*
374         if (hit.recid == curDetRecId) {
375             html.push(renderDetails_iphone(curDetRecData));
376         }
377 */
378         html.push('</li>');
379     }
380     if (data.activeclients == 0)
381       finishLoading();
382 /*
383     // set up "More..." if needed. 
384     style = 'display:none';
385     if (recToShow < recPerPage) {
386         style = 'display:block';
387     }
388     html.push('<li class="img" id="recdiv_END" style="' + style + '"><a onclick="showMoreRecords()">More...</a></li>');     
389 */
390     replaceHtml(results, html.join(''));
391 }
392
393 function my_onstat(data) {
394     var stat = document.getElementById("stat");
395     if (stat == null)
396         return;
397     
398     stat.innerHTML = '<b> .:STATUS INFO</b> -- Active clients: '
399                         + data.activeclients
400                         + '/' + data.clients + ' -- </span>'
401                         + '<span>Retrieved records: ' + data.records
402                         + '/' + data.hits + ' :.</span>';
403 }
404
405 function showhide(newtab, hash) {
406     var showtermlist = false;
407     if (newtab != null)
408         tab = newtab;
409     
410     if (tab == "recordview") {
411         document.getElementById("recordview").style.display = '';
412         if (hash != undefined)
413             document.location.hash = hash;
414     }
415     else 
416         document.getElementById("recordview").style.display = 'none';
417
418     if (tab == "xtargets") {
419         document.getElementById("term_xtargets").style.display = '';
420         showtermlist = true;
421     }
422     else
423         document.getElementById("term_xtargets").style.display = 'none';
424
425     if (tab == "subjects") {
426         document.getElementById("term_subjects").style.display = '';
427         showtermlist = true;
428     }
429     else
430         document.getElementById("term_subjects").style.display = 'none';
431
432     if (tab == "authors") {
433         document.getElementById("term_authors").style.display = '';
434         showtermlist = true;
435     }
436     else
437         document.getElementById("term_authors").style.display = 'none';
438
439     if (tab == "detailview") {
440         document.getElementById("detailview").style.display = '';
441     }
442     else {
443         document.getElementById("detailview").style.display = 'none';
444         var element = document.getElementById("rec_" + curDetRecId);
445         if (element != undefined)
446             element.scrollIntoView();
447
448     }
449     if (showtermlist == false) 
450         document.getElementById("termlist").style.display = 'none';
451     else 
452         document.getElementById("termlist").style.display = '';
453
454     var tabDiv = document.getElementById("loginDiv");
455     if (tab == "login") {
456         tabDiv.style.display = '';
457     }
458     else {
459         tabDiv.style.display = 'none';
460     }
461 }
462
463 function my_onterm(data) {
464     var termlists = [];
465     
466     termlists.push('<div id="term_xtargets" >');
467     termlists.push('<h4 class="termtitle">Sources</h4>');
468     termlists.push('<ul class="termlist">');
469     termlists.push('<li> <a href="#" target_id="reset_xt" onclick="limitOrResetTarget(\'reset_xt\',\'All\');return false;">All</a></li>');
470     for (var i = 0; i < data.xtargets.length && i < SourceMax; i++ ) {
471         termlists.push('<li class="termlist"><a href="#" target_id='+data.xtargets[i].id
472             + ' onclick="limitOrResetTarget(this.getAttribute(\'target_id\'), \'' + data.xtargets[i].name + '\');return false;">' 
473             + data.xtargets[i].name + ' (' + data.xtargets[i].freq + ')</a></li>');
474     }
475     termlists.push('</ul>');
476     termlists.push('</div>');
477      
478     termlists.push('<div id="term_subjects" >');
479     termlists.push('<h4>Subjects</h4>');
480     termlists.push('<ul class="termlist">');
481     termlists.push('<li><a href="#" target_id="reset_su" onclick="limitOrResetQuery(\'reset_su\',\'All\');return false;">All</a></li>');
482     for (var i = 0; i < data.subject.length && i < SubjectMax; i++ ) {
483         termlists.push('<li><a href="#" onclick="limitOrResetQuery(\'su\', \'' + data.subject[i].name + '\');return false;">' 
484                        + data.subject[i].name + ' (' + data.subject[i].freq + ')</a></li>');
485     }
486     termlists.push('</ul>');
487     termlists.push('</div>');
488             
489     termlists.push('<div id="term_authors" >');
490     termlists.push('<h4 class="termtitle">Authors</h4>');
491     termlists.push('<ul class="termlist">');
492     termlists.push('<li><a href="#" onclick="limitOrResetQuery(\'reset_au\',\'All\');return false;">All</a></li>');
493     for (var i = 0; i < data.author.length && i < AuthorMax; i++ ) {
494         termlists.push('<li><a href="#" onclick="limitOrResetQuery(\'au\', \'' + data.author[i].name +'\');return false;">' 
495                             + data.author[i].name 
496                             + '  (' 
497                             + data.author[i].freq 
498                             + ')</a></li>');
499     }
500     termlists.push('</ul>');
501     termlists.push('</div>');
502     var termlist = document.getElementById("termlist");
503     replaceHtml(termlist, termlists.join(''));
504     showhide();
505 }
506
507 var termlist = {};
508 function my_onterm_iphone(data) {
509     my_onterm(data);
510     var targets = "reset_xt|All\n";
511     
512     for (var i = 0; i < data.xtargets.length; i++ ) {
513         
514         targets = targets + data.xtargets[i].id + "|" + data.xtargets[i].name + "|" + data.xtargets[i].freq + "\n";
515     }
516     termlist["xtargets"] = targets;
517     var subjects = "reset_su|All\n";
518     for (var i = 0; i < data.subject.length; i++ ) {
519         subjects = subjects + "su" + "|" + data.subject[i].name + "|" + data.subject[i].freq + "\n";
520     }
521     termlist["subjects"] = subjects;
522     var authors = "reset_au|All\n";
523     for (var i = 0; i < data.author.length; i++ ) {
524         authors = authors + "au" + "|" + data.author[i].name + "|" + data.author[i].freq + "\n";
525     }
526     termlist["authors"] = authors;
527     callback.send("termlist", "refresh");
528 }
529
530 function getTargets() {
531         return termlist['xtargets'];
532 }
533
534 function getSubjects() {
535         return termlist['subjects'];
536 }
537
538 function getAuthors() {
539         return termlist['authors'];
540 }
541
542 function my_onrecord(data) {
543
544     // FIXME: record is async!!
545     clearTimeout(my_paz.recordTimer);
546     // in case on_show was faster to redraw element
547     var detailRecordDiv = document.getElementById('detailrecord');
548     if (!detailRecordDiv) 
549         return;
550     curDetRecData = data;
551     var html = renderDetails_iphone(curDetRecData);
552     detailRecordDiv.innerHTML = html;
553     showhide('detailview');
554     finishLoading();
555 }
556
557 function my_onrecord_iphone(data) {
558     my_onrecord(data);
559     callback.send("record", data.recid, data, data.xtargets[i].freq);
560 }
561
562
563 function my_onbytarget(data) {
564     var targetDiv = document.getElementById("bytarget");
565     var table ='<table><thead><tr><td>Target ID</td><td>Hits</td><td>Diags</td>'
566         +'<td>Records</td><td>State</td></tr></thead><tbody>';
567     
568     for (var i = 0; i < data.length; i++ ) {
569         table += "<tr><td>" + data[i].id +
570             "</td><td>" + data[i].hits +
571             "</td><td>" + data[i].diagnostic +
572             "</td><td>" + data[i].records +
573             "</td><td>" + data[i].state + "</td></tr>";
574     }
575
576     table += '</tbody></table>';
577     targetDiv.innerHTML = table;
578 }
579
580 ////////////////////////////////////////////////////////////////////////////////
581 ////////////////////////////////////////////////////////////////////////////////
582
583 // wait until the DOM is ready
584 function domReady () 
585
586     // document.search.onsubmit = onFormSubmitEventHandler;
587     document.search.query.value = '';
588     document.select.sort.onchange = onSelectDdChange;
589     document.select.perpage.onchange = onSelectDdChange;
590     if (document.location.search.match("inApp=true")) 
591         applicationMode(true);
592     else
593         applicationMode(false);
594
595     window.location.parameters = parseQueryString(window.location.search);
596     window.location.parametersMulti = parseQueryStringMulti(window.location.search);
597
598     // hash params have highest priority, than query params
599     var params = (window.location.hash && window.location.hash.length > 1)
600       ? parseQueryString(getRealHash())
601       : window.location.parameters;
602     var paramsMulti = window.location.parametersMulti;
603 /*
604     var params = parseQueryString(window.location.search);
605     if (params.query) {
606         document.search.query.value = params.query;
607         onFormSubmitEventHandler();
608     }
609     
610 */
611     controlRegister.loadControls();
612
613     //append settings to the 'state'
614     loadSettings(function (setts) {
615         state.setFallbackSettings(setts);
616         controlRegister.populateControls(setts);  // set controls from cookies
617         controlRegister.populateControls(params); // override from query string
618         stateChanged(params);        
619     });
620     
621 }
622  
623 function applicationMode(newmode) 
624 {
625     var searchdiv = document.getElementById("searchForm");
626     if (newmode)
627         inApp = newmode;
628     if (inApp) {
629         document.getElementById("heading").style.display="none";
630         searchdiv.style.display = 'none';
631     }
632     else { 
633         
634         document.getElementById("nav").style.display="";
635         document.getElementById("normal").style.display="inline";
636         document.getElementById("normal").style.visibility="";
637         searchdiv.style.display = '';
638         //document.search.onsubmit = onFormSubmit;
639     }
640     callback.init();
641 }
642 // when search button pressed
643 function onFormSubmitEventHandler() 
644 {
645     resetPage();
646     document.location.hash = "query=" + document.search.query.value;
647     //window.location.search = "query=" + document.search.query.value;
648     loadSelect();
649     triggerSearch();
650     submitted = true;
651     return true;
652 }
653
654 function onSelectDdChange()
655 {
656     if (!submitted) return false;
657     resetPage();
658     loadSelect();
659     my_paz.show(0, state.recPerPage, curSort);
660     return false;
661 }
662
663
664 function stateChanged(params) {
665   if (params == undefined) 
666         return;
667   if (params["query"]) {
668     // If this page was accessed with a query param, usually means
669     // new page refresh, but not always!
670     state.reset(); // to ensure it's clean and fallbacks are loaded
671     calcRecPerPage();
672     state.loadParams(params);
673   } else if (params["query_state"]) {
674           // If this page was accessed with a serialized State object
675     state.reset(); // to ensure it's clean and fallbacks are loaded
676     state.deserialize(String(params["query_state"]));
677   }
678   document.search.query.value = state.simpleQuery;        
679   document.select.sort.value = state.curSort;        
680   //document.select.perpage.value = state.recPerPage;
681   if (document.category && document.category.category_filter) {
682         document.category.category_filter.value = state.categoryFilter;
683   }
684   if (document.search.query.value != "")
685     triggerSearch();
686 }
687
688 function resetPage()
689 {
690   state.curPage = 1;    
691   totalRec = 0;     
692 }
693
694 function getFacets() {
695     var result = "";
696     for (var key in querys_server) {
697         if (result.length > 0)
698             result += ","
699         result += querys_server[key];
700     }
701     return result;
702 }
703
704 function triggerSearch ()
705 {
706     // Restore to initial page size. Old stuff
707     recToShow = recToShowPageSize;
708     
709     displayLoading();
710     my_paz.search(document.search.query.value, state.recPerPage, curSort, curFilter, undefined,
711         {
712            "limit" : getFacets() 
713         }
714         );
715     showhide("recordview");
716 }
717
718 function loadSelect ()
719 {
720     curSort = document.select.sort.value;
721     //state.recPerPage = document.select.perpage.value;
722 }
723
724 // limit the query after clicking the facet
725 function limitQuery(field, value)
726 {
727   var newQuery = ' and ' + field + '="' + value + '"';
728   querys[field] += newQuery;
729   document.search.query.value += newQuery;
730   onFormSubmitEventHandler();
731   showhide("recordview");
732 }
733
734 // limit the query after clicking the facet
735 function limitQueryServer(field, value)
736 {
737     // Check for client field usage
738     var fieldname = query_client_server[field];
739     if (!fieldname) 
740         fieldname = field;      
741     
742     var newQuery = fieldname + '=' + value.replace(",", "\\,").replace("|", "\\,");
743     // Does it already exists?
744     if (querys_server[fieldname]) 
745         querys_server[fieldname] += "," + newQuery;
746     else
747         querys_server[fieldname] = newQuery;
748 //  document.search.query.value += newQuery;
749   onFormSubmitEventHandler();
750   showhide("recordview");
751 }
752
753
754
755 // limit the query after clicking the facet
756 function removeQuery (field, value) {
757         document.search.query.value.replace(' and ' + field + '="' + value + '"', '');
758     onFormSubmitEventHandler();
759     showhide("recordview");
760 }
761
762 // limit the query after clicking the facet
763 function limitOrResetQuery (field, value, selected) {
764     if (useLimit) {
765         limitOrResetQueryServer(field,value, selected);
766         return ;
767     }
768     if (field == 'reset_su' || field == 'reset_au') {
769         var reset_field = field.substring(6);
770         document.search.query.value = document.search.query.value.replace(querys[reset_field], '');
771         querys[reset_field] = '';
772         onFormSubmitEventHandler();
773         showhide("recordview");
774     }
775     else 
776         limitQuery(field, value);
777         //alert("limitOrResetQuerry: query after: " + document.search.query.value);
778 }
779
780 // limit the query after clicking the facet
781 function limitOrResetQueryServer (field, value, selected) {
782     if (field.substring(0,6) == 'reset_') {
783         var clientname = field.substring(6);
784         var fieldname = query_client_server[clientname];
785         if (!fieldname) 
786             fieldname = clientname;     
787         delete querys_server[fieldname];
788         onFormSubmitEventHandler();
789         showhide("recordview");
790     }
791     else 
792         limitQueryServer(field, value);
793         //alert("limitOrResetQuerry: query after: " + document.search.query.value);
794 }
795
796
797
798
799 // limit by target functions
800 function limitTarget (id, name)
801 {
802     curFilter = 'pz:id=' + id;
803     resetPage();
804     loadSelect();
805     triggerSearch();
806     return false;
807 }
808
809 function delimitTarget ()
810 {
811     curFilter = 'ALL'; 
812     resetPage();
813     loadSelect();
814     triggerSearch();
815     return false;
816 }
817
818 function limitOrResetTarget(id, name) {
819         if (id == 'reset_xt') {
820                 delimitTarget();
821         }
822         else {
823                 limitTarget(id,name);
824         }
825 }
826
827 function drawPager (pagerDiv)
828 {
829     //client indexes pages from 1 but pz2 from 0
830     var onsides = 2;
831     var pages = Math.ceil(totalRec / state.recPerPage);
832     
833     var firstClkbl = ( state.curPage - onsides > 0 ) 
834         ? state.curPage - onsides
835         : 1;
836
837     var lastClkbl = firstClkbl + 2*onsides < pages
838         ? firstClkbl + 2*onsides
839         : pages;
840
841     var prev = '<span id="prev">Prev</span><b> | </b>';
842     if (state.curPage > 1)
843         var prev = '<a href="#" id="prev" onclick="pagerPrev();">'
844         +'Prev</a><b> | </b>';
845
846     var middle = '';
847     for(var i = firstClkbl; i <= lastClkbl; i++) {
848         var numLabel = i;
849         if(i == state.curPage)
850             numLabel = '<b>' + i + '</b>';
851
852         middle += '<a href="#" onclick="showPage(' + i + ')"> '
853             + numLabel + ' </a>';
854     }
855     
856     var next = '<b> | </b><span id="next">Next</span>';
857     if (pages - state.curPage > 0)
858     var next = '<b> | </b><a href="#" id="next" onclick="pagerNext()">'
859         +'Next</a>';
860
861     predots = '';
862     if (firstClkbl > 1)
863         predots = '...';
864
865     postdots = '';
866     if (lastClkbl < pages)
867         postdots = '...';
868
869     pagerDiv.innerHTML += '<div class="pager">' 
870         + prev + predots + middle + postdots + next + '</div>';
871 }
872
873 function showPage(pageNum)
874 {
875     //state.curPage = pageNum;
876     state.curPage = pageNum;
877     displayLoading();
878     my_paz.showPage( state.curPage - 1 );
879 }
880
881 // simple paging functions
882
883 function pagerNext() {
884     if ( totalRec - state.recPerPage*state.curPage > 0) {
885         displayLoading();
886         my_paz.showNext();
887         //curPage++;
888         state.curPage++;
889     }
890 }
891
892 function pagerPrev() {
893   if ( my_paz.showPrev() != false ) {
894     displayLoading();    
895     state.curPage--;
896     if (state.curPage <= 0)
897       throw "Zeo or negative current page"; 
898   }
899
900 }
901
902 // swithing view between targets and records
903
904 function switchView(view) {
905     
906     var targets = document.getElementById('targetview');
907     var records = document.getElementById('recordview');
908     
909     switch(view) {
910         case 'targetview':
911             targets.style.display = "block";            
912             records.style.display = "none";
913             break;
914         case 'recordview':
915             targets.style.display = "none";            
916             records.style.display = "block";
917             break;
918         default:
919             alert('Unknown view.');
920     }
921 }
922
923 function hideLogo() {
924   document.getElementById("logo").style.display = 'none';
925 }
926
927 function displayLoading() {
928   document.getElementById("loading").style.display = 'inline';
929 }
930
931 function finishLoading() {
932   document.getElementById("loading").style.display = 'none';
933 }
934
935
936 // detailed record drawing
937 function showDetails (prefixRecId) {
938     var recId = prefixRecId.replace('rec_', '');
939     var oldRecId = curDetRecId;
940     curDetRecId = recId;
941     
942     // if the same clicked, just show it again
943     if (recId == oldRecId) {
944         showhide('detailview');
945         return;
946     }
947     // request the record
948     displayLoading()
949     my_paz.record_with_query(recId);
950 }
951
952 function replaceHtml(el, html) {
953   var oldEl = typeof el === "string" ? document.getElementById(el) : el;
954   /*@cc_on // Pure innerHTML is slightly faster in IE
955     oldEl.innerHTML = html;
956     return oldEl;
957     @*/
958   var newEl = oldEl.cloneNode(false);
959   newEl.innerHTML = html;
960   oldEl.parentNode.replaceChild(newEl, oldEl);
961   /* Since we just removed the old element from the DOM, return a reference
962      to the new element, which can be used to restore variable references. */
963   return newEl;
964 };
965
966 function renderDetails(data, marker)
967 {
968     var details = '<div class="details" id="det_'+data.recid+'"><table>';
969     if (marker) details += '<tr><td>'+ marker + '</td></tr>';
970     if (data["md-title"] != undefined) {
971         details += '<tr><td><b>Title</b></td><td><b>:</b> '+data["md-title"];
972         if (data["md-title-remainder"] != undefined) {
973               details += ' : <span>' + data["md-title-remainder"] + ' </span>';
974         }
975         if (data["md-author"] != undefined) {
976               details += ' <span><i>'+ data["md-auhtor"] +'</i></span>';
977         }
978         details += '</td></tr>';
979     }
980     if (data["md-date"] != undefined)
981         details += '<tr><td><b>Date</b></td><td><b>:</b> ' + data["md-date"] + '</td></tr>';
982     if (data["md-author"] != undefined)
983         details += '<tr><td><b>Author</b></td><td><b>:</b> ' + data["md-author"] + '</td></tr>';
984     if (data["md-electronic-url"] != undefined)
985         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>';
986     if (data["location"][0]["md-subject"] != undefined)
987         details += '<tr><td><b>Subject</b></td><td><b>:</b> ' + data["location"][0]["md-subject"] + '</td></tr>';
988     if (data["location"][0]["@name"] != undefined)
989         details += '<tr><td><b>Location</b></td><td><b>:</b> ' + data["location"][0]["@name"] + " (" +data["location"][0]["@id"] + ")" + '</td></tr>';
990     details += '</table></div>';
991     return details;
992 }
993
994 var default_tag = 'big';
995 function renderLine(title, value, tag) {
996     if (tag == undefined)
997         tag = default_tag;
998     if (value != undefined)
999         return '<li><h3>' + title + '</h3><' + tag + '>' + value + '</' + tag + '></li>';
1000     return '';
1001 }
1002
1003 function renderLines(title, values, name, tag) {
1004     if (tag == undefined)
1005         tag = default_tag;
1006     var result = "";
1007     if (values != undefined && values.length)
1008         for (var idx = 0 ; idx < values.length ; idx++)
1009             if (values[idx][name] != undefined )
1010                 result += values[idx][name] + ' ';
1011     if (result != "") 
1012         result = '<li><h3>' + title + '</h3><' + tag + '>' + result + '</' + tag + '></li>';
1013     return result;
1014 }
1015
1016 // Values is a array of locations. 
1017
1018 function renderLinesURL(title, values, name, url, tag) {
1019     if (tag == undefined)
1020         tag = default_tag;
1021     var result = "";
1022     result = '<li><h3>' + title + '</h3><' + tag + ' style="display: inline-block;">';
1023     if (values != undefined && values.length) {
1024         for (var idx = 0 ; idx < values.length ; idx++) {
1025             var url = choose_url(values[idx], auth.proxyUrl);
1026             if (url != null)
1027                 result += '<a target="_blank" href="' + url + '">' + values[idx][name] + '</a><br>';
1028             else
1029                 result += values[idx][name] + '<br>';
1030         }
1031     }
1032     result += '</' + tag + '></li>';
1033     return result;
1034 }
1035
1036 function renderLineURL(title, URL, display) {
1037     if (URL != undefined)
1038         return '<li><h3>' + title + '</h3><a href="' + URL + '" target="_blank">' + display + '</a></li>';
1039     return '';
1040 }
1041
1042 function renderLineEmail(dtitle, email, display) {
1043     if (email != undefined)
1044         return '<li><h3>' + title + '</h3> <a href="mailto:' + email + '" target="_blank">' + display + '</a></li>';
1045     return '';
1046 }
1047
1048
1049 function find_prioritized(values) {
1050     for (var index = 0; index < values.length; index++) {
1051         if (values[index] != undefined)
1052             return values[index];
1053     }
1054     return undefined;
1055 }
1056
1057 function renderDetails_iphone(data, marker)
1058 {
1059         //return renderDetails(data,marker);
1060
1061     if (!data) 
1062         return ""; 
1063     var details = '<div class="details" id="det_'+data.recid+'" >'
1064     if (marker) 
1065         details += '<h4>'+ marker + '</h4>'; 
1066     details += '<ul class="field" >';
1067
1068     var title  = '';
1069     if (data["md-title"] != undefined) {
1070         title +=  data["md-title"];
1071         if (data["md-title-remainder"] != undefined) {
1072             title += '<br><i>' + data["md-title-remainder"] + '</i>';
1073         }
1074     }
1075     details += renderLine('Title', title);
1076
1077     var author = find_prioritized(
1078         [
1079             data["md-author"],
1080             data["md-title-responsibility"]
1081         ]
1082     );
1083
1084     var coverimagetag = imageHelper.getImageTagByRecId(data.recid, "md-isbn", undefined, "M");
1085     details 
1086         +=renderLine('Date',    data["md-date"])
1087         + renderLine('Author',  data["md-author"])
1088 //      + renderLineURL('URL',  data["md-electronic-url"], data["md-electronic-url"])
1089         + renderLine('Description',     data["md-description"])
1090 //      + renderLines('Subjects', data["location"], "md-subject")
1091     ;
1092
1093     details += renderLinesURL('Location', data["location"], "@name", "md-url_recipe");
1094     details += '<li><a href="#" onclick="showhide(\'recordview\')" style="font-size: 18px;margin-left: 10px;">Back</a></li>';
1095     if (coverimagetag.length>0) {
1096         details += renderLine('&nbsp;', coverimagetag);
1097     }
1098
1099     details += '</ul></div>';
1100     return details;
1101 }
1102
1103 //EOF