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