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