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