Aligns parameter name windowid
[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, "windowid" : self.window.name },
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           "windowid" : self.window.name
279         };
280         
281         if (filter !== undefined)
282                 searchParams["filter"] = filter;
283
284         // copy additional parmeters, do not overwrite
285         if (addParamsArr != undefined) {
286             for (var prop in addParamsArr) {
287                 if (!searchParams.hasOwnProperty(prop))
288                     searchParams[prop] = addParamsArr[prop];
289             }
290         }
291         
292         var context = this;
293         var request = new pzHttpRequest(this.pz2String, this.errorHandler);
294         request.safeGet(
295             searchParams,
296             function(data) {
297                 if ( data.getElementsByTagName("status")[0]
298                         .childNodes[0].nodeValue == "OK" ) {
299                     context.searchStatusOK = true;
300                     //piggyback search
301                     context.show(start, num, sort);
302                     if (context.statCallback)
303                         context.stat();
304                     if (context.termlistCallback)
305                         context.termlist();
306                     if (context.bytargetCallback)
307                         context.bytarget();
308                 }
309                 else
310                     context.throwError('Search failed. Malformed WS resonse.',
311                                         112);
312             }
313         );
314     },
315     stat: function()
316     {
317         if( !this.initStatusOK )
318             throw new Error('Pz2.js: session not initialized.');
319         
320         // if called explicitly takes precedence
321         clearTimeout(this.statTimer);
322         
323         var context = this;
324         var request = new pzHttpRequest(this.pz2String, this.errorHandler);
325         request.safeGet(
326             { "command": "stat", "session": this.sessionID, "windowid" : self.window.name },
327             function(data) {
328                 if ( data.getElementsByTagName("stat") ) {
329                     var activeClients = 
330                         Number( data.getElementsByTagName("activeclients")[0]
331                                     .childNodes[0].nodeValue );
332                     context.activeClients = activeClients;
333
334                     var stat = Element_parseChildNodes(data.documentElement);
335
336                     context.statCounter++;
337                     var delay = context.statTime 
338                         + context.statCounter * context.dumpFactor;
339                     
340                     if ( activeClients > 0 )
341                         context.statTimer = 
342                             setTimeout( 
343                                 function () {
344                                     context.stat();
345                                 },
346                                 delay
347                             );
348                     context.statCallback(stat);
349                 }
350                 else
351                     context.throwError('Stat failed. Malformed WS resonse.',
352                                         113);
353             }
354         );
355     },
356     show: function(start, num, sort)
357     {
358         if( !this.searchStatusOK && this.useSessions )
359             throw new Error(
360                 'Pz2.js: show command has to be preceded with a search command.'
361             );
362         
363         // if called explicitly takes precedence
364         clearTimeout(this.showTimer);
365         
366         if( sort !== undefined )
367             this.currentSort = sort;
368         if( start !== undefined )
369             this.currentStart = Number( start );
370         if( num !== undefined )
371             this.currentNum = Number( num );
372
373         var context = this;
374         var request = new pzHttpRequest(this.pz2String, this.errorHandler);
375         request.safeGet(
376           {
377             "command": "show", 
378             "session": this.sessionID, 
379             "start": this.currentStart,
380             "num": this.currentNum, 
381             "sort": this.currentSort, 
382             "block": 1,
383             "type": this.showResponseType,
384             "windowid" : self.window.name
385           },
386           function(data, type) {
387             var show = null;
388             var activeClients = 0;
389             if (type === "json") {
390               show = {};
391               activeClients = Number(data.activeclients[0]);
392               show.activeclients = activeClients;
393               show.merged = Number(data.merged[0]);
394               show.total = Number(data.total[0]);
395               show.start = Number(data.start[0]);
396               show.num = Number(data.num[0]);
397               show.hits = data.hit;
398             } else if (data.getElementsByTagName("status")[0]
399                   .childNodes[0].nodeValue == "OK") {
400                 // first parse the status data send along with records
401                 // this is strictly bound to the format
402                 activeClients = 
403                   Number(data.getElementsByTagName("activeclients")[0]
404                       .childNodes[0].nodeValue);
405                 show = {
406                   "activeclients": activeClients,
407                   "merged": 
408                     Number( data.getElementsByTagName("merged")[0]
409                         .childNodes[0].nodeValue ),
410                   "total": 
411                     Number( data.getElementsByTagName("total")[0]
412                         .childNodes[0].nodeValue ),
413                   "start": 
414                     Number( data.getElementsByTagName("start")[0]
415                         .childNodes[0].nodeValue ),
416                   "num": 
417                     Number( data.getElementsByTagName("num")[0]
418                         .childNodes[0].nodeValue ),
419                   "hits": []
420                 };
421                 // parse all the first-level nodes for all <hit> tags
422                 var hits = data.getElementsByTagName("hit");
423                 for (i = 0; i < hits.length; i++)
424                   show.hits[i] = Element_parseChildNodes(hits[i]);
425             } else {
426               context.throwError('Show failed. Malformed WS resonse.',
427                   114);
428             }
429             context.activeClients = activeClients; 
430             context.showCounter++;
431             var delay = context.showTime;
432             if (context.showCounter > context.showFastCount)
433               delay += context.showCounter * context.dumpFactor;
434             if ( activeClients > 0 )
435               context.showTimer = setTimeout(
436                 function () {
437                   context.show();
438                 }, 
439                 delay);
440             context.showCallback(show);
441           }
442         );
443     },
444     record: function(id, offset, syntax, handler)
445     {
446         // we may call record with no previous search if in proxy mode
447         if(!this.searchStatusOK && this.useSessions)
448            throw new Error(
449             'Pz2.js: record command has to be preceded with a search command.'
450             );
451         
452         if( id !== undefined )
453             this.currRecID = id;
454         
455         var recordParams = { 
456             "command": "record", 
457             "session": this.sessionID,
458             "id": this.currRecID,
459             "windowid" : self.window.name
460         };
461         
462         this.currRecOffset = null;
463         if (offset != undefined) {
464             recordParams["offset"] = offset;
465             this.currRecOffset = offset;
466         }
467
468         if (syntax != undefined)
469             recordParams['syntax'] = syntax;
470
471         //overwrite default callback id needed
472         var callback = this.recordCallback;
473         var args = undefined;
474         if (handler != undefined) {
475             callback = handler['callback'];
476             args = handler['args'];
477         }
478         
479         var context = this;
480         var request = new pzHttpRequest(this.pz2String, this.errorHandler);
481
482         request.safeGet(
483             recordParams,
484             function(data) {
485                 var recordNode;
486                 var record;                                
487                 //raw record
488                 if (context.currRecOffset !== null) {
489                     record = new Array();
490                     record['xmlDoc'] = data;
491                     record['offset'] = context.currRecOffset;
492                     callback(record, args);
493                 //pz2 record
494                 } else if ( recordNode = 
495                     data.getElementsByTagName("record")[0] ) {
496                     // if stylesheet was fetched do not parse the response
497                     if ( context.xslDoc ) {
498                         record = new Array();
499                         record['xmlDoc'] = data;
500                         record['xslDoc'] = context.xslDoc;
501                         record['recid'] = 
502                             recordNode.getElementsByTagName("recid")[0]
503                                 .firstChild.nodeValue;
504                     //parse record
505                     } else {
506                         record = Element_parseChildNodes(recordNode);
507                     }    
508                     var activeClients = 
509                        Number( data.getElementsByTagName("activeclients")[0]
510                                 .childNodes[0].nodeValue );
511                     context.activeClients = activeClients; 
512                     context.recordCounter++;
513                     var delay = context.recordTime + context.recordCounter * context.dumpFactor;
514                     if ( activeClients > 0 )
515                         context.recordTimer = 
516                            setTimeout ( 
517                                function() {
518                                   context.record(id, offset, syntax, handler);
519                                   },
520                                   delay
521                                );                                    
522                     callback(record, args);
523                 }
524                 else
525                     context.throwError('Record failed. Malformed WS resonse.',
526                                         115);
527             }
528         );
529     },
530
531     termlist: function()
532     {
533         if( !this.searchStatusOK && this.useSessions )
534             throw new Error(
535             'Pz2.js: termlist command has to be preceded with a search command.'
536             );
537
538         // if called explicitly takes precedence
539         clearTimeout(this.termTimer);
540         
541         var context = this;
542         var request = new pzHttpRequest(this.pz2String, this.errorHandler);
543         request.safeGet(
544             { 
545                 "command": "termlist", 
546                 "session": this.sessionID, 
547                 "name": this.termKeys,
548                 "windowid" : self.window.name
549             },
550             function(data) {
551                 if ( data.getElementsByTagName("termlist") ) {
552                     var activeClients = 
553                         Number( data.getElementsByTagName("activeclients")[0]
554                                     .childNodes[0].nodeValue );
555                     context.activeClients = activeClients;
556                     var termList = { "activeclients":  activeClients };
557                     var termLists = data.getElementsByTagName("list");
558                     //for each termlist
559                     for (i = 0; i < termLists.length; i++) {
560                         var listName = termLists[i].getAttribute('name');
561                         termList[listName] = new Array();
562                         var terms = termLists[i].getElementsByTagName('term');
563                         //for each term in the list
564                         for (j = 0; j < terms.length; j++) { 
565                             var term = {
566                                 "name": 
567                                     (terms[j].getElementsByTagName("name")[0]
568                                         .childNodes.length 
569                                     ? terms[j].getElementsByTagName("name")[0]
570                                         .childNodes[0].nodeValue
571                                     : 'ERROR'),
572                                 "freq": 
573                                     terms[j]
574                                     .getElementsByTagName("frequency")[0]
575                                     .childNodes[0].nodeValue || 'ERROR'
576                             };
577
578                             var termIdNode = 
579                                 terms[j].getElementsByTagName("id");
580                             if(terms[j].getElementsByTagName("id").length)
581                                 term["id"] = 
582                                     termIdNode[0].childNodes[0].nodeValue;
583                             termList[listName][j] = term;
584                         }
585                     }
586
587                     context.termCounter++;
588                     var delay = context.termTime 
589                         + context.termCounter * context.dumpFactor;
590                     if ( activeClients > 0 )
591                         context.termTimer = 
592                             setTimeout(
593                                 function () {
594                                     context.termlist();
595                                 }, 
596                                 delay
597                             );
598                    
599                    context.termlistCallback(termList);
600                 }
601                 else
602                     context.throwError('Termlist failed. Malformed WS resonse.',
603                                         116);
604             }
605         );
606
607     },
608     bytarget: function()
609     {
610         if( !this.initStatusOK && this.useSessions )
611             throw new Error(
612             'Pz2.js: bytarget command has to be preceded with a search command.'
613             );
614         
615         // no need to continue
616         if( !this.searchStatusOK )
617             return;
618
619         // if called explicitly takes precedence
620         clearTimeout(this.bytargetTimer);
621         
622         var context = this;
623         var request = new pzHttpRequest(this.pz2String, this.errorHandler);
624         request.safeGet(
625             { "command": "bytarget", "session": this.sessionID, "windowid" : self.window.name},
626             function(data) {
627                 if ( data.getElementsByTagName("status")[0]
628                         .childNodes[0].nodeValue == "OK" ) {
629                     var targetNodes = data.getElementsByTagName("target");
630                     var bytarget = new Array();
631                     for ( i = 0; i < targetNodes.length; i++) {
632                         bytarget[i] = new Array();
633                         for( j = 0; j < targetNodes[i].childNodes.length; j++ ) {
634                             if ( targetNodes[i].childNodes[j].nodeType 
635                                 == Node.ELEMENT_NODE ) {
636                                 var nodeName = 
637                                     targetNodes[i].childNodes[j].nodeName;
638                                 var nodeText = 
639                                     targetNodes[i].childNodes[j]
640                                         .firstChild.nodeValue;
641                                 bytarget[i][nodeName] = nodeText;
642                             }
643                         }
644                         if (bytarget[i]["state"]=="Client_Disconnected") {
645                           bytarget[i]["hits"] = "Error";
646                         } else if (bytarget[i]["state"]=="Client_Error") {
647                           bytarget[i]["hits"] = "Error";                          
648                         } else if (bytarget[i]["state"]=="Client_Working") {
649                           bytarget[i]["hits"] = "...";
650                         }
651                         if (bytarget[i].diagnostic == "1") {
652                           bytarget[i].diagnostic = "Permanent system error";
653                         } else if (bytarget[i].diagnostic == "2") {
654                           bytarget[i].diagnostic = "Temporary system error";
655                         } 
656                     }
657                     
658                     context.bytargetCounter++;
659                     var delay = context.bytargetTime 
660                         + context.bytargetCounter * context.dumpFactor;
661                     if ( context.activeClients > 0 )
662                         context.bytargetTimer = 
663                             setTimeout(
664                                 function () {
665                                     context.bytarget();
666                                 }, 
667                                 delay
668                             );
669
670                     context.bytargetCallback(bytarget);
671                 }
672                 else
673                     context.throwError('Bytarget failed. Malformed WS resonse.',
674                                         117);
675             }
676         );
677     },
678     
679     // just for testing, probably shouldn't be here
680     showNext: function(page)
681     {
682         var step = page || 1;
683         this.show( ( step * this.currentNum ) + this.currentStart );     
684     },
685
686     showPrev: function(page)
687     {
688         if (this.currentStart == 0 )
689             return false;
690         var step = page || 1;
691         var newStart = this.currentStart - (step * this.currentNum );
692         this.show( newStart > 0 ? newStart : 0 );
693     },
694
695     showPage: function(pageNum)
696     {
697         //var page = pageNum || 1;
698         this.show(pageNum * this.currentNum);
699     }
700 };
701
702 /*
703 ********************************************************************************
704 ** AJAX HELPER CLASS ***********************************************************
705 ********************************************************************************
706 */
707 var pzHttpRequest = function ( url, errorHandler ) {
708         this.maxUrlLength = 2048;
709         this.request = null;
710         this.url = url;
711         this.errorHandler = errorHandler || null;
712         this.async = true;
713         this.requestHeaders = {};
714         
715         if ( window.XMLHttpRequest ) {
716             this.request = new XMLHttpRequest();
717         } else if ( window.ActiveXObject ) {
718             try {
719                 this.request = new ActiveXObject( 'Msxml2.XMLHTTP' );
720             } catch (err) {
721                 this.request = new ActiveXObject( 'Microsoft.XMLHTTP' );
722             }
723         }
724 };
725
726
727 pzHttpRequest.prototype = 
728 {
729     safeGet: function ( params, callback )
730     {
731         var encodedParams =  this.encodeParams(params);
732         var url = this._urlAppendParams(encodedParams);
733         if (url.length >= this.maxUrlLength) {
734             this.requestHeaders["Content-Type"]
735                 = "application/x-www-form-urlencoded";
736             this._send( 'POST', this.url, encodedParams, callback );
737         } else {
738             this._send( 'GET', url, '', callback );
739         }
740     },
741
742     get: function ( params, callback ) 
743     {
744         this._send( 'GET', this._urlAppendParams(this.encodeParams(params)), 
745             '', callback );
746     },
747
748     post: function ( params, data, callback )
749     {
750         this._send( 'POST', this._urlAppendParams(this.encodeParams(params)), 
751             data, callback );
752     },
753
754     load: function ()
755     {
756         this.async = false;
757         this.request.open( 'GET', this.url, this.async );
758         this.request.send('');
759         if ( this.request.status == 200 )
760             return this.request.responseXML;
761     },
762
763     encodeParams: function (params)
764     {
765         var sep = "";
766         var encoded = "";
767         for (var key in params) {
768             if (params[key] != null) {
769                 encoded += sep + key + '=' + encodeURIComponent(params[key]);
770                 sep = '&';
771             }
772         }
773         return encoded;
774     },
775
776     _send: function ( type, url, data, callback)
777     {
778         var context = this;
779         this.callback = callback;
780         this.async = true;
781         this.request.open( type, url, this.async );
782         for (var key in this.requestHeaders)
783             this.request.setRequestHeader(key, this.requestHeaders[key]);
784         this.request.onreadystatechange = function () {
785             context._handleResponse(url); /// url used ONLY for error reporting
786         }
787         this.request.send(data);
788     },
789
790     _urlAppendParams: function (encodedParams)
791     {
792         if (encodedParams)
793             return this.url + "?" + encodedParams;
794         else
795             return this.url;
796     },
797
798     _handleResponse: function (savedUrlForErrorReporting)
799     {
800         if ( this.request.readyState == 4 ) { 
801             // pick up appplication errors first
802             var errNode = null;
803             if (this.request.responseXML &&
804                 (errNode = this.request.responseXML.documentElement)
805                 && errNode.nodeName == 'error') {
806                 var errMsg = errNode.getAttribute("msg");
807                 var errCode = errNode.getAttribute("code");
808                 var errAddInfo = '';
809                 if (errNode.childNodes.length)
810                     errAddInfo = ': ' + errNode.childNodes[0].nodeValue;
811                            
812                 var err = new Error(errMsg + errAddInfo);
813                 err.code = errCode;
814             
815                 if (this.errorHandler) {
816                     this.errorHandler(err);
817                 }
818                 else {
819                     throw err;
820                 }
821             } else if (this.request.status == 200 && 
822                        this.request.responseXML == null) {
823               if (this.request.responseText != null) {
824                 //assume JSON
825                 
826                 var json = null; 
827                 var text = this.request.responseText;
828                 if (typeof window.JSON == "undefined") 
829                     json = eval("(" + text + ")");
830                 else { 
831                     try {
832                         json = JSON.parse(text);
833                     }
834                     catch (e) {
835                         // Safari: eval will fail as well. Considering trying JSON2 (non-native implementation) instead
836                         /* DEBUG only works in mk2-mobile
837                         if (document.getElementById("log")) 
838                             document.getElementById("log").innerHTML = "" + e + " " + length + ": " + text;
839                         */
840                         try {
841                             json = eval("(" + text + ")");
842                         }
843                         catch (e) {
844                             /* DEBUG only works in mk2-mobile
845                             if (document.getElementById("log")) 
846                                 document.getElementById("log").innerHTML = "" + e + " " + length + ": " + text;
847                             */
848                         }
849                     }
850                 } 
851                 this.callback(json, "json");
852               } else {
853                 var err = new Error("XML response is empty but no error " +
854                                     "for " + savedUrlForErrorReporting);
855                 err.code = -1;
856                 if (this.errorHandler) {
857                     this.errorHandler(err);
858                 } else {
859                     throw err;
860                 }
861               }
862             } else if (this.request.status == 200) {
863                 this.callback(this.request.responseXML);
864             } else {
865                 var err = new Error("HTTP response not OK: " 
866                             + this.request.status + " - " 
867                             + this.request.statusText );
868                 err.code = '00' + this.request.status;        
869                 if (this.errorHandler) {
870                     this.errorHandler(err);
871                 }
872                 else {
873                     throw err;
874                 }
875             }
876         }
877     }
878 };
879
880 /*
881 ********************************************************************************
882 ** XML HELPER FUNCTIONS ********************************************************
883 ********************************************************************************
884 */
885
886 // DOMDocument
887
888 if ( window.ActiveXObject) {
889     var DOMDoc = document;
890 } else {
891     var DOMDoc = Document.prototype;
892 }
893
894 DOMDoc.newXmlDoc = function ( root )
895 {
896     var doc;
897
898     if (document.implementation && document.implementation.createDocument) {
899         doc = document.implementation.createDocument('', root, null);
900     } else if ( window.ActiveXObject ) {
901         doc = new ActiveXObject("MSXML2.DOMDocument");
902         doc.loadXML('<' + root + '/>');
903     } else {
904         throw new Error ('No XML support in this browser');
905     }
906
907     return doc;
908 }
909
910    
911 DOMDoc.parseXmlFromString = function ( xmlString ) 
912 {
913     var doc;
914
915     if ( window.DOMParser ) {
916         var parser = new DOMParser();
917         doc = parser.parseFromString( xmlString, "text/xml");
918     } else if ( window.ActiveXObject ) {
919         doc = new ActiveXObject("MSXML2.DOMDocument");
920         doc.loadXML( xmlString );
921     } else {
922         throw new Error ("No XML parsing support in this browser.");
923     }
924
925     return doc;
926 }
927
928 DOMDoc.transformToDoc = function (xmlDoc, xslDoc)
929 {
930     if ( window.XSLTProcessor ) {
931         var proc = new XSLTProcessor();
932         proc.importStylesheet( xslDoc );
933         return proc.transformToDocument(xmlDoc);
934     } else if ( window.ActiveXObject ) {
935         return document.parseXmlFromString(xmlDoc.transformNode(xslDoc));
936     } else {
937         alert( 'Unable to perform XSLT transformation in this browser' );
938     }
939 }
940  
941 // DOMElement
942
943 Element_removeFromDoc = function (DOM_Element)
944 {
945     DOM_Element.parentNode.removeChild(DOM_Element);
946 }
947
948 Element_emptyChildren = function (DOM_Element)
949 {
950     while( DOM_Element.firstChild ) {
951         DOM_Element.removeChild( DOM_Element.firstChild )
952     }
953 }
954
955 Element_appendTransformResult = function ( DOM_Element, xmlDoc, xslDoc )
956 {
957     if ( window.XSLTProcessor ) {
958         var proc = new XSLTProcessor();
959         proc.importStylesheet( xslDoc );
960         var docFrag = false;
961         docFrag = proc.transformToFragment( xmlDoc, DOM_Element.ownerDocument );
962         DOM_Element.appendChild(docFrag);
963     } else if ( window.ActiveXObject ) {
964         DOM_Element.innerHTML = xmlDoc.transformNode( xslDoc );
965     } else {
966         alert( 'Unable to perform XSLT transformation in this browser' );
967     }
968 }
969  
970 Element_appendTextNode = function (DOM_Element, tagName, textContent )
971 {
972     var node = DOM_Element.ownerDocument.createElement(tagName);
973     var text = DOM_Element.ownerDocument.createTextNode(textContent);
974
975     DOM_Element.appendChild(node);
976     node.appendChild(text);
977
978     return node;
979 }
980
981 Element_setTextContent = function ( DOM_Element, textContent )
982 {
983     if (typeof DOM_Element.textContent !== "undefined") {
984         DOM_Element.textContent = textContent;
985     } else if (typeof DOM_Element.innerText !== "undefined" ) {
986         DOM_Element.innerText = textContent;
987     } else {
988         throw new Error("Cannot set text content of the node, no such method.");
989     }
990 }
991
992 Element_getTextContent = function (DOM_Element)
993 {
994     if ( typeof DOM_Element.textContent != 'undefined' ) {
995         return DOM_Element.textContent;
996     } else if (typeof DOM_Element.text != 'undefined') {
997         return DOM_Element.text;
998     } else {
999         throw new Error("Cannot get text content of the node, no such method.");
1000     }
1001 }
1002
1003 Element_parseChildNodes = function (node)
1004 {
1005     var parsed = {};
1006     var hasChildElems = false;
1007
1008     if (node.hasChildNodes()) {
1009         var children = node.childNodes;
1010         for (var i = 0; i < children.length; i++) {
1011             var child = children[i];
1012             if (child.nodeType == Node.ELEMENT_NODE) {
1013                 hasChildElems = true;
1014                 var nodeName = child.nodeName; 
1015                 if (!(nodeName in parsed))
1016                     parsed[nodeName] = [];
1017                 parsed[nodeName].push(Element_parseChildNodes(child));
1018             }
1019         }
1020     }
1021
1022     var attrs = node.attributes;
1023     for (var i = 0; i < attrs.length; i++) {
1024         var attrName = '@' + attrs[i].nodeName;
1025         var attrValue = attrs[i].nodeValue;
1026         parsed[attrName] = attrValue;
1027     }
1028
1029     // if no nested elements, get text content
1030     if (node.hasChildNodes() && !hasChildElems) {
1031         if (node.attributes.length) 
1032             parsed['#text'] = node.firstChild.nodeValue;
1033         else
1034             parsed = node.firstChild.nodeValue;
1035     }
1036     
1037     return parsed;
1038 }
1039
1040 /* do not remove trailing bracket */
1041 }