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