add SOLR facets tests
[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                     }
648                     
649                     context.bytargetCounter++;
650                     var delay = context.bytargetTime 
651                         + context.bytargetCounter * context.dumpFactor;
652                     if ( context.activeClients > 0 )
653                         context.bytargetTimer = 
654                             setTimeout(
655                                 function () {
656                                     context.bytarget();
657                                 }, 
658                                 delay
659                             );
660
661                     context.bytargetCallback(bytarget);
662                 }
663                 else
664                     context.throwError('Bytarget failed. Malformed WS resonse.',
665                                         117);
666             }
667         );
668     },
669     
670     // just for testing, probably shouldn't be here
671     showNext: function(page)
672     {
673         var step = page || 1;
674         this.show( ( step * this.currentNum ) + this.currentStart );     
675     },
676
677     showPrev: function(page)
678     {
679         if (this.currentStart == 0 )
680             return false;
681         var step = page || 1;
682         var newStart = this.currentStart - (step * this.currentNum );
683         this.show( newStart > 0 ? newStart : 0 );
684     },
685
686     showPage: function(pageNum)
687     {
688         //var page = pageNum || 1;
689         this.show(pageNum * this.currentNum);
690     }
691 };
692
693 /*
694 ********************************************************************************
695 ** AJAX HELPER CLASS ***********************************************************
696 ********************************************************************************
697 */
698 var pzHttpRequest = function ( url, errorHandler ) {
699         this.maxUrlLength = 2048;
700         this.request = null;
701         this.url = url;
702         this.errorHandler = errorHandler || null;
703         this.async = true;
704         this.requestHeaders = {};
705         
706         if ( window.XMLHttpRequest ) {
707             this.request = new XMLHttpRequest();
708         } else if ( window.ActiveXObject ) {
709             try {
710                 this.request = new ActiveXObject( 'Msxml2.XMLHTTP' );
711             } catch (err) {
712                 this.request = new ActiveXObject( 'Microsoft.XMLHTTP' );
713             }
714         }
715 };
716
717
718 pzHttpRequest.prototype = 
719 {
720     safeGet: function ( params, callback )
721     {
722         var encodedParams =  this.encodeParams(params);
723         var url = this._urlAppendParams(encodedParams);
724         if (url.length >= this.maxUrlLength) {
725             this.requestHeaders["Content-Type"]
726                 = "application/x-www-form-urlencoded";
727             this._send( 'POST', this.url, encodedParams, callback );
728         } else {
729             this._send( 'GET', url, '', callback );
730         }
731     },
732
733     get: function ( params, callback ) 
734     {
735         this._send( 'GET', this._urlAppendParams(this.encodeParams(params)), 
736             '', callback );
737     },
738
739     post: function ( params, data, callback )
740     {
741         this._send( 'POST', this._urlAppendParams(this.encodeParams(params)), 
742             data, callback );
743     },
744
745     load: function ()
746     {
747         this.async = false;
748         this.request.open( 'GET', this.url, this.async );
749         this.request.send('');
750         if ( this.request.status == 200 )
751             return this.request.responseXML;
752     },
753
754     encodeParams: function (params)
755     {
756         var sep = "";
757         var encoded = "";
758         for (var key in params) {
759             if (params[key] != null) {
760                 encoded += sep + key + '=' + encodeURIComponent(params[key]);
761                 sep = '&';
762             }
763         }
764         return encoded;
765     },
766
767     _send: function ( type, url, data, callback)
768     {
769         var context = this;
770         this.callback = callback;
771         this.async = true;
772         this.request.open( type, url, this.async );
773         for (var key in this.requestHeaders)
774             this.request.setRequestHeader(key, this.requestHeaders[key]);
775         this.request.onreadystatechange = function () {
776             context._handleResponse(url); /// url used ONLY for error reporting
777         }
778         this.request.send(data);
779     },
780
781     _urlAppendParams: function (encodedParams)
782     {
783         if (encodedParams)
784             return this.url + "?" + encodedParams;
785         else
786             return this.url;
787     },
788
789     _handleResponse: function (savedUrlForErrorReporting)
790     {
791         if ( this.request.readyState == 4 ) { 
792             // pick up appplication errors first
793             var errNode = null;
794             if (this.request.responseXML &&
795                 (errNode = this.request.responseXML.documentElement)
796                 && errNode.nodeName == 'error') {
797                 var errMsg = errNode.getAttribute("msg");
798                 var errCode = errNode.getAttribute("code");
799                 var errAddInfo = '';
800                 if (errNode.childNodes.length)
801                     errAddInfo = ': ' + errNode.childNodes[0].nodeValue;
802                            
803                 var err = new Error(errMsg + errAddInfo);
804                 err.code = errCode;
805             
806                 if (this.errorHandler) {
807                     this.errorHandler(err);
808                 }
809                 else {
810                     throw err;
811                 }
812             } else if (this.request.status == 200 && 
813                        this.request.responseXML == null) {
814               if (this.request.responseText != null) {
815                 //assume JSON
816                 
817                 var json = null; 
818                 var text = this.request.responseText;
819                 if (typeof window.JSON == "undefined") 
820                     json = eval("(" + text + ")");
821                 else { 
822                     try {
823                         json = JSON.parse(text);
824                     }
825                     catch (e) {
826                         // Safari: eval will fail as well. Considering trying JSON2 (non-native implementation) instead
827                         /* DEBUG only works in mk2-mobile
828                         if (document.getElementById("log")) 
829                             document.getElementById("log").innerHTML = "" + e + " " + length + ": " + text;
830                         */
831                         try {
832                             json = eval("(" + text + ")");
833                         }
834                         catch (e) {
835                             /* DEBUG only works in mk2-mobile
836                             if (document.getElementById("log")) 
837                                 document.getElementById("log").innerHTML = "" + e + " " + length + ": " + text;
838                             */
839                         }
840                     }
841                 } 
842                 this.callback(json, "json");
843               } else {
844                 var err = new Error("XML response is empty but no error " +
845                                     "for " + savedUrlForErrorReporting);
846                 err.code = -1;
847                 if (this.errorHandler) {
848                     this.errorHandler(err);
849                 } else {
850                     throw err;
851                 }
852               }
853             } else if (this.request.status == 200) {
854                 this.callback(this.request.responseXML);
855             } else {
856                 var err = new Error("HTTP response not OK: " 
857                             + this.request.status + " - " 
858                             + this.request.statusText );
859                 err.code = '00' + this.request.status;        
860                 if (this.errorHandler) {
861                     this.errorHandler(err);
862                 }
863                 else {
864                     throw err;
865                 }
866             }
867         }
868     }
869 };
870
871 /*
872 ********************************************************************************
873 ** XML HELPER FUNCTIONS ********************************************************
874 ********************************************************************************
875 */
876
877 // DOMDocument
878
879 if ( window.ActiveXObject) {
880     var DOMDoc = document;
881 } else {
882     var DOMDoc = Document.prototype;
883 }
884
885 DOMDoc.newXmlDoc = function ( root )
886 {
887     var doc;
888
889     if (document.implementation && document.implementation.createDocument) {
890         doc = document.implementation.createDocument('', root, null);
891     } else if ( window.ActiveXObject ) {
892         doc = new ActiveXObject("MSXML2.DOMDocument");
893         doc.loadXML('<' + root + '/>');
894     } else {
895         throw new Error ('No XML support in this browser');
896     }
897
898     return doc;
899 }
900
901    
902 DOMDoc.parseXmlFromString = function ( xmlString ) 
903 {
904     var doc;
905
906     if ( window.DOMParser ) {
907         var parser = new DOMParser();
908         doc = parser.parseFromString( xmlString, "text/xml");
909     } else if ( window.ActiveXObject ) {
910         doc = new ActiveXObject("MSXML2.DOMDocument");
911         doc.loadXML( xmlString );
912     } else {
913         throw new Error ("No XML parsing support in this browser.");
914     }
915
916     return doc;
917 }
918
919 DOMDoc.transformToDoc = function (xmlDoc, xslDoc)
920 {
921     if ( window.XSLTProcessor ) {
922         var proc = new XSLTProcessor();
923         proc.importStylesheet( xslDoc );
924         return proc.transformToDocument(xmlDoc);
925     } else if ( window.ActiveXObject ) {
926         return document.parseXmlFromString(xmlDoc.transformNode(xslDoc));
927     } else {
928         alert( 'Unable to perform XSLT transformation in this browser' );
929     }
930 }
931  
932 // DOMElement
933
934 Element_removeFromDoc = function (DOM_Element)
935 {
936     DOM_Element.parentNode.removeChild(DOM_Element);
937 }
938
939 Element_emptyChildren = function (DOM_Element)
940 {
941     while( DOM_Element.firstChild ) {
942         DOM_Element.removeChild( DOM_Element.firstChild )
943     }
944 }
945
946 Element_appendTransformResult = function ( DOM_Element, xmlDoc, xslDoc )
947 {
948     if ( window.XSLTProcessor ) {
949         var proc = new XSLTProcessor();
950         proc.importStylesheet( xslDoc );
951         var docFrag = false;
952         docFrag = proc.transformToFragment( xmlDoc, DOM_Element.ownerDocument );
953         DOM_Element.appendChild(docFrag);
954     } else if ( window.ActiveXObject ) {
955         DOM_Element.innerHTML = xmlDoc.transformNode( xslDoc );
956     } else {
957         alert( 'Unable to perform XSLT transformation in this browser' );
958     }
959 }
960  
961 Element_appendTextNode = function (DOM_Element, tagName, textContent )
962 {
963     var node = DOM_Element.ownerDocument.createElement(tagName);
964     var text = DOM_Element.ownerDocument.createTextNode(textContent);
965
966     DOM_Element.appendChild(node);
967     node.appendChild(text);
968
969     return node;
970 }
971
972 Element_setTextContent = function ( DOM_Element, textContent )
973 {
974     if (typeof DOM_Element.textContent !== "undefined") {
975         DOM_Element.textContent = textContent;
976     } else if (typeof DOM_Element.innerText !== "undefined" ) {
977         DOM_Element.innerText = textContent;
978     } else {
979         throw new Error("Cannot set text content of the node, no such method.");
980     }
981 }
982
983 Element_getTextContent = function (DOM_Element)
984 {
985     if ( typeof DOM_Element.textContent != 'undefined' ) {
986         return DOM_Element.textContent;
987     } else if (typeof DOM_Element.text != 'undefined') {
988         return DOM_Element.text;
989     } else {
990         throw new Error("Cannot get text content of the node, no such method.");
991     }
992 }
993
994 Element_parseChildNodes = function (node)
995 {
996     var parsed = {};
997     var hasChildElems = false;
998
999     if (node.hasChildNodes()) {
1000         var children = node.childNodes;
1001         for (var i = 0; i < children.length; i++) {
1002             var child = children[i];
1003             if (child.nodeType == Node.ELEMENT_NODE) {
1004                 hasChildElems = true;
1005                 var nodeName = child.nodeName; 
1006                 if (!(nodeName in parsed))
1007                     parsed[nodeName] = [];
1008                 parsed[nodeName].push(Element_parseChildNodes(child));
1009             }
1010         }
1011     }
1012
1013     var attrs = node.attributes;
1014     for (var i = 0; i < attrs.length; i++) {
1015         var attrName = '@' + attrs[i].nodeName;
1016         var attrValue = attrs[i].nodeValue;
1017         parsed[attrName] = attrValue;
1018     }
1019
1020     // if no nested elements, get text content
1021     if (node.hasChildNodes() && !hasChildElems) {
1022         if (node.attributes.length) 
1023             parsed['#text'] = node.firstChild.nodeValue;
1024         else
1025             parsed = node.firstChild.nodeValue;
1026     }
1027     
1028     return parsed;
1029 }
1030
1031 /* do not remove trailing bracket */
1032 }