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