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