Fix memory leak for termlist of type xtargets
[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                         if (bytarget[i]["state"]=="Client_Disconnected") {
641                           bytarget[i]["hits"] = "Error";
642                         } else if (bytarget[i]["state"]=="Client_Error") {
643                           bytarget[i]["hits"] = "Error";                          
644                         } else if (bytarget[i]["state"]=="Client_Working") {
645                           bytarget[i]["hits"] = "...";
646                         }
647                         if (bytarget[i].diagnostic == "1") {
648                           bytarget[i].diagnostic = "Permanent system error";
649                         } else if (bytarget[i].diagnostic == "2") {
650                           bytarget[i].diagnostic = "Temporary system error";
651                         } 
652                     }
653                     
654                     context.bytargetCounter++;
655                     var delay = context.bytargetTime 
656                         + context.bytargetCounter * context.dumpFactor;
657                     if ( context.activeClients > 0 )
658                         context.bytargetTimer = 
659                             setTimeout(
660                                 function () {
661                                     context.bytarget();
662                                 }, 
663                                 delay
664                             );
665
666                     context.bytargetCallback(bytarget);
667                 }
668                 else
669                     context.throwError('Bytarget failed. Malformed WS resonse.',
670                                         117);
671             }
672         );
673     },
674     
675     // just for testing, probably shouldn't be here
676     showNext: function(page)
677     {
678         var step = page || 1;
679         this.show( ( step * this.currentNum ) + this.currentStart );     
680     },
681
682     showPrev: function(page)
683     {
684         if (this.currentStart == 0 )
685             return false;
686         var step = page || 1;
687         var newStart = this.currentStart - (step * this.currentNum );
688         this.show( newStart > 0 ? newStart : 0 );
689     },
690
691     showPage: function(pageNum)
692     {
693         //var page = pageNum || 1;
694         this.show(pageNum * this.currentNum);
695     }
696 };
697
698 /*
699 ********************************************************************************
700 ** AJAX HELPER CLASS ***********************************************************
701 ********************************************************************************
702 */
703 var pzHttpRequest = function ( url, errorHandler ) {
704         this.maxUrlLength = 2048;
705         this.request = null;
706         this.url = url;
707         this.errorHandler = errorHandler || null;
708         this.async = true;
709         this.requestHeaders = {};
710         
711         if ( window.XMLHttpRequest ) {
712             this.request = new XMLHttpRequest();
713         } else if ( window.ActiveXObject ) {
714             try {
715                 this.request = new ActiveXObject( 'Msxml2.XMLHTTP' );
716             } catch (err) {
717                 this.request = new ActiveXObject( 'Microsoft.XMLHTTP' );
718             }
719         }
720 };
721
722
723 pzHttpRequest.prototype = 
724 {
725     safeGet: function ( params, callback )
726     {
727         var encodedParams =  this.encodeParams(params);
728         var url = this._urlAppendParams(encodedParams);
729         if (url.length >= this.maxUrlLength) {
730             this.requestHeaders["Content-Type"]
731                 = "application/x-www-form-urlencoded";
732             this._send( 'POST', this.url, encodedParams, callback );
733         } else {
734             this._send( 'GET', url, '', callback );
735         }
736     },
737
738     get: function ( params, callback ) 
739     {
740         this._send( 'GET', this._urlAppendParams(this.encodeParams(params)), 
741             '', callback );
742     },
743
744     post: function ( params, data, callback )
745     {
746         this._send( 'POST', this._urlAppendParams(this.encodeParams(params)), 
747             data, callback );
748     },
749
750     load: function ()
751     {
752         this.async = false;
753         this.request.open( 'GET', this.url, this.async );
754         this.request.send('');
755         if ( this.request.status == 200 )
756             return this.request.responseXML;
757     },
758
759     encodeParams: function (params)
760     {
761         var sep = "";
762         var encoded = "";
763         for (var key in params) {
764             if (params[key] != null) {
765                 encoded += sep + key + '=' + encodeURIComponent(params[key]);
766                 sep = '&';
767             }
768         }
769         return encoded;
770     },
771
772     _send: function ( type, url, data, callback)
773     {
774         var context = this;
775         this.callback = callback;
776         this.async = true;
777         this.request.open( type, url, this.async );
778         for (var key in this.requestHeaders)
779             this.request.setRequestHeader(key, this.requestHeaders[key]);
780         this.request.onreadystatechange = function () {
781             context._handleResponse(url); /// url used ONLY for error reporting
782         }
783         this.request.send(data);
784     },
785
786     _urlAppendParams: function (encodedParams)
787     {
788         if (encodedParams)
789             return this.url + "?" + encodedParams;
790         else
791             return this.url;
792     },
793
794     _handleResponse: function (savedUrlForErrorReporting)
795     {
796         if ( this.request.readyState == 4 ) { 
797             // pick up appplication errors first
798             var errNode = null;
799             if (this.request.responseXML &&
800                 (errNode = this.request.responseXML.documentElement)
801                 && errNode.nodeName == 'error') {
802                 var errMsg = errNode.getAttribute("msg");
803                 var errCode = errNode.getAttribute("code");
804                 var errAddInfo = '';
805                 if (errNode.childNodes.length)
806                     errAddInfo = ': ' + errNode.childNodes[0].nodeValue;
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.request.responseXML == null) {
819               if (this.request.responseText != null) {
820                 //assume JSON
821                 
822                 var json = null; 
823                 var text = this.request.responseText;
824                 if (typeof window.JSON == "undefined") 
825                     json = eval("(" + text + ")");
826                 else { 
827                     try {
828                         json = JSON.parse(text);
829                     }
830                     catch (e) {
831                         // Safari: eval will fail as well. Considering trying JSON2 (non-native implementation) instead
832                         /* DEBUG only works in mk2-mobile
833                         if (document.getElementById("log")) 
834                             document.getElementById("log").innerHTML = "" + e + " " + length + ": " + text;
835                         */
836                         try {
837                             json = eval("(" + text + ")");
838                         }
839                         catch (e) {
840                             /* DEBUG only works in mk2-mobile
841                             if (document.getElementById("log")) 
842                                 document.getElementById("log").innerHTML = "" + e + " " + length + ": " + text;
843                             */
844                         }
845                     }
846                 } 
847                 this.callback(json, "json");
848               } else {
849                 var err = new Error("XML response is empty but no error " +
850                                     "for " + savedUrlForErrorReporting);
851                 err.code = -1;
852                 if (this.errorHandler) {
853                     this.errorHandler(err);
854                 } else {
855                     throw err;
856                 }
857               }
858             } else if (this.request.status == 200) {
859                 this.callback(this.request.responseXML);
860             } else {
861                 var err = new Error("HTTP response not OK: " 
862                             + this.request.status + " - " 
863                             + this.request.statusText );
864                 err.code = '00' + this.request.status;        
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 Element_parseChildNodes = function (node)
1000 {
1001     var parsed = {};
1002     var hasChildElems = false;
1003
1004     if (node.hasChildNodes()) {
1005         var children = node.childNodes;
1006         for (var i = 0; i < children.length; i++) {
1007             var child = children[i];
1008             if (child.nodeType == Node.ELEMENT_NODE) {
1009                 hasChildElems = true;
1010                 var nodeName = child.nodeName; 
1011                 if (!(nodeName in parsed))
1012                     parsed[nodeName] = [];
1013                 parsed[nodeName].push(Element_parseChildNodes(child));
1014             }
1015         }
1016     }
1017
1018     var attrs = node.attributes;
1019     for (var i = 0; i < attrs.length; i++) {
1020         var attrName = '@' + attrs[i].nodeName;
1021         var attrValue = attrs[i].nodeValue;
1022         parsed[attrName] = attrValue;
1023     }
1024
1025     // if no nested elements, get text content
1026     if (node.hasChildNodes() && !hasChildElems) {
1027         if (node.attributes.length) 
1028             parsed['#text'] = node.firstChild.nodeValue;
1029         else
1030             parsed = node.firstChild.nodeValue;
1031     }
1032     
1033     return parsed;
1034 }
1035
1036 /* do not remove trailing bracket */
1037 }