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