d252eaaa24b75b6bb88c905d361b5b620367131e
[pazpar2-moved-to-github.git] / js / pz2.js
1 /*
2  * !! WARNING WARNING WARNING WARNING WARNING WARNING WARNING WARNING !!
3  *
4  * Do not edit this file. The current version of pz2.js now lives in
5  * its own git module ssh://git.indexdata.com/home/git/pub/pz2js and
6  * ALL FURTHER CHANGES SHOULD BE MADE TO THAT FILE.
7  *
8  * This copy will be removed as soon as we have good, solid Debian and
9  * Red Hat releases of the new independent pz2js package and have
10  * modified the pazpar2 packages to depend on it.
11  *
12  * !! WARNING WARNING WARNING WARNING WARNING WARNING WARNING WARNING !!
13  */
14
15
16 /*
17  * $Id$
18 ** pz2.js - pazpar2's javascript client library.
19 */
20
21 //since explorer is flawed
22 if (!window['Node']) {
23     window.Node = new Object();
24     Node.ELEMENT_NODE = 1;
25     Node.ATTRIBUTE_NODE = 2;
26     Node.TEXT_NODE = 3;
27     Node.CDATA_SECTION_NODE = 4;
28     Node.ENTITY_REFERENCE_NODE = 5;
29     Node.ENTITY_NODE = 6;
30     Node.PROCESSING_INSTRUCTION_NODE = 7;
31     Node.COMMENT_NODE = 8;
32     Node.DOCUMENT_NODE = 9;
33     Node.DOCUMENT_TYPE_NODE = 10;
34     Node.DOCUMENT_FRAGMENT_NODE = 11;
35     Node.NOTATION_NODE = 12;
36 }
37
38 // prevent execution of more than once
39 if(typeof window.pz2 == "undefined") {
40 window.undefined = window.undefined;
41
42 var pz2 = function ( paramArray )
43 {
44     
45     // at least one callback required
46     if ( !paramArray )
47         throw new Error("Pz2.js: Array with parameters has to be supplied."); 
48
49     //supported pazpar2's protocol version
50     this.suppProtoVer = '1';
51     if (typeof paramArray.pazpar2path != "undefined")
52         this.pz2String = paramArray.pazpar2path;
53     else
54         this.pz2String = "/pazpar2/search.pz2";
55     this.useSessions = true;
56     
57     this.stylesheet = paramArray.detailstylesheet || null;
58     //load stylesheet if required in async mode
59     if( this.stylesheet ) {
60         var context = this;
61         var request = new pzHttpRequest( this.stylesheet );
62         request.get( {}, function ( doc ) { context.xslDoc = doc; } );
63     }
64     
65     this.errorHandler = paramArray.errorhandler || null;
66     this.showResponseType = paramArray.showResponseType || "xml";
67     
68     // function callbacks
69     this.initCallback = paramArray.oninit || null;
70     this.statCallback = paramArray.onstat || null;
71     this.showCallback = paramArray.onshow || null;
72     this.termlistCallback = paramArray.onterm || null;
73     this.recordCallback = paramArray.onrecord || null;
74     this.bytargetCallback = paramArray.onbytarget || null;
75     this.resetCallback = paramArray.onreset || null;
76
77     // termlist keys
78     this.termKeys = paramArray.termlist || "subject";
79     
80     // some configurational stuff
81     this.keepAlive = 50000;
82     
83     if ( paramArray.keepAlive < this.keepAlive )
84         this.keepAlive = paramArray.keepAlive;
85
86     this.sessionID = null;
87     this.serviceId = paramArray.serviceId || null;
88     this.initStatusOK = false;
89     this.pingStatusOK = false;
90     this.searchStatusOK = false;
91     
92     // for sorting
93     this.currentSort = "relevance";
94
95     // where are we?
96     this.currentStart = 0;
97     // currentNum can be overwritten in show 
98     this.currentNum = 20;
99
100     // last full record retrieved
101     this.currRecID = null;
102     
103     // current query
104     this.currQuery = null;
105
106     //current raw record offset
107     this.currRecOffset = null;
108
109     //timers
110     this.pingTimer = null;
111     this.statTime = paramArray.stattime || 1000;
112     this.statTimer = null;
113     this.termTime = paramArray.termtime || 1000;
114     this.termTimer = null;
115     this.showTime = paramArray.showtime || 1000;
116     this.showTimer = null;
117     this.showFastCount = 4;
118     this.bytargetTime = paramArray.bytargettime || 1000;
119     this.bytargetTimer = null;
120     this.recordTime = paramArray.recordtime || 500;
121     this.recordTimer = null;
122
123     // counters for each command and applied delay
124     this.dumpFactor = 500;
125     this.showCounter = 0;
126     this.termCounter = 0;
127     this.statCounter = 0;
128     this.bytargetCounter = 0;
129     this.recordCounter = 0;
130
131     // active clients, updated by stat and show
132     // might be an issue since bytarget will poll accordingly
133     this.activeClients = 1;
134
135     // if in proxy mode no need to init
136     if (paramArray.usesessions != undefined) {
137          this.useSessions = paramArray.usesessions;
138         this.initStatusOK = true;
139     }
140     // else, auto init session or wait for a user init?
141     if (this.useSessions && paramArray.autoInit !== false) {
142         this.init(this.sessionID, this.serviceId);
143     }
144     // Version parameter
145     this.version = paramArray.version || null;
146 };
147
148 pz2.prototype = 
149 {
150     //error handler for async error throws
151    throwError: function (errMsg, errCode)
152    {
153         var err = new Error(errMsg);
154         if (errCode) err.code = errCode;
155                 
156         if (this.errorHandler) {
157             this.errorHandler(err);
158         }
159         else {
160             throw err;
161         }
162    },
163
164     // stop activity by clearing tiemouts 
165    stop: function ()
166    {
167        clearTimeout(this.statTimer);
168        clearTimeout(this.showTimer);
169        clearTimeout(this.termTimer);
170        clearTimeout(this.bytargetTimer);
171     },
172     
173     // reset status variables
174     reset: function ()
175     {   
176         if ( this.useSessions ) {
177             this.sessionID = null;
178             this.initStatusOK = false;
179             this.pingStatusOK = false;
180             clearTimeout(this.pingTimer);
181         }
182         this.searchStatusOK = false;
183         this.stop();
184             
185         if ( this.resetCallback )
186                 this.resetCallback();
187     },
188
189     init: function (sessionId, serviceId) 
190     {
191         this.reset();
192         
193         // session id as a param
194         if (sessionId && this.useSessions ) {
195             this.initStatusOK = true;
196             this.sessionID = sessionId;
197             this.ping();
198         // old school direct pazpar2 init
199         } else if (this.useSessions) {
200             var context = this;
201             var request = new pzHttpRequest(this.pz2String, this.errorHandler);
202             var opts = {'command' : 'init'};
203             if (serviceId) opts.service = serviceId;
204             request.safeGet(
205                 opts,
206                 function(data) {
207                     if ( data.getElementsByTagName("status")[0]
208                             .childNodes[0].nodeValue == "OK" ) {
209                         if ( data.getElementsByTagName("protocol")[0]
210                                 .childNodes[0].nodeValue 
211                             != context.suppProtoVer )
212                             throw new Error(
213                                 "Server's protocol not supported by the client"
214                             );
215                         context.initStatusOK = true;
216                         context.sessionID = 
217                             data.getElementsByTagName("session")[0]
218                                 .childNodes[0].nodeValue;
219                         if (data.getElementsByTagName("keepAlive").length > 0) {
220                             context.keepAlive = data.getElementsByTagName("keepAlive")[0].childNodes[0].nodeValue;
221                         }
222                         context.pingTimer =
223                             setTimeout(
224                                 function () {
225                                     context.ping();
226                                 },
227                                 context.keepAlive
228                             );
229                         if ( context.initCallback )
230                             context.initCallback();
231                     }
232                     else
233                         context.throwError('Init failed. Malformed WS resonse.',
234                                             110);
235                 }
236             );
237         // when through proxy no need to init
238         } else {
239             this.initStatusOK = true;
240         }
241     },
242     // no need to ping explicitly
243     ping: function () 
244     {
245         // pinging only makes sense when using pazpar2 directly
246         if( !this.initStatusOK || !this.useSessions )
247             throw new Error(
248             'Pz2.js: Ping not allowed (proxy mode) or session not initialized.'
249             );
250         var context = this;
251
252         clearTimeout(context.pingTimer);
253
254         var request = new pzHttpRequest(this.pz2String, this.errorHandler);
255         request.safeGet(
256             { "command": "ping", "session": this.sessionID, "windowid" : window.name },
257             function(data) {
258                 if ( data.getElementsByTagName("status")[0]
259                         .childNodes[0].nodeValue == "OK" ) {
260                     context.pingStatusOK = true;
261                     context.pingTimer =
262                         setTimeout(
263                             function () {
264                                 context.ping();
265                             },
266                             context.keepAlive
267                         );
268                 }
269                 else
270                     context.throwError('Ping failed. Malformed WS resonse.',
271                                         111);
272             }
273         );
274     },
275     search: function (query, num, sort, filter, showfrom, addParamsArr)
276     {
277         clearTimeout(this.statTimer);
278         clearTimeout(this.showTimer);
279         clearTimeout(this.termTimer);
280         clearTimeout(this.bytargetTimer);
281         
282         this.showCounter = 0;
283         this.termCounter = 0;
284         this.bytargetCounter = 0;
285         this.statCounter = 0;
286         this.activeClients = 1;
287         
288         // no proxy mode
289         if( !this.initStatusOK )
290             throw new Error('Pz2.js: session not initialized.');
291         
292         if( query !== undefined )
293             this.currQuery = query;
294         else
295             throw new Error("Pz2.js: no query supplied to the search command.");
296         
297         if ( showfrom !== undefined )
298             var start = showfrom;
299         else
300             var start = 0;
301
302         var searchParams = { 
303           "command": "search",
304           "query": this.currQuery, 
305           "session": this.sessionID,
306           "windowid" : window.name
307         };
308         
309         if( sort !== undefined ) {
310             this.currentSort = sort;
311             searchParams["sort"] = sort;
312         }
313         if (filter !== undefined)
314                 searchParams["filter"] = filter;
315
316         // copy additional parmeters, do not overwrite
317         if (addParamsArr != undefined) {
318             for (var prop in addParamsArr) {
319                 if (!searchParams.hasOwnProperty(prop))
320                     searchParams[prop] = addParamsArr[prop];
321             }
322         }
323         
324         var context = this;
325         var request = new pzHttpRequest(this.pz2String, this.errorHandler);
326         request.safeGet(
327             searchParams,
328             function(data) {
329                 if ( data.getElementsByTagName("status")[0]
330                         .childNodes[0].nodeValue == "OK" ) {
331                     context.searchStatusOK = true;
332                     //piggyback search
333                     context.show(start, num, sort);
334                     if (context.statCallback)
335                         context.stat();
336                     if (context.termlistCallback)
337                         context.termlist();
338                     if (context.bytargetCallback)
339                         context.bytarget();
340                 }
341                 else
342                     context.throwError('Search failed. Malformed WS resonse.',
343                                         112);
344             }
345         );
346     },
347     stat: function()
348     {
349         if( !this.initStatusOK )
350             throw new Error('Pz2.js: session not initialized.');
351         
352         // if called explicitly takes precedence
353         clearTimeout(this.statTimer);
354         
355         var context = this;
356         var request = new pzHttpRequest(this.pz2String, this.errorHandler);
357         request.safeGet(
358             { "command": "stat", "session": this.sessionID, "windowid" : window.name },
359             function(data) {
360                 if ( data.getElementsByTagName("stat") ) {
361                     var activeClients = 
362                         Number( data.getElementsByTagName("activeclients")[0]
363                                     .childNodes[0].nodeValue );
364                     context.activeClients = activeClients;
365
366                     var stat = Element_parseChildNodes(data.documentElement);
367
368                     context.statCounter++;
369                     var delay = context.statTime 
370                         + context.statCounter * context.dumpFactor;
371                     
372                     if ( activeClients > 0 )
373                         context.statTimer = 
374                             setTimeout( 
375                                 function () {
376                                     context.stat();
377                                 },
378                                 delay
379                             );
380                     context.statCallback(stat);
381                 }
382                 else
383                     context.throwError('Stat failed. Malformed WS resonse.',
384                                         113);
385             }
386         );
387     },
388     show: function(start, num, sort, query_state)
389     {
390         if( !this.searchStatusOK && this.useSessions )
391             throw new Error(
392                 'Pz2.js: show command has to be preceded with a search command.'
393             );
394         
395         // if called explicitly takes precedence
396         clearTimeout(this.showTimer);
397         
398         if( sort !== undefined )
399             this.currentSort = sort;
400         if( start !== undefined )
401             this.currentStart = Number( start );
402         if( num !== undefined )
403             this.currentNum = Number( num );
404
405         var context = this;
406         var request = new pzHttpRequest(this.pz2String, this.errorHandler);
407         var requestParameters = 
408           {
409               "command": "show", 
410               "session": this.sessionID, 
411               "start": this.currentStart,
412               "num": this.currentNum, 
413               "sort": this.currentSort, 
414               "block": 1,
415               "type": this.showResponseType,
416               "windowid" : window.name
417           };
418         if (query_state)
419           requestParameters["query-state"] = query_state;
420         if (this.version && this.version > 0)
421             requestParameters["version"] = this.version;
422         request.safeGet(
423           requestParameters,
424           function(data, type) {
425             var show = null;
426             var activeClients = 0;
427             if (type === "json") {
428               show = {};
429               activeClients = Number(data.activeclients[0]);
430               show.activeclients = activeClients;
431               show.merged = Number(data.merged[0]);
432               show.total = Number(data.total[0]);
433               show.start = Number(data.start[0]);
434               show.num = Number(data.num[0]);
435               show.hits = data.hit;
436             } else if (data.getElementsByTagName("status")[0]
437                   .childNodes[0].nodeValue == "OK") {
438                 // first parse the status data send along with records
439                 // this is strictly bound to the format
440                 activeClients = 
441                   Number(data.getElementsByTagName("activeclients")[0]
442                       .childNodes[0].nodeValue);
443                 show = {
444                   "activeclients": activeClients,
445                   "merged": 
446                     Number( data.getElementsByTagName("merged")[0]
447                         .childNodes[0].nodeValue ),
448                   "total": 
449                     Number( data.getElementsByTagName("total")[0]
450                         .childNodes[0].nodeValue ),
451                   "start": 
452                     Number( data.getElementsByTagName("start")[0]
453                         .childNodes[0].nodeValue ),
454                   "num": 
455                     Number( data.getElementsByTagName("num")[0]
456                         .childNodes[0].nodeValue ),
457                   "hits": []
458                 };
459                 // parse all the first-level nodes for all <hit> tags
460                 var hits = data.getElementsByTagName("hit");
461                 for (i = 0; i < hits.length; i++)
462                   show.hits[i] = Element_parseChildNodes(hits[i]);
463             } else {
464               context.throwError('Show failed. Malformed WS resonse.',
465                   114);
466             };
467             
468             var approxNode = data.getElementsByTagName("approximation");
469             if (approxNode && approxNode[0] && approxNode[0].childNodes[0] && approxNode[0].childNodes[0].nodeValue)
470                 show['approximation'] = 
471                   Number( approxNode[0].childNodes[0].nodeValue);
472               
473
474               data.getElementsByTagName("")
475             context.activeClients = activeClients; 
476             context.showCounter++;
477             var delay = context.showTime;
478             if (context.showCounter > context.showFastCount)
479               delay += context.showCounter * context.dumpFactor;
480             if ( activeClients > 0 )
481               context.showTimer = setTimeout(
482                 function () {
483                   context.show();
484                 }, 
485                 delay);
486             context.showCallback(show);
487           }
488         );
489     },
490     record: function(id, offset, syntax, handler)
491     {
492         // we may call record with no previous search if in proxy mode
493         if(!this.searchStatusOK && this.useSessions)
494            throw new Error(
495             'Pz2.js: record command has to be preceded with a search command.'
496             );
497         
498         if( id !== undefined )
499             this.currRecID = id;
500         
501         var recordParams = { 
502             "command": "record", 
503             "session": this.sessionID,
504             "id": this.currRecID,
505             "windowid" : window.name
506         };
507         
508         this.currRecOffset = null;
509         if (offset != undefined) {
510             recordParams["offset"] = offset;
511             this.currRecOffset = offset;
512         }
513
514         if (syntax != undefined)
515             recordParams['syntax'] = syntax;
516
517         //overwrite default callback id needed
518         var callback = this.recordCallback;
519         var args = undefined;
520         if (handler != undefined) {
521             callback = handler['callback'];
522             args = handler['args'];
523         }
524         
525         var context = this;
526         var request = new pzHttpRequest(this.pz2String, this.errorHandler);
527
528         request.safeGet(
529             recordParams,
530             function(data) {
531                 var recordNode;
532                 var record;                                
533                 //raw record
534                 if (context.currRecOffset !== null) {
535                     record = new Array();
536                     record['xmlDoc'] = data;
537                     record['offset'] = context.currRecOffset;
538                     callback(record, args);
539                 //pz2 record
540                 } else if ( recordNode = 
541                     data.getElementsByTagName("record")[0] ) {
542                     // if stylesheet was fetched do not parse the response
543                     if ( context.xslDoc ) {
544                         record = new Array();
545                         record['xmlDoc'] = data;
546                         record['xslDoc'] = context.xslDoc;
547                         record['recid'] = 
548                             recordNode.getElementsByTagName("recid")[0]
549                                 .firstChild.nodeValue;
550                     //parse record
551                     } else {
552                         record = Element_parseChildNodes(recordNode);
553                     }    
554                     var activeClients = 
555                        Number( data.getElementsByTagName("activeclients")[0]
556                                 .childNodes[0].nodeValue );
557                     context.activeClients = activeClients; 
558                     context.recordCounter++;
559                     var delay = context.recordTime + context.recordCounter * context.dumpFactor;
560                     if ( activeClients > 0 )
561                         context.recordTimer = 
562                            setTimeout ( 
563                                function() {
564                                   context.record(id, offset, syntax, handler);
565                                   },
566                                   delay
567                                );                                    
568                     callback(record, args);
569                 }
570                 else
571                     context.throwError('Record failed. Malformed WS resonse.',
572                                         115);
573             }
574         );
575     },
576
577     termlist: function()
578     {
579         if( !this.searchStatusOK && this.useSessions )
580             throw new Error(
581             'Pz2.js: termlist command has to be preceded with a search command.'
582             );
583
584         // if called explicitly takes precedence
585         clearTimeout(this.termTimer);
586         
587         var context = this;
588         var request = new pzHttpRequest(this.pz2String, this.errorHandler);
589         request.safeGet(
590             { 
591                 "command": "termlist", 
592                 "session": this.sessionID, 
593                 "name": this.termKeys,
594                 "windowid" : window.name, 
595                 "version" : this.version
596         
597             },
598             function(data) {
599                 if ( data.getElementsByTagName("termlist") ) {
600                     var activeClients = 
601                         Number( data.getElementsByTagName("activeclients")[0]
602                                     .childNodes[0].nodeValue );
603                     context.activeClients = activeClients;
604                     var termList = { "activeclients":  activeClients };
605                     var termLists = data.getElementsByTagName("list");
606                     //for each termlist
607                     for (i = 0; i < termLists.length; i++) {
608                         var listName = termLists[i].getAttribute('name');
609                         termList[listName] = new Array();
610                         var terms = termLists[i].getElementsByTagName('term');
611                         //for each term in the list
612                         for (j = 0; j < terms.length; j++) { 
613                             var term = {
614                                 "name": 
615                                     (terms[j].getElementsByTagName("name")[0]
616                                         .childNodes.length 
617                                     ? terms[j].getElementsByTagName("name")[0]
618                                         .childNodes[0].nodeValue
619                                     : 'ERROR'),
620                                 "freq": 
621                                     terms[j]
622                                     .getElementsByTagName("frequency")[0]
623                                     .childNodes[0].nodeValue || 'ERROR'
624                             };
625
626                             // Only for xtargets: id, records, filtered
627                             var termIdNode = 
628                                 terms[j].getElementsByTagName("id");
629                             if(terms[j].getElementsByTagName("id").length)
630                                 term["id"] = 
631                                     termIdNode[0].childNodes[0].nodeValue;
632                             termList[listName][j] = term;
633
634                             var recordsNode  = terms[j].getElementsByTagName("records");
635                             if (recordsNode && recordsNode.length)
636                                 term["records"] = recordsNode[0].childNodes[0].nodeValue;
637                               
638                             var filteredNode  = terms[j].getElementsByTagName("filtered");
639                             if (filteredNode && filteredNode.length)
640                                 term["filtered"] = filteredNode[0].childNodes[0].nodeValue;
641                               
642                         }
643                     }
644
645                     context.termCounter++;
646                     var delay = context.termTime 
647                         + context.termCounter * context.dumpFactor;
648                     if ( activeClients > 0 )
649                         context.termTimer = 
650                             setTimeout(
651                                 function () {
652                                     context.termlist();
653                                 }, 
654                                 delay
655                             );
656                    
657                    context.termlistCallback(termList);
658                 }
659                 else
660                     context.throwError('Termlist failed. Malformed WS resonse.',
661                                         116);
662             }
663         );
664
665     },
666     bytarget: function()
667     {
668         if( !this.initStatusOK && this.useSessions )
669             throw new Error(
670             'Pz2.js: bytarget command has to be preceded with a search command.'
671             );
672         
673         // no need to continue
674         if( !this.searchStatusOK )
675             return;
676
677         // if called explicitly takes precedence
678         clearTimeout(this.bytargetTimer);
679         
680         var context = this;
681         var request = new pzHttpRequest(this.pz2String, this.errorHandler);
682         request.safeGet(
683             { 
684                 "command": "bytarget", 
685                 "session": this.sessionID, 
686                 "block": 1,
687                 "windowid" : window.name,
688                 "version" : this.version
689             },
690             function(data) {
691                 if ( data.getElementsByTagName("status")[0]
692                         .childNodes[0].nodeValue == "OK" ) {
693                     var targetNodes = data.getElementsByTagName("target");
694                     var bytarget = new Array();
695                     for ( i = 0; i < targetNodes.length; i++) {
696                         bytarget[i] = new Array();
697                         for( j = 0; j < targetNodes[i].childNodes.length; j++ ) {
698                             if ( targetNodes[i].childNodes[j].nodeType 
699                                 == Node.ELEMENT_NODE ) {
700                                 var nodeName = 
701                                     targetNodes[i].childNodes[j].nodeName;
702                                 if (targetNodes[i].childNodes[j].firstChild != null) 
703                                 {
704                                     var nodeText = targetNodes[i].childNodes[j]
705                                         .firstChild.nodeValue;
706                                     bytarget[i][nodeName] = nodeText;
707                                 }
708                                 else { 
709                                     bytarget[i][nodeName] = "";  
710                                 }
711
712
713                             }
714                         }
715                         if (bytarget[i]["state"]=="Client_Disconnected") {
716                           bytarget[i]["hits"] = "Error";
717                         } else if (bytarget[i]["state"]=="Client_Error") {
718                           bytarget[i]["hits"] = "Error";                          
719                         } else if (bytarget[i]["state"]=="Client_Working") {
720                           bytarget[i]["hits"] = "...";
721                         }
722                         if (bytarget[i].diagnostic == "1") {
723                           bytarget[i].diagnostic = "Permanent system error";
724                         } else if (bytarget[i].diagnostic == "2") {
725                           bytarget[i].diagnostic = "Temporary system error";
726                         } 
727                         var targetsSuggestions = targetNodes[i].getElementsByTagName("suggestions");
728                         if (targetsSuggestions != undefined && targetsSuggestions.length>0) {
729                           var suggestions = targetsSuggestions[0];
730                           bytarget[i]["suggestions"] = Element_parseChildNodes(suggestions);
731                         }
732                     }
733                     
734                     context.bytargetCounter++;
735                     var delay = context.bytargetTime 
736                         + context.bytargetCounter * context.dumpFactor;
737                     if ( context.activeClients > 0 )
738                         context.bytargetTimer = 
739                             setTimeout(
740                                 function () {
741                                     context.bytarget();
742                                 }, 
743                                 delay
744                             );
745
746                     context.bytargetCallback(bytarget);
747                 }
748                 else
749                     context.throwError('Bytarget failed. Malformed WS resonse.',
750                                         117);
751             }
752         );
753     },
754     
755     // just for testing, probably shouldn't be here
756     showNext: function(page)
757     {
758         var step = page || 1;
759         this.show( ( step * this.currentNum ) + this.currentStart );     
760     },
761
762     showPrev: function(page)
763     {
764         if (this.currentStart == 0 )
765             return false;
766         var step = page || 1;
767         var newStart = this.currentStart - (step * this.currentNum );
768         this.show( newStart > 0 ? newStart : 0 );
769     },
770
771     showPage: function(pageNum)
772     {
773         //var page = pageNum || 1;
774         this.show(pageNum * this.currentNum);
775     }
776 };
777
778 /*
779 ********************************************************************************
780 ** AJAX HELPER CLASS ***********************************************************
781 ********************************************************************************
782 */
783 var pzHttpRequest = function ( url, errorHandler ) {
784         this.maxUrlLength = 2048;
785         this.request = null;
786         this.url = url;
787         this.errorHandler = errorHandler || null;
788         this.async = true;
789         this.requestHeaders = {};
790         
791         if ( window.XMLHttpRequest ) {
792             this.request = new XMLHttpRequest();
793         } else if ( window.ActiveXObject ) {
794             try {
795                 this.request = new ActiveXObject( 'Msxml2.XMLHTTP' );
796             } catch (err) {
797                 this.request = new ActiveXObject( 'Microsoft.XMLHTTP' );
798             }
799         }
800 };
801
802
803 pzHttpRequest.prototype = 
804 {
805     safeGet: function ( params, callback )
806     {
807         var encodedParams =  this.encodeParams(params);
808         var url = this._urlAppendParams(encodedParams);
809         if (url.length >= this.maxUrlLength) {
810             this.requestHeaders["Content-Type"]
811                 = "application/x-www-form-urlencoded";
812             this._send( 'POST', this.url, encodedParams, callback );
813         } else {
814             this._send( 'GET', url, '', callback );
815         }
816     },
817
818     get: function ( params, callback ) 
819     {
820         this._send( 'GET', this._urlAppendParams(this.encodeParams(params)), 
821             '', callback );
822     },
823
824     post: function ( params, data, callback )
825     {
826         this._send( 'POST', this._urlAppendParams(this.encodeParams(params)), 
827             data, callback );
828     },
829
830     load: function ()
831     {
832         this.async = false;
833         this.request.open( 'GET', this.url, this.async );
834         this.request.send('');
835         if ( this.request.status == 200 )
836             return this.request.responseXML;
837     },
838
839     encodeParams: function (params)
840     {
841         var sep = "";
842         var encoded = "";
843         for (var key in params) {
844             if (params[key] != null) {
845                 encoded += sep + key + '=' + encodeURIComponent(params[key]);
846                 sep = '&';
847             }
848         }
849         return encoded;
850     },
851
852     _send: function ( type, url, data, callback)
853     {
854         var context = this;
855         this.callback = callback;
856         this.async = true;
857         this.request.open( type, url, this.async );
858         for (var key in this.requestHeaders)
859             this.request.setRequestHeader(key, this.requestHeaders[key]);
860         this.request.onreadystatechange = function () {
861             context._handleResponse(url); /// url used ONLY for error reporting
862         }
863         this.request.send(data);
864     },
865
866     _urlAppendParams: function (encodedParams)
867     {
868         if (encodedParams)
869             return this.url + "?" + encodedParams;
870         else
871             return this.url;
872     },
873
874     _handleResponse: function (savedUrlForErrorReporting)
875     {
876         if ( this.request.readyState == 4 ) { 
877             // pick up appplication errors first
878             var errNode = null;
879             if (this.request.responseXML &&
880                 (errNode = this.request.responseXML.documentElement)
881                 && errNode.nodeName == 'error') {
882                 var errMsg = errNode.getAttribute("msg");
883                 var errCode = errNode.getAttribute("code");
884                 var errAddInfo = '';
885                 if (errNode.childNodes.length)
886                     errAddInfo = ': ' + errNode.childNodes[0].nodeValue;
887                            
888                 var err = new Error(errMsg + errAddInfo);
889                 err.code = errCode;
890             
891                 if (this.errorHandler) {
892                     this.errorHandler(err);
893                 }
894                 else {
895                     throw err;
896                 }
897             } else if (this.request.status == 200 && 
898                        this.request.responseXML == null) {
899               if (this.request.responseText != null) {
900                 //assume JSON
901                 
902                 var json = null; 
903                 var text = this.request.responseText;
904                 if (typeof window.JSON == "undefined") 
905                     json = eval("(" + text + ")");
906                 else { 
907                     try {
908                         json = JSON.parse(text);
909                     }
910                     catch (e) {
911                         // Safari: eval will fail as well. Considering trying JSON2 (non-native implementation) instead
912                         /* DEBUG only works in mk2-mobile
913                         if (document.getElementById("log")) 
914                             document.getElementById("log").innerHTML = "" + e + " " + length + ": " + text;
915                         */
916                         try {
917                             json = eval("(" + text + ")");
918                         }
919                         catch (e) {
920                             /* DEBUG only works in mk2-mobile
921                             if (document.getElementById("log")) 
922                                 document.getElementById("log").innerHTML = "" + e + " " + length + ": " + text;
923                             */
924                         }
925                     }
926                 } 
927                 this.callback(json, "json");
928               } else {
929                 var err = new Error("XML response is empty but no error " +
930                                     "for " + savedUrlForErrorReporting);
931                 err.code = -1;
932                 if (this.errorHandler) {
933                     this.errorHandler(err);
934                 } else {
935                     throw err;
936                 }
937               }
938             } else if (this.request.status == 200) {
939                 this.callback(this.request.responseXML);
940             } else {
941                 var err = new Error("HTTP response not OK: " 
942                             + this.request.status + " - " 
943                             + this.request.statusText );
944                 err.code = '00' + this.request.status;        
945                 if (this.errorHandler) {
946                     this.errorHandler(err);
947                 }
948                 else {
949                     throw err;
950                 }
951             }
952         }
953     }
954 };
955
956 /*
957 ********************************************************************************
958 ** XML HELPER FUNCTIONS ********************************************************
959 ********************************************************************************
960 */
961
962 // DOMDocument
963
964 if ( window.ActiveXObject) {
965     var DOMDoc = document;
966 } else {
967     var DOMDoc = Document.prototype;
968 }
969
970 DOMDoc.newXmlDoc = function ( root )
971 {
972     var doc;
973
974     if (document.implementation && document.implementation.createDocument) {
975         doc = document.implementation.createDocument('', root, null);
976     } else if ( window.ActiveXObject ) {
977         doc = new ActiveXObject("MSXML2.DOMDocument");
978         doc.loadXML('<' + root + '/>');
979     } else {
980         throw new Error ('No XML support in this browser');
981     }
982
983     return doc;
984 }
985
986    
987 DOMDoc.parseXmlFromString = function ( xmlString ) 
988 {
989     var doc;
990
991     if ( window.DOMParser ) {
992         var parser = new DOMParser();
993         doc = parser.parseFromString( xmlString, "text/xml");
994     } else if ( window.ActiveXObject ) {
995         doc = new ActiveXObject("MSXML2.DOMDocument");
996         doc.loadXML( xmlString );
997     } else {
998         throw new Error ("No XML parsing support in this browser.");
999     }
1000
1001     return doc;
1002 }
1003
1004 DOMDoc.transformToDoc = function (xmlDoc, xslDoc)
1005 {
1006     if ( window.XSLTProcessor ) {
1007         var proc = new XSLTProcessor();
1008         proc.importStylesheet( xslDoc );
1009         return proc.transformToDocument(xmlDoc);
1010     } else if ( window.ActiveXObject ) {
1011         return document.parseXmlFromString(xmlDoc.transformNode(xslDoc));
1012     } else {
1013         alert( 'Unable to perform XSLT transformation in this browser' );
1014     }
1015 }
1016  
1017 // DOMElement
1018
1019 Element_removeFromDoc = function (DOM_Element)
1020 {
1021     DOM_Element.parentNode.removeChild(DOM_Element);
1022 }
1023
1024 Element_emptyChildren = function (DOM_Element)
1025 {
1026     while( DOM_Element.firstChild ) {
1027         DOM_Element.removeChild( DOM_Element.firstChild )
1028     }
1029 }
1030
1031 Element_appendTransformResult = function ( DOM_Element, xmlDoc, xslDoc )
1032 {
1033     if ( window.XSLTProcessor ) {
1034         var proc = new XSLTProcessor();
1035         proc.importStylesheet( xslDoc );
1036         var docFrag = false;
1037         docFrag = proc.transformToFragment( xmlDoc, DOM_Element.ownerDocument );
1038         DOM_Element.appendChild(docFrag);
1039     } else if ( window.ActiveXObject ) {
1040         DOM_Element.innerHTML = xmlDoc.transformNode( xslDoc );
1041     } else {
1042         alert( 'Unable to perform XSLT transformation in this browser' );
1043     }
1044 }
1045  
1046 Element_appendTextNode = function (DOM_Element, tagName, textContent )
1047 {
1048     var node = DOM_Element.ownerDocument.createElement(tagName);
1049     var text = DOM_Element.ownerDocument.createTextNode(textContent);
1050
1051     DOM_Element.appendChild(node);
1052     node.appendChild(text);
1053
1054     return node;
1055 }
1056
1057 Element_setTextContent = function ( DOM_Element, textContent )
1058 {
1059     if (typeof DOM_Element.textContent !== "undefined") {
1060         DOM_Element.textContent = textContent;
1061     } else if (typeof DOM_Element.innerText !== "undefined" ) {
1062         DOM_Element.innerText = textContent;
1063     } else {
1064         throw new Error("Cannot set text content of the node, no such method.");
1065     }
1066 }
1067
1068 Element_getTextContent = function (DOM_Element)
1069 {
1070     if ( typeof DOM_Element.textContent != 'undefined' ) {
1071         return DOM_Element.textContent;
1072     } else if (typeof DOM_Element.text != 'undefined') {
1073         return DOM_Element.text;
1074     } else {
1075         throw new Error("Cannot get text content of the node, no such method.");
1076     }
1077 }
1078
1079 Element_parseChildNodes = function (node)
1080 {
1081     var parsed = {};
1082     var hasChildElems = false;
1083     var textContent = '';
1084
1085     if (node.hasChildNodes()) {
1086         var children = node.childNodes;
1087         for (var i = 0; i < children.length; i++) {
1088             var child = children[i];
1089             switch (child.nodeType) {
1090               case Node.ELEMENT_NODE:
1091                 hasChildElems = true;
1092                 var nodeName = child.nodeName; 
1093                 if (!(nodeName in parsed))
1094                     parsed[nodeName] = [];
1095                 parsed[nodeName].push(Element_parseChildNodes(child));
1096                 break;
1097               case Node.TEXT_NODE:
1098                 textContent += child.nodeValue;
1099                 break;
1100               case Node.CDATA_SECTION_NODE:
1101                 textContent += child.nodeValue;
1102                 break;
1103             }
1104         }
1105     }
1106
1107     var attrs = node.attributes;
1108     for (var i = 0; i < attrs.length; i++) {
1109         hasChildElems = true;
1110         var attrName = '@' + attrs[i].nodeName;
1111         var attrValue = attrs[i].nodeValue;
1112         parsed[attrName] = attrValue;
1113     }
1114
1115     // if no nested elements/attrs set value to text
1116     if (hasChildElems)
1117       parsed['#text'] = textContent;
1118     else
1119       parsed = textContent;
1120     
1121     return parsed;
1122 }
1123
1124 /* do not remove trailing bracket */
1125 }