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