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