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 var targetsSuggestions = targetNodes[i].getElementsByTagName("suggestions");
713 if (targetsSuggestions != undefined && targetsSuggestions.length>0) {
714 var suggestions = targetsSuggestions[0];
715 bytarget[i]["suggestions"] = Element_parseChildNodes(suggestions);
719 context.bytargetCounter++;
720 var delay = context.bytargetTime
721 + context.bytargetCounter * context.dumpFactor;
722 if ( context.activeClients > 0 )
723 context.bytargetTimer =
731 context.bytargetCallback(bytarget, context.windowid);
734 context.throwError('Bytarget failed. Malformed WS resonse.',
740 // just for testing, probably shouldn't be here
741 showNext: function(page)
743 var step = page || 1;
744 this.show( ( step * this.currentNum ) + this.currentStart );
747 showPrev: function(page)
749 if (this.currentStart == 0 )
751 var step = page || 1;
752 var newStart = this.currentStart - (step * this.currentNum );
753 this.show( newStart > 0 ? newStart : 0 );
756 showPage: function(pageNum)
758 //var page = pageNum || 1;
759 this.show(pageNum * this.currentNum);
764 ********************************************************************************
765 ** AJAX HELPER CLASS ***********************************************************
766 ********************************************************************************
768 var pzHttpRequest = function (url, errorHandler, cookieDomain, windowId) {
769 this.maxUrlLength = 2048;
772 this.errorHandler = errorHandler || null;
774 this.requestHeaders = {};
776 this.domainRegex = /https?:\/\/([^:/]+).*/;
777 this.cookieDomain = cookieDomain || null;
778 this.windowId = windowId || window.name;
780 var xhr = new XMLHttpRequest();
781 var domain = this._getDomainFromUrl(url);
782 if ("withCredentials" in xhr) {
783 // XHR for Chrome/Firefox/Opera/Safari.
784 } else if (domain && this._isCrossDomain(domain) &&
785 typeof XDomainRequest != "undefined") {
786 // use XDR (IE7/8) when no other way
787 xhr = new XDomainRequest();
790 // CORS not supported.
796 pzHttpRequest.prototype =
798 safeGet: function ( params, callback )
800 var encodedParams = this.encodeParams(params);
801 var url = this._urlAppendParams(encodedParams);
802 if (url.length >= this.maxUrlLength) {
803 this.requestHeaders["Content-Type"]
804 = "application/x-www-form-urlencoded";
805 this._send( 'POST', this.url, encodedParams, callback );
807 this._send( 'GET', url, '', callback );
811 get: function ( params, callback )
813 this._send( 'GET', this._urlAppendParams(this.encodeParams(params)),
817 post: function ( params, data, callback )
819 this._send( 'POST', this._urlAppendParams(this.encodeParams(params)),
826 this.request.open( 'GET', this.url, this.async );
827 this.request.send('');
828 if ( this.request.status == 200 )
829 return this.request.responseXML;
832 encodeParams: function (params)
836 for (var key in params) {
837 if (params[key] != null) {
838 encoded += sep + key + '=' + encodeURIComponent(params[key]);
845 _getDomainFromUrl: function (url)
847 if (this.cookieDomain) return this.cookieDomain; //explicit cookie domain
848 var m = this.domainRegex.exec(url);
849 return (m && m.length > 1) ? m[1] : null;
852 _strEndsWith: function (str, suffix)
854 return str.indexOf(suffix, str.length - suffix.length) !== -1;
857 _isCrossDomain: function (domain)
859 if (this.cookieDomain) return true; //assume xdomain is cookie domain set
860 return !this._strEndsWith(domain, document.domain);
863 getCookie: function (sKey) {
864 return decodeURI(document.cookie.replace(new RegExp("(?:(?:^|.*;)\\s*"
865 + encodeURI(sKey).replace(/[\-\.\+\*]/g, "\\$&")
866 + "\\s*\\=\\s*([^;]*).*$)|^.*$"), "$1")) || null;
869 setCookie: function (sKey, sValue, vEnd, sPath, sDomain, bSecure) {
870 if (!sKey || /^(?:expires|max\-age|path|domain|secure)$/i.test(sKey)) {
875 switch (vEnd.constructor) {
877 sExpires = vEnd === Infinity
878 ? "; expires=Fri, 31 Dec 9999 23:59:59 GMT"
879 : "; max-age=" + vEnd;
882 sExpires = "; expires=" + vEnd;
885 sExpires = "; expires=" + vEnd.toGMTString();
889 document.cookie = encodeURI(sKey) + "=" + encodeURI(sValue)
891 + (sDomain ? "; domain=" + sDomain : "")
892 + (sPath ? "; path=" + sPath : "")
893 + (bSecure ? "; secure" : "");
897 _send: function ( type, url, data, callback)
900 this.callback = callback;
902 //we never do withCredentials, so if it's CORS and we have
903 //session cookie, resend it
904 var domain = this._getDomainFromUrl(url);
905 if (domain && this._isCrossDomain(domain) &&
906 this.getCookie(domain+":"+this.windowId+":SESSID")) {
908 var sessparam = ';jsessionid=' + this.getCookie(domain+":"+this.windowId+":SESSID");
909 var q = url.indexOf('?');
913 url = url.substring(0, q) + sessparam + url.substring(q);
916 this.request.open( type, url, this.async );
918 //setting headers is only allowed with XHR
919 for (var key in this.requestHeaders)
920 this.request.setRequestHeader(key, this.requestHeaders[key]);
923 this.request.onload = function () {
925 context.request.status = 200;
926 context.request.readyState = 4;
928 context._handleResponse(url);
930 this.request.onerror = function () {
932 context.request.status = 417; //not really, but what can we do
933 context.request.readyState = 4;
935 context._handleResponse(url);
938 this.request.onreadystatechange = function () {
939 context._handleResponse(url); /// url used ONLY for error reporting
942 this.request.send(data);
945 _urlAppendParams: function (encodedParams)
948 return this.url + "?" + encodedParams;
953 _handleResponse: function (requestUrl)
955 if ( this.request.readyState == 4 ) {
956 // pick up appplication errors first
958 // xdomainreq does not have responseXML
960 if (this.request.contentType.match(/\/xml/)){
961 var dom = new ActiveXObject('Microsoft.XMLDOM');
963 dom.loadXML(this.request.responseText);
964 this.request.responseXML = dom;
966 this.request.responseXML = null;
969 if (this.request.responseXML &&
970 (errNode = this.request.responseXML.documentElement)
971 && errNode.nodeName == 'error') {
972 var errMsg = errNode.getAttribute("msg");
973 var errCode = errNode.getAttribute("code");
975 if (errNode.childNodes.length)
976 errAddInfo = ': ' + errNode.childNodes[0].nodeValue;
978 var err = new Error(errMsg + errAddInfo);
981 if (this.errorHandler) {
982 this.errorHandler(err);
988 else if (this.request.status == 200 &&
989 this.request.responseXML === null) {
990 if (this.request.responseText !== null) {
993 var text = this.request.responseText;
994 if (typeof window.JSON == "undefined") {
995 json = eval("(" + text + ")");
998 json = JSON.parse(text);
1002 this.callback(json, "json");
1004 var err = new Error("XML/Text response is empty but no error " +
1005 "for " + requestUrl);
1007 if (this.errorHandler) {
1008 this.errorHandler(err);
1013 } else if (this.request.status == 200) {
1014 //set cookie manually only if cross-domain
1015 var domain = this._getDomainFromUrl(requestUrl);
1016 if (domain && this._isCrossDomain(domain)) {
1017 var jsessionId = this.request.responseXML
1018 .documentElement.getAttribute('jsessionId');
1020 this.setCookie(domain+":"+this.windowId+":SESSID", jsessionId);
1022 this.callback(this.request.responseXML);
1024 var err = new Error("HTTP response not OK: "
1025 + this.request.status + " - "
1026 + this.request.statusText );
1027 err.code = '00' + this.request.status;
1028 if (this.errorHandler) {
1029 this.errorHandler(err);
1040 ********************************************************************************
1041 ** XML HELPER FUNCTIONS ********************************************************
1042 ********************************************************************************
1047 if ( window.ActiveXObject) {
1048 var DOMDoc = document;
1050 var DOMDoc = Document.prototype;
1053 DOMDoc.newXmlDoc = function ( root )
1057 if (document.implementation && document.implementation.createDocument) {
1058 doc = document.implementation.createDocument('', root, null);
1059 } else if ( window.ActiveXObject ) {
1060 doc = new ActiveXObject("MSXML2.DOMDocument");
1061 doc.loadXML('<' + root + '/>');
1063 throw new Error ('No XML support in this browser');
1070 DOMDoc.parseXmlFromString = function ( xmlString )
1074 if ( window.DOMParser ) {
1075 var parser = new DOMParser();
1076 doc = parser.parseFromString( xmlString, "text/xml");
1077 } else if ( window.ActiveXObject ) {
1078 doc = new ActiveXObject("MSXML2.DOMDocument");
1079 doc.loadXML( xmlString );
1081 throw new Error ("No XML parsing support in this browser.");
1087 DOMDoc.transformToDoc = function (xmlDoc, xslDoc)
1089 if ( window.XSLTProcessor ) {
1090 var proc = new XSLTProcessor();
1091 proc.importStylesheet( xslDoc );
1092 return proc.transformToDocument(xmlDoc);
1093 } else if ( window.ActiveXObject ) {
1094 return document.parseXmlFromString(xmlDoc.transformNode(xslDoc));
1096 alert( 'Unable to perform XSLT transformation in this browser' );
1102 Element_removeFromDoc = function (DOM_Element)
1104 DOM_Element.parentNode.removeChild(DOM_Element);
1107 Element_emptyChildren = function (DOM_Element)
1109 while( DOM_Element.firstChild ) {
1110 DOM_Element.removeChild( DOM_Element.firstChild )
1114 Element_appendTransformResult = function ( DOM_Element, xmlDoc, xslDoc )
1116 if ( window.XSLTProcessor ) {
1117 var proc = new XSLTProcessor();
1118 proc.importStylesheet( xslDoc );
1119 var docFrag = false;
1120 docFrag = proc.transformToFragment( xmlDoc, DOM_Element.ownerDocument );
1121 DOM_Element.appendChild(docFrag);
1122 } else if ( window.ActiveXObject ) {
1123 DOM_Element.innerHTML = xmlDoc.transformNode( xslDoc );
1125 alert( 'Unable to perform XSLT transformation in this browser' );
1129 Element_appendTextNode = function (DOM_Element, tagName, textContent )
1131 var node = DOM_Element.ownerDocument.createElement(tagName);
1132 var text = DOM_Element.ownerDocument.createTextNode(textContent);
1134 DOM_Element.appendChild(node);
1135 node.appendChild(text);
1140 Element_setTextContent = function ( DOM_Element, textContent )
1142 if (typeof DOM_Element.textContent !== "undefined") {
1143 DOM_Element.textContent = textContent;
1144 } else if (typeof DOM_Element.innerText !== "undefined" ) {
1145 DOM_Element.innerText = textContent;
1147 throw new Error("Cannot set text content of the node, no such method.");
1151 Element_getTextContent = function (DOM_Element)
1153 if ( typeof DOM_Element.textContent != 'undefined' ) {
1154 return DOM_Element.textContent;
1155 } else if (typeof DOM_Element.text != 'undefined') {
1156 return DOM_Element.text;
1158 throw new Error("Cannot get text content of the node, no such method.");
1162 Element_parseChildNodes = function (node)
1165 var hasChildElems = false;
1166 var textContent = '';
1168 if (node.hasChildNodes()) {
1169 var children = node.childNodes;
1170 for (var i = 0; i < children.length; i++) {
1171 var child = children[i];
1172 switch (child.nodeType) {
1173 case Node.ELEMENT_NODE:
1174 hasChildElems = true;
1175 var nodeName = child.nodeName;
1176 if (!(nodeName in parsed))
1177 parsed[nodeName] = [];
1178 parsed[nodeName].push(Element_parseChildNodes(child));
1180 case Node.TEXT_NODE:
1181 textContent += child.nodeValue;
1183 case Node.CDATA_SECTION_NODE:
1184 textContent += child.nodeValue;
1190 var attrs = node.attributes;
1191 for (var i = 0; i < attrs.length; i++) {
1192 hasChildElems = true;
1193 var attrName = '@' + attrs[i].nodeName;
1194 var attrValue = attrs[i].nodeValue;
1195 parsed[attrName] = attrValue;
1198 // if no nested elements/attrs set value to text
1200 parsed['#text'] = textContent;
1202 parsed = textContent;
1207 /* do not remove trailing bracket */