3 ** pz2.js - pazpar2's javascript client library.
6 //since explorer is flawed
8 window.Node = new Object();
10 Node.ATTRIBUTE_NODE = 2;
12 Node.CDATA_SECTION_NODE = 4;
13 Node.ENTITY_REFERENCE_NODE = 5;
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;
23 // prevent execution of more than once
24 if(typeof window.pz2 == "undefined") {
25 window.undefined = window.undefined;
27 var pz2 = function ( paramArray )
30 // at least one callback required
32 throw new Error("Pz2.js: Array with parameters has to be supplied.");
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;
40 this.pz2String = "/pazpar2/search.pz2";
41 this.useSessions = true;
43 this.stylesheet = paramArray.detailstylesheet || null;
44 //load stylesheet if required in async mode
45 if( this.stylesheet ) {
47 var request = new pzHttpRequest( this.stylesheet );
48 request.get( {}, function ( doc ) { context.xslDoc = doc; } );
51 this.errorHandler = paramArray.errorhandler || null;
52 this.showResponseType = paramArray.showResponseType || "xml";
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;
64 this.termKeys = paramArray.termlist || "subject";
66 // some configurational stuff
67 this.keepAlive = 50000;
69 if ( paramArray.keepAlive < this.keepAlive )
70 this.keepAlive = paramArray.keepAlive;
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;
81 this.currentSort = "relevance";
84 this.currentStart = 0;
85 // currentNum can be overwritten in show
88 // last full record retrieved
89 this.currRecID = null;
92 this.currQuery = null;
94 //current raw record offset
95 this.currRecOffset = null;
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;
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;
119 // active clients, updated by stat and show
120 // might be an issue since bytarget will poll accordingly
121 this.activeClients = 1;
123 // if in proxy mode no need to init
124 if (paramArray.usesessions != undefined) {
125 this.useSessions = paramArray.usesessions;
126 this.initStatusOK = true;
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);
133 this.version = paramArray.version || null;
138 //error handler for async error throws
139 throwError: function (errMsg, errCode)
141 var err = new Error(errMsg);
142 if (errCode) err.code = errCode;
144 if (this.errorHandler) {
145 this.errorHandler(err);
152 // stop activity by clearing tiemouts
155 clearTimeout(this.statTimer);
156 clearTimeout(this.showTimer);
157 clearTimeout(this.termTimer);
158 clearTimeout(this.bytargetTimer);
161 // reset status variables
164 if ( this.useSessions ) {
165 this.sessionID = null;
166 this.initStatusOK = false;
167 this.pingStatusOK = false;
168 clearTimeout(this.pingTimer);
170 this.searchStatusOK = false;
173 if ( this.resetCallback )
174 this.resetCallback(this.windowid);
177 init: function (sessionId, serviceId)
181 // session id as a param
182 if (sessionId && this.useSessions ) {
183 this.initStatusOK = true;
184 this.sessionID = sessionId;
186 // old school direct pazpar2 init
187 } else if (this.useSessions) {
189 var request = new pzHttpRequest(this.pz2String, this.errorHandler);
190 var opts = {'command' : 'init'};
191 if (serviceId) opts.service = serviceId;
195 if ( data.getElementsByTagName("status")[0]
196 .childNodes[0].nodeValue == "OK" ) {
197 if ( data.getElementsByTagName("protocol")[0]
198 .childNodes[0].nodeValue
199 != context.suppProtoVer )
201 "Server's protocol not supported by the client"
203 context.initStatusOK = true;
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;
217 if ( context.initCallback )
218 context.initCallback(context.windowid);
221 context.throwError('Init failed. Malformed WS resonse.',
225 // when through proxy no need to init
227 this.initStatusOK = true;
230 // no need to ping explicitly
233 // pinging only makes sense when using pazpar2 directly
234 if( !this.initStatusOK || !this.useSessions )
236 'Pz2.js: Ping not allowed (proxy mode) or session not initialized.'
240 clearTimeout(context.pingTimer);
242 var request = new pzHttpRequest(this.pz2String, this.errorHandler);
244 { "command": "ping", "session": this.sessionID, "windowid" : context.windowid },
246 if ( data.getElementsByTagName("status")[0]
247 .childNodes[0].nodeValue == "OK" ) {
248 context.pingStatusOK = true;
258 context.throwError('Ping failed. Malformed WS resonse.',
263 search: function (query, num, sort, filter, showfrom, addParamsArr)
265 clearTimeout(this.statTimer);
266 clearTimeout(this.showTimer);
267 clearTimeout(this.termTimer);
268 clearTimeout(this.bytargetTimer);
270 this.showCounter = 0;
271 this.termCounter = 0;
272 this.bytargetCounter = 0;
273 this.statCounter = 0;
274 this.activeClients = 1;
277 if( !this.initStatusOK )
278 throw new Error('Pz2.js: session not initialized.');
280 if( query !== undefined )
281 this.currQuery = query;
283 throw new Error("Pz2.js: no query supplied to the search command.");
285 if ( showfrom !== undefined )
286 var start = showfrom;
292 "query": this.currQuery,
293 "session": this.sessionID,
294 "windowid" : this.windowid
297 if( sort !== undefined ) {
298 this.currentSort = sort;
299 searchParams["sort"] = sort;
301 if (filter !== undefined) searchParams["filter"] = filter;
302 if (this.mergekey) searchParams["mergekey"] = this.mergekey;
303 if (this.rank) searchParams["rank"] = this.rank;
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];
314 var request = new pzHttpRequest(this.pz2String, this.errorHandler);
318 if ( data.getElementsByTagName("status")[0]
319 .childNodes[0].nodeValue == "OK" ) {
320 context.searchStatusOK = true;
322 if (context.showCallback)
323 context.show(start, num, sort);
324 if (context.statCallback)
326 if (context.termlistCallback)
328 if (context.bytargetCallback)
332 context.throwError('Search failed. Malformed WS resonse.',
339 if( !this.initStatusOK )
340 throw new Error('Pz2.js: session not initialized.');
342 // if called explicitly takes precedence
343 clearTimeout(this.statTimer);
346 var request = new pzHttpRequest(this.pz2String, this.errorHandler);
348 { "command": "stat", "session": this.sessionID, "windowid" : context.windowid },
350 if ( data.getElementsByTagName("stat") ) {
352 Number( data.getElementsByTagName("activeclients")[0]
353 .childNodes[0].nodeValue );
354 context.activeClients = activeClients;
356 var stat = Element_parseChildNodes(data.documentElement);
358 context.statCounter++;
359 var delay = context.statTime
360 + context.statCounter * context.dumpFactor;
362 if ( activeClients > 0 )
370 context.statCallback(stat, context.windowid);
373 context.throwError('Stat failed. Malformed WS resonse.',
378 show: function(start, num, sort, query_state)
380 if( !this.searchStatusOK && this.useSessions )
382 'Pz2.js: show command has to be preceded with a search command.'
385 // if called explicitly takes precedence
386 clearTimeout(this.showTimer);
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 );
396 var request = new pzHttpRequest(this.pz2String, this.errorHandler);
397 var requestParameters =
400 "session": this.sessionID,
401 "start": this.currentStart,
402 "num": this.currentNum,
403 "sort": this.currentSort,
405 "type": this.showResponseType,
406 "windowid" : this.windowid
409 requestParameters["query-state"] = query_state;
410 if (this.version && this.version > 0)
411 requestParameters["version"] = this.version;
414 function(data, type) {
416 var activeClients = 0;
417 if (type === "json") {
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
431 Number(data.getElementsByTagName("activeclients")[0]
432 .childNodes[0].nodeValue);
434 "activeclients": activeClients,
436 Number( data.getElementsByTagName("merged")[0]
437 .childNodes[0].nodeValue ),
439 Number( data.getElementsByTagName("total")[0]
440 .childNodes[0].nodeValue ),
442 Number( data.getElementsByTagName("start")[0]
443 .childNodes[0].nodeValue ),
445 Number( data.getElementsByTagName("num")[0]
446 .childNodes[0].nodeValue ),
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]);
454 context.throwError('Show failed. Malformed WS resonse.',
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);
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(
476 context.showCallback(show, context.windowid);
480 record: function(id, offset, syntax, handler)
482 // we may call record with no previous search if in proxy mode
483 if(!this.searchStatusOK && this.useSessions)
485 'Pz2.js: record command has to be preceded with a search command.'
488 if( id !== undefined )
493 "session": this.sessionID,
494 "id": this.currRecID,
495 "windowid" : this.windowid
498 this.currRecOffset = null;
499 if (offset != undefined) {
500 recordParams["offset"] = offset;
501 this.currRecOffset = offset;
504 if (syntax != undefined)
505 recordParams['syntax'] = syntax;
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'];
516 var request = new pzHttpRequest(this.pz2String, this.errorHandler);
524 if (context.currRecOffset !== null) {
525 record = new Array();
526 record['xmlDoc'] = data;
527 record['offset'] = context.currRecOffset;
528 callback(record, args, context.windowid);
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;
538 recordNode.getElementsByTagName("recid")[0]
539 .firstChild.nodeValue;
542 record = Element_parseChildNodes(recordNode);
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 =
554 context.record(id, offset, syntax, handler);
558 callback(record, args, context.windowid);
561 context.throwError('Record failed. Malformed WS resonse.',
569 if( !this.searchStatusOK && this.useSessions )
571 'Pz2.js: termlist command has to be preceded with a search command.'
574 // if called explicitly takes precedence
575 clearTimeout(this.termTimer);
578 var request = new pzHttpRequest(this.pz2String, this.errorHandler);
581 "command": "termlist",
582 "session": this.sessionID,
583 "name": this.termKeys,
584 "windowid" : this.windowid,
585 "version" : this.version
589 if ( data.getElementsByTagName("termlist") ) {
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");
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++) {
605 (terms[j].getElementsByTagName("name")[0]
607 ? terms[j].getElementsByTagName("name")[0]
608 .childNodes[0].nodeValue
612 .getElementsByTagName("frequency")[0]
613 .childNodes[0].nodeValue || 'ERROR'
616 // Only for xtargets: id, records, filtered
618 terms[j].getElementsByTagName("id");
619 if(terms[j].getElementsByTagName("id").length)
621 termIdNode[0].childNodes[0].nodeValue;
622 termList[listName][j] = term;
624 var recordsNode = terms[j].getElementsByTagName("records");
625 if (recordsNode && recordsNode.length)
626 term["records"] = recordsNode[0].childNodes[0].nodeValue;
628 var filteredNode = terms[j].getElementsByTagName("filtered");
629 if (filteredNode && filteredNode.length)
630 term["filtered"] = filteredNode[0].childNodes[0].nodeValue;
635 context.termCounter++;
636 var delay = context.termTime
637 + context.termCounter * context.dumpFactor;
638 if ( activeClients > 0 )
647 context.termlistCallback(termList, context.windowid);
650 context.throwError('Termlist failed. Malformed WS resonse.',
658 if( !this.initStatusOK && this.useSessions )
660 'Pz2.js: bytarget command has to be preceded with a search command.'
663 // no need to continue
664 if( !this.searchStatusOK )
667 // if called explicitly takes precedence
668 clearTimeout(this.bytargetTimer);
671 var request = new pzHttpRequest(this.pz2String, this.errorHandler);
674 "command": "bytarget",
675 "session": this.sessionID,
677 "windowid" : this.windowid,
678 "version" : this.version
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 ) {
691 targetNodes[i].childNodes[j].nodeName;
692 if (targetNodes[i].childNodes[j].firstChild != null)
694 var nodeText = targetNodes[i].childNodes[j]
695 .firstChild.nodeValue;
696 bytarget[i][nodeName] = nodeText;
699 bytarget[i][nodeName] = "";
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"] = "...";
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";
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);
724 context.bytargetCounter++;
725 var delay = context.bytargetTime
726 + context.bytargetCounter * context.dumpFactor;
727 if ( context.activeClients > 0 )
728 context.bytargetTimer =
736 context.bytargetCallback(bytarget, context.windowid);
739 context.throwError('Bytarget failed. Malformed WS resonse.',
745 // just for testing, probably shouldn't be here
746 showNext: function(page)
748 var step = page || 1;
749 this.show( ( step * this.currentNum ) + this.currentStart );
752 showPrev: function(page)
754 if (this.currentStart == 0 )
756 var step = page || 1;
757 var newStart = this.currentStart - (step * this.currentNum );
758 this.show( newStart > 0 ? newStart : 0 );
761 showPage: function(pageNum)
763 //var page = pageNum || 1;
764 this.show(pageNum * this.currentNum);
769 ********************************************************************************
770 ** AJAX HELPER CLASS ***********************************************************
771 ********************************************************************************
773 var pzHttpRequest = function (url, errorHandler, cookieDomain, windowId) {
774 this.maxUrlLength = 2048;
777 this.errorHandler = errorHandler || null;
779 this.requestHeaders = {};
781 this.domainRegex = /https?:\/\/([^:/]+).*/;
782 this.cookieDomain = cookieDomain || null;
783 this.windowId = windowId || window.name;
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();
795 // CORS not supported.
801 pzHttpRequest.prototype =
803 safeGet: function ( params, callback )
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 );
812 this._send( 'GET', url, '', callback );
816 get: function ( params, callback )
818 this._send( 'GET', this._urlAppendParams(this.encodeParams(params)),
822 post: function ( params, data, callback )
824 this._send( 'POST', this._urlAppendParams(this.encodeParams(params)),
831 this.request.open( 'GET', this.url, this.async );
832 this.request.send('');
833 if ( this.request.status == 200 )
834 return this.request.responseXML;
837 encodeParams: function (params)
841 for (var key in params) {
842 if (params[key] != null) {
843 encoded += sep + key + '=' + encodeURIComponent(params[key]);
850 _getDomainFromUrl: function (url)
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;
857 _strEndsWith: function (str, suffix)
859 return str.indexOf(suffix, str.length - suffix.length) !== -1;
862 _isCrossDomain: function (domain)
864 if (this.cookieDomain) return true; //assume xdomain is cookie domain set
865 return !this._strEndsWith(domain, document.domain);
868 getCookie: function (sKey) {
869 return decodeURI(document.cookie.replace(new RegExp("(?:(?:^|.*;)\\s*"
870 + encodeURI(sKey).replace(/[\-\.\+\*]/g, "\\$&")
871 + "\\s*\\=\\s*([^;]*).*$)|^.*$"), "$1")) || null;
874 setCookie: function (sKey, sValue, vEnd, sPath, sDomain, bSecure) {
875 if (!sKey || /^(?:expires|max\-age|path|domain|secure)$/i.test(sKey)) {
880 switch (vEnd.constructor) {
882 sExpires = vEnd === Infinity
883 ? "; expires=Fri, 31 Dec 9999 23:59:59 GMT"
884 : "; max-age=" + vEnd;
887 sExpires = "; expires=" + vEnd;
890 sExpires = "; expires=" + vEnd.toGMTString();
894 document.cookie = encodeURI(sKey) + "=" + encodeURI(sValue)
896 + (sDomain ? "; domain=" + sDomain : "")
897 + (sPath ? "; path=" + sPath : "")
898 + (bSecure ? "; secure" : "");
902 _send: function ( type, url, data, callback)
905 this.callback = callback;
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")) {
913 var sessparam = ';jsessionid=' + this.getCookie(domain+":"+this.windowId+":SESSID");
914 var q = url.indexOf('?');
918 url = url.substring(0, q) + sessparam + url.substring(q);
921 this.request.open( type, url, this.async );
923 //setting headers is only allowed with XHR
924 for (var key in this.requestHeaders)
925 this.request.setRequestHeader(key, this.requestHeaders[key]);
928 this.request.onload = function () {
930 context.request.status = 200;
931 context.request.readyState = 4;
933 context._handleResponse(url);
935 this.request.onerror = function () {
937 context.request.status = 417; //not really, but what can we do
938 context.request.readyState = 4;
940 context._handleResponse(url);
943 this.request.onreadystatechange = function () {
944 context._handleResponse(url); /// url used ONLY for error reporting
947 this.request.send(data);
950 _urlAppendParams: function (encodedParams)
953 return this.url + "?" + encodedParams;
958 _handleResponse: function (requestUrl)
960 if ( this.request.readyState == 4 ) {
961 // pick up appplication errors first
963 // xdomainreq does not have responseXML
965 if (this.request.contentType.match(/\/xml/)){
966 var dom = new ActiveXObject('Microsoft.XMLDOM');
968 dom.loadXML(this.request.responseText);
969 this.request.responseXML = dom;
971 this.request.responseXML = null;
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");
980 if (errNode.childNodes.length)
981 errAddInfo = ': ' + errNode.childNodes[0].nodeValue;
983 var err = new Error(errMsg + errAddInfo);
986 if (this.errorHandler) {
987 this.errorHandler(err);
993 else if (this.request.status == 200 &&
994 this.request.responseXML === null) {
995 if (this.request.responseText !== null) {
998 var text = this.request.responseText;
999 if (typeof window.JSON == "undefined") {
1000 json = eval("(" + text + ")");
1003 json = JSON.parse(text);
1007 this.callback(json, "json");
1009 var err = new Error("XML/Text response is empty but no error " +
1010 "for " + requestUrl);
1012 if (this.errorHandler) {
1013 this.errorHandler(err);
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');
1025 this.setCookie(domain+":"+this.windowId+":SESSID", jsessionId);
1027 this.callback(this.request.responseXML);
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);
1045 ********************************************************************************
1046 ** XML HELPER FUNCTIONS ********************************************************
1047 ********************************************************************************
1052 if ( window.ActiveXObject) {
1053 var DOMDoc = document;
1055 var DOMDoc = Document.prototype;
1058 DOMDoc.newXmlDoc = function ( root )
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 + '/>');
1068 throw new Error ('No XML support in this browser');
1075 DOMDoc.parseXmlFromString = function ( xmlString )
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 );
1086 throw new Error ("No XML parsing support in this browser.");
1092 DOMDoc.transformToDoc = function (xmlDoc, xslDoc)
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));
1101 alert( 'Unable to perform XSLT transformation in this browser' );
1107 Element_removeFromDoc = function (DOM_Element)
1109 DOM_Element.parentNode.removeChild(DOM_Element);
1112 Element_emptyChildren = function (DOM_Element)
1114 while( DOM_Element.firstChild ) {
1115 DOM_Element.removeChild( DOM_Element.firstChild )
1119 Element_appendTransformResult = function ( DOM_Element, xmlDoc, xslDoc )
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 );
1130 alert( 'Unable to perform XSLT transformation in this browser' );
1134 Element_appendTextNode = function (DOM_Element, tagName, textContent )
1136 var node = DOM_Element.ownerDocument.createElement(tagName);
1137 var text = DOM_Element.ownerDocument.createTextNode(textContent);
1139 DOM_Element.appendChild(node);
1140 node.appendChild(text);
1145 Element_setTextContent = function ( DOM_Element, textContent )
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;
1152 throw new Error("Cannot set text content of the node, no such method.");
1156 Element_getTextContent = function (DOM_Element)
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;
1163 throw new Error("Cannot get text content of the node, no such method.");
1167 Element_parseChildNodes = function (node)
1170 var hasChildElems = false;
1171 var textContent = '';
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));
1185 case Node.TEXT_NODE:
1186 textContent += child.nodeValue;
1188 case Node.CDATA_SECTION_NODE:
1189 textContent += child.nodeValue;
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;
1203 // if no nested elements/attrs set value to text
1205 parsed['#text'] = textContent;
1207 parsed = textContent;
1212 /* do not remove trailing bracket */