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