2 * !! WARNING WARNING WARNING WARNING WARNING WARNING WARNING WARNING !!
4 * Do not edit this file. The current version of pz2.js now lives in
5 * its own git module ssh://git.indexdata.com/home/git/pub/pz2js and
6 * ALL FURTHER CHANGES SHOULD BE MADE TO THAT FILE.
8 * This copy will be removed as soon as we have good, solid Debian and
9 * Red Hat releases of the new independent pz2js package and have
10 * modified the pazpar2 packages to depend on it.
12 * !! WARNING WARNING WARNING WARNING WARNING WARNING WARNING WARNING !!
18 ** pz2.js - pazpar2's javascript client library.
21 //since explorer is flawed
22 if (!window['Node']) {
23 window.Node = new Object();
24 Node.ELEMENT_NODE = 1;
25 Node.ATTRIBUTE_NODE = 2;
27 Node.CDATA_SECTION_NODE = 4;
28 Node.ENTITY_REFERENCE_NODE = 5;
30 Node.PROCESSING_INSTRUCTION_NODE = 7;
31 Node.COMMENT_NODE = 8;
32 Node.DOCUMENT_NODE = 9;
33 Node.DOCUMENT_TYPE_NODE = 10;
34 Node.DOCUMENT_FRAGMENT_NODE = 11;
35 Node.NOTATION_NODE = 12;
38 // prevent execution of more than once
39 if(typeof window.pz2 == "undefined") {
40 window.undefined = window.undefined;
42 var pz2 = function ( paramArray )
45 // at least one callback required
47 throw new Error("Pz2.js: Array with parameters has to be supplied.");
49 //supported pazpar2's protocol version
50 this.suppProtoVer = '1';
51 if (typeof paramArray.pazpar2path != "undefined")
52 this.pz2String = paramArray.pazpar2path;
54 this.pz2String = "/pazpar2/search.pz2";
55 this.useSessions = true;
57 this.stylesheet = paramArray.detailstylesheet || null;
58 //load stylesheet if required in async mode
59 if( this.stylesheet ) {
61 var request = new pzHttpRequest( this.stylesheet );
62 request.get( {}, function ( doc ) { context.xslDoc = doc; } );
65 this.errorHandler = paramArray.errorhandler || null;
66 this.showResponseType = paramArray.showResponseType || "xml";
69 this.initCallback = paramArray.oninit || null;
70 this.statCallback = paramArray.onstat || null;
71 this.showCallback = paramArray.onshow || null;
72 this.termlistCallback = paramArray.onterm || null;
73 this.recordCallback = paramArray.onrecord || null;
74 this.bytargetCallback = paramArray.onbytarget || null;
75 this.resetCallback = paramArray.onreset || null;
78 this.termKeys = paramArray.termlist || "subject";
80 // some configurational stuff
81 this.keepAlive = 50000;
83 if ( paramArray.keepAlive < this.keepAlive )
84 this.keepAlive = paramArray.keepAlive;
86 this.sessionID = null;
87 this.serviceId = paramArray.serviceId || null;
88 this.initStatusOK = false;
89 this.pingStatusOK = false;
90 this.searchStatusOK = false;
93 this.currentSort = "relevance";
96 this.currentStart = 0;
97 // currentNum can be overwritten in show
100 // last full record retrieved
101 this.currRecID = null;
104 this.currQuery = null;
106 //current raw record offset
107 this.currRecOffset = null;
110 this.pingTimer = null;
111 this.statTime = paramArray.stattime || 1000;
112 this.statTimer = null;
113 this.termTime = paramArray.termtime || 1000;
114 this.termTimer = null;
115 this.showTime = paramArray.showtime || 1000;
116 this.showTimer = null;
117 this.showFastCount = 4;
118 this.bytargetTime = paramArray.bytargettime || 1000;
119 this.bytargetTimer = null;
120 this.recordTime = paramArray.recordtime || 500;
121 this.recordTimer = null;
123 // counters for each command and applied delay
124 this.dumpFactor = 500;
125 this.showCounter = 0;
126 this.termCounter = 0;
127 this.statCounter = 0;
128 this.bytargetCounter = 0;
129 this.recordCounter = 0;
131 // active clients, updated by stat and show
132 // might be an issue since bytarget will poll accordingly
133 this.activeClients = 1;
135 // if in proxy mode no need to init
136 if (paramArray.usesessions != undefined) {
137 this.useSessions = paramArray.usesessions;
138 this.initStatusOK = true;
140 // else, auto init session or wait for a user init?
141 if (this.useSessions && paramArray.autoInit !== false) {
142 this.init(this.sessionID, this.serviceId);
145 this.version = paramArray.version || null;
150 //error handler for async error throws
151 throwError: function (errMsg, errCode)
153 var err = new Error(errMsg);
154 if (errCode) err.code = errCode;
156 if (this.errorHandler) {
157 this.errorHandler(err);
164 // stop activity by clearing tiemouts
167 clearTimeout(this.statTimer);
168 clearTimeout(this.showTimer);
169 clearTimeout(this.termTimer);
170 clearTimeout(this.bytargetTimer);
173 // reset status variables
176 if ( this.useSessions ) {
177 this.sessionID = null;
178 this.initStatusOK = false;
179 this.pingStatusOK = false;
180 clearTimeout(this.pingTimer);
182 this.searchStatusOK = false;
185 if ( this.resetCallback )
186 this.resetCallback();
189 init: function (sessionId, serviceId)
193 // session id as a param
194 if (sessionId && this.useSessions ) {
195 this.initStatusOK = true;
196 this.sessionID = sessionId;
198 // old school direct pazpar2 init
199 } else if (this.useSessions) {
201 var request = new pzHttpRequest(this.pz2String, this.errorHandler);
202 var opts = {'command' : 'init'};
203 if (serviceId) opts.service = serviceId;
207 if ( data.getElementsByTagName("status")[0]
208 .childNodes[0].nodeValue == "OK" ) {
209 if ( data.getElementsByTagName("protocol")[0]
210 .childNodes[0].nodeValue
211 != context.suppProtoVer )
213 "Server's protocol not supported by the client"
215 context.initStatusOK = true;
217 data.getElementsByTagName("session")[0]
218 .childNodes[0].nodeValue;
219 if (data.getElementsByTagName("keepAlive").length > 0) {
220 context.keepAlive = data.getElementsByTagName("keepAlive")[0].childNodes[0].nodeValue;
229 if ( context.initCallback )
230 context.initCallback();
233 context.throwError('Init failed. Malformed WS resonse.',
237 // when through proxy no need to init
239 this.initStatusOK = true;
242 // no need to ping explicitly
245 // pinging only makes sense when using pazpar2 directly
246 if( !this.initStatusOK || !this.useSessions )
248 'Pz2.js: Ping not allowed (proxy mode) or session not initialized.'
252 clearTimeout(context.pingTimer);
254 var request = new pzHttpRequest(this.pz2String, this.errorHandler);
256 { "command": "ping", "session": this.sessionID, "windowid" : window.name },
258 if ( data.getElementsByTagName("status")[0]
259 .childNodes[0].nodeValue == "OK" ) {
260 context.pingStatusOK = true;
270 context.throwError('Ping failed. Malformed WS resonse.',
275 search: function (query, num, sort, filter, showfrom, addParamsArr)
277 clearTimeout(this.statTimer);
278 clearTimeout(this.showTimer);
279 clearTimeout(this.termTimer);
280 clearTimeout(this.bytargetTimer);
282 this.showCounter = 0;
283 this.termCounter = 0;
284 this.bytargetCounter = 0;
285 this.statCounter = 0;
286 this.activeClients = 1;
289 if( !this.initStatusOK )
290 throw new Error('Pz2.js: session not initialized.');
292 if( query !== undefined )
293 this.currQuery = query;
295 throw new Error("Pz2.js: no query supplied to the search command.");
297 if ( showfrom !== undefined )
298 var start = showfrom;
304 "query": this.currQuery,
305 "session": this.sessionID,
306 "windowid" : window.name
309 if( sort !== undefined ) {
310 this.currentSort = sort;
311 searchParams["sort"] = sort;
313 if (filter !== undefined)
314 searchParams["filter"] = filter;
316 // copy additional parmeters, do not overwrite
317 if (addParamsArr != undefined) {
318 for (var prop in addParamsArr) {
319 if (!searchParams.hasOwnProperty(prop))
320 searchParams[prop] = addParamsArr[prop];
325 var request = new pzHttpRequest(this.pz2String, this.errorHandler);
329 if ( data.getElementsByTagName("status")[0]
330 .childNodes[0].nodeValue == "OK" ) {
331 context.searchStatusOK = true;
333 context.show(start, num, sort);
334 if (context.statCallback)
336 if (context.termlistCallback)
338 if (context.bytargetCallback)
342 context.throwError('Search failed. Malformed WS resonse.',
349 if( !this.initStatusOK )
350 throw new Error('Pz2.js: session not initialized.');
352 // if called explicitly takes precedence
353 clearTimeout(this.statTimer);
356 var request = new pzHttpRequest(this.pz2String, this.errorHandler);
358 { "command": "stat", "session": this.sessionID, "windowid" : window.name },
360 if ( data.getElementsByTagName("stat") ) {
362 Number( data.getElementsByTagName("activeclients")[0]
363 .childNodes[0].nodeValue );
364 context.activeClients = activeClients;
366 var stat = Element_parseChildNodes(data.documentElement);
368 context.statCounter++;
369 var delay = context.statTime
370 + context.statCounter * context.dumpFactor;
372 if ( activeClients > 0 )
380 context.statCallback(stat);
383 context.throwError('Stat failed. Malformed WS resonse.',
388 show: function(start, num, sort, query_state)
390 if( !this.searchStatusOK && this.useSessions )
392 'Pz2.js: show command has to be preceded with a search command.'
395 // if called explicitly takes precedence
396 clearTimeout(this.showTimer);
398 if( sort !== undefined )
399 this.currentSort = sort;
400 if( start !== undefined )
401 this.currentStart = Number( start );
402 if( num !== undefined )
403 this.currentNum = Number( num );
406 var request = new pzHttpRequest(this.pz2String, this.errorHandler);
407 var requestParameters =
410 "session": this.sessionID,
411 "start": this.currentStart,
412 "num": this.currentNum,
413 "sort": this.currentSort,
415 "type": this.showResponseType,
416 "windowid" : window.name
419 requestParameters["query-state"] = query_state;
420 if (this.version && this.version > 0)
421 requestParameters["version"] = this.version;
424 function(data, type) {
426 var activeClients = 0;
427 if (type === "json") {
429 activeClients = Number(data.activeclients[0]);
430 show.activeclients = activeClients;
431 show.merged = Number(data.merged[0]);
432 show.total = Number(data.total[0]);
433 show.start = Number(data.start[0]);
434 show.num = Number(data.num[0]);
435 show.hits = data.hit;
436 } else if (data.getElementsByTagName("status")[0]
437 .childNodes[0].nodeValue == "OK") {
438 // first parse the status data send along with records
439 // this is strictly bound to the format
441 Number(data.getElementsByTagName("activeclients")[0]
442 .childNodes[0].nodeValue);
444 "activeclients": activeClients,
446 Number( data.getElementsByTagName("merged")[0]
447 .childNodes[0].nodeValue ),
449 Number( data.getElementsByTagName("total")[0]
450 .childNodes[0].nodeValue ),
452 Number( data.getElementsByTagName("start")[0]
453 .childNodes[0].nodeValue ),
455 Number( data.getElementsByTagName("num")[0]
456 .childNodes[0].nodeValue ),
459 // parse all the first-level nodes for all <hit> tags
460 var hits = data.getElementsByTagName("hit");
461 for (i = 0; i < hits.length; i++)
462 show.hits[i] = Element_parseChildNodes(hits[i]);
464 context.throwError('Show failed. Malformed WS resonse.',
468 var approxNode = data.getElementsByTagName("approximation");
469 if (approxNode && approxNode[0] && approxNode[0].childNodes[0] && approxNode[0].childNodes[0].nodeValue)
470 show['approximation'] =
471 Number( approxNode[0].childNodes[0].nodeValue);
474 data.getElementsByTagName("")
475 context.activeClients = activeClients;
476 context.showCounter++;
477 var delay = context.showTime;
478 if (context.showCounter > context.showFastCount)
479 delay += context.showCounter * context.dumpFactor;
480 if ( activeClients > 0 )
481 context.showTimer = setTimeout(
486 context.showCallback(show);
490 record: function(id, offset, syntax, handler)
492 // we may call record with no previous search if in proxy mode
493 if(!this.searchStatusOK && this.useSessions)
495 'Pz2.js: record command has to be preceded with a search command.'
498 if( id !== undefined )
503 "session": this.sessionID,
504 "id": this.currRecID,
505 "windowid" : window.name
508 this.currRecOffset = null;
509 if (offset != undefined) {
510 recordParams["offset"] = offset;
511 this.currRecOffset = offset;
514 if (syntax != undefined)
515 recordParams['syntax'] = syntax;
517 //overwrite default callback id needed
518 var callback = this.recordCallback;
519 var args = undefined;
520 if (handler != undefined) {
521 callback = handler['callback'];
522 args = handler['args'];
526 var request = new pzHttpRequest(this.pz2String, this.errorHandler);
534 if (context.currRecOffset !== null) {
535 record = new Array();
536 record['xmlDoc'] = data;
537 record['offset'] = context.currRecOffset;
538 callback(record, args);
540 } else if ( recordNode =
541 data.getElementsByTagName("record")[0] ) {
542 // if stylesheet was fetched do not parse the response
543 if ( context.xslDoc ) {
544 record = new Array();
545 record['xmlDoc'] = data;
546 record['xslDoc'] = context.xslDoc;
548 recordNode.getElementsByTagName("recid")[0]
549 .firstChild.nodeValue;
552 record = Element_parseChildNodes(recordNode);
555 Number( data.getElementsByTagName("activeclients")[0]
556 .childNodes[0].nodeValue );
557 context.activeClients = activeClients;
558 context.recordCounter++;
559 var delay = context.recordTime + context.recordCounter * context.dumpFactor;
560 if ( activeClients > 0 )
561 context.recordTimer =
564 context.record(id, offset, syntax, handler);
568 callback(record, args);
571 context.throwError('Record failed. Malformed WS resonse.',
579 if( !this.searchStatusOK && this.useSessions )
581 'Pz2.js: termlist command has to be preceded with a search command.'
584 // if called explicitly takes precedence
585 clearTimeout(this.termTimer);
588 var request = new pzHttpRequest(this.pz2String, this.errorHandler);
591 "command": "termlist",
592 "session": this.sessionID,
593 "name": this.termKeys,
594 "windowid" : window.name,
595 "version" : this.version
599 if ( data.getElementsByTagName("termlist") ) {
601 Number( data.getElementsByTagName("activeclients")[0]
602 .childNodes[0].nodeValue );
603 context.activeClients = activeClients;
604 var termList = { "activeclients": activeClients };
605 var termLists = data.getElementsByTagName("list");
607 for (i = 0; i < termLists.length; i++) {
608 var listName = termLists[i].getAttribute('name');
609 termList[listName] = new Array();
610 var terms = termLists[i].getElementsByTagName('term');
611 //for each term in the list
612 for (j = 0; j < terms.length; j++) {
615 (terms[j].getElementsByTagName("name")[0]
617 ? terms[j].getElementsByTagName("name")[0]
618 .childNodes[0].nodeValue
622 .getElementsByTagName("frequency")[0]
623 .childNodes[0].nodeValue || 'ERROR'
626 // Only for xtargets: id, records, filtered
628 terms[j].getElementsByTagName("id");
629 if(terms[j].getElementsByTagName("id").length)
631 termIdNode[0].childNodes[0].nodeValue;
632 termList[listName][j] = term;
634 var recordsNode = terms[j].getElementsByTagName("records");
635 if (recordsNode && recordsNode.length)
636 term["records"] = recordsNode[0].childNodes[0].nodeValue;
638 var filteredNode = terms[j].getElementsByTagName("filtered");
639 if (filteredNode && filteredNode.length)
640 term["filtered"] = filteredNode[0].childNodes[0].nodeValue;
645 context.termCounter++;
646 var delay = context.termTime
647 + context.termCounter * context.dumpFactor;
648 if ( activeClients > 0 )
657 context.termlistCallback(termList);
660 context.throwError('Termlist failed. Malformed WS resonse.',
668 if( !this.initStatusOK && this.useSessions )
670 'Pz2.js: bytarget command has to be preceded with a search command.'
673 // no need to continue
674 if( !this.searchStatusOK )
677 // if called explicitly takes precedence
678 clearTimeout(this.bytargetTimer);
681 var request = new pzHttpRequest(this.pz2String, this.errorHandler);
684 "command": "bytarget",
685 "session": this.sessionID,
687 "windowid" : window.name,
688 "version" : this.version
691 if ( data.getElementsByTagName("status")[0]
692 .childNodes[0].nodeValue == "OK" ) {
693 var targetNodes = data.getElementsByTagName("target");
694 var bytarget = new Array();
695 for ( i = 0; i < targetNodes.length; i++) {
696 bytarget[i] = new Array();
697 for( j = 0; j < targetNodes[i].childNodes.length; j++ ) {
698 if ( targetNodes[i].childNodes[j].nodeType
699 == Node.ELEMENT_NODE ) {
701 targetNodes[i].childNodes[j].nodeName;
702 if (targetNodes[i].childNodes[j].firstChild != null)
704 var nodeText = targetNodes[i].childNodes[j]
705 .firstChild.nodeValue;
706 bytarget[i][nodeName] = nodeText;
709 bytarget[i][nodeName] = "";
715 if (bytarget[i]["state"]=="Client_Disconnected") {
716 bytarget[i]["hits"] = "Error";
717 } else if (bytarget[i]["state"]=="Client_Error") {
718 bytarget[i]["hits"] = "Error";
719 } else if (bytarget[i]["state"]=="Client_Working") {
720 bytarget[i]["hits"] = "...";
722 if (bytarget[i].diagnostic == "1") {
723 bytarget[i].diagnostic = "Permanent system error";
724 } else if (bytarget[i].diagnostic == "2") {
725 bytarget[i].diagnostic = "Temporary system error";
727 var targetsSuggestions = targetNodes[i].getElementsByTagName("suggestions");
728 if (targetsSuggestions != undefined && targetsSuggestions.length>0) {
729 var suggestions = targetsSuggestions[0];
730 bytarget[i]["suggestions"] = Element_parseChildNodes(suggestions);
734 context.bytargetCounter++;
735 var delay = context.bytargetTime
736 + context.bytargetCounter * context.dumpFactor;
737 if ( context.activeClients > 0 )
738 context.bytargetTimer =
746 context.bytargetCallback(bytarget);
749 context.throwError('Bytarget failed. Malformed WS resonse.',
755 // just for testing, probably shouldn't be here
756 showNext: function(page)
758 var step = page || 1;
759 this.show( ( step * this.currentNum ) + this.currentStart );
762 showPrev: function(page)
764 if (this.currentStart == 0 )
766 var step = page || 1;
767 var newStart = this.currentStart - (step * this.currentNum );
768 this.show( newStart > 0 ? newStart : 0 );
771 showPage: function(pageNum)
773 //var page = pageNum || 1;
774 this.show(pageNum * this.currentNum);
779 ********************************************************************************
780 ** AJAX HELPER CLASS ***********************************************************
781 ********************************************************************************
783 var pzHttpRequest = function ( url, errorHandler ) {
784 this.maxUrlLength = 2048;
787 this.errorHandler = errorHandler || null;
789 this.requestHeaders = {};
791 if ( window.XMLHttpRequest ) {
792 this.request = new XMLHttpRequest();
793 } else if ( window.ActiveXObject ) {
795 this.request = new ActiveXObject( 'Msxml2.XMLHTTP' );
797 this.request = new ActiveXObject( 'Microsoft.XMLHTTP' );
803 pzHttpRequest.prototype =
805 safeGet: function ( params, callback )
807 var encodedParams = this.encodeParams(params);
808 var url = this._urlAppendParams(encodedParams);
809 if (url.length >= this.maxUrlLength) {
810 this.requestHeaders["Content-Type"]
811 = "application/x-www-form-urlencoded";
812 this._send( 'POST', this.url, encodedParams, callback );
814 this._send( 'GET', url, '', callback );
818 get: function ( params, callback )
820 this._send( 'GET', this._urlAppendParams(this.encodeParams(params)),
824 post: function ( params, data, callback )
826 this._send( 'POST', this._urlAppendParams(this.encodeParams(params)),
833 this.request.open( 'GET', this.url, this.async );
834 this.request.send('');
835 if ( this.request.status == 200 )
836 return this.request.responseXML;
839 encodeParams: function (params)
843 for (var key in params) {
844 if (params[key] != null) {
845 encoded += sep + key + '=' + encodeURIComponent(params[key]);
852 _send: function ( type, url, data, callback)
855 this.callback = callback;
857 this.request.open( type, url, this.async );
858 for (var key in this.requestHeaders)
859 this.request.setRequestHeader(key, this.requestHeaders[key]);
860 this.request.onreadystatechange = function () {
861 context._handleResponse(url); /// url used ONLY for error reporting
863 this.request.send(data);
866 _urlAppendParams: function (encodedParams)
869 return this.url + "?" + encodedParams;
874 _handleResponse: function (savedUrlForErrorReporting)
876 if ( this.request.readyState == 4 ) {
877 // pick up appplication errors first
879 if (this.request.responseXML &&
880 (errNode = this.request.responseXML.documentElement)
881 && errNode.nodeName == 'error') {
882 var errMsg = errNode.getAttribute("msg");
883 var errCode = errNode.getAttribute("code");
885 if (errNode.childNodes.length)
886 errAddInfo = ': ' + errNode.childNodes[0].nodeValue;
888 var err = new Error(errMsg + errAddInfo);
891 if (this.errorHandler) {
892 this.errorHandler(err);
897 } else if (this.request.status == 200 &&
898 this.request.responseXML == null) {
899 if (this.request.responseText != null) {
903 var text = this.request.responseText;
904 if (typeof window.JSON == "undefined")
905 json = eval("(" + text + ")");
908 json = JSON.parse(text);
911 // Safari: eval will fail as well. Considering trying JSON2 (non-native implementation) instead
912 /* DEBUG only works in mk2-mobile
913 if (document.getElementById("log"))
914 document.getElementById("log").innerHTML = "" + e + " " + length + ": " + text;
917 json = eval("(" + text + ")");
920 /* DEBUG only works in mk2-mobile
921 if (document.getElementById("log"))
922 document.getElementById("log").innerHTML = "" + e + " " + length + ": " + text;
927 this.callback(json, "json");
929 var err = new Error("XML response is empty but no error " +
930 "for " + savedUrlForErrorReporting);
932 if (this.errorHandler) {
933 this.errorHandler(err);
938 } else if (this.request.status == 200) {
939 this.callback(this.request.responseXML);
941 var err = new Error("HTTP response not OK: "
942 + this.request.status + " - "
943 + this.request.statusText );
944 err.code = '00' + this.request.status;
945 if (this.errorHandler) {
946 this.errorHandler(err);
957 ********************************************************************************
958 ** XML HELPER FUNCTIONS ********************************************************
959 ********************************************************************************
964 if ( window.ActiveXObject) {
965 var DOMDoc = document;
967 var DOMDoc = Document.prototype;
970 DOMDoc.newXmlDoc = function ( root )
974 if (document.implementation && document.implementation.createDocument) {
975 doc = document.implementation.createDocument('', root, null);
976 } else if ( window.ActiveXObject ) {
977 doc = new ActiveXObject("MSXML2.DOMDocument");
978 doc.loadXML('<' + root + '/>');
980 throw new Error ('No XML support in this browser');
987 DOMDoc.parseXmlFromString = function ( xmlString )
991 if ( window.DOMParser ) {
992 var parser = new DOMParser();
993 doc = parser.parseFromString( xmlString, "text/xml");
994 } else if ( window.ActiveXObject ) {
995 doc = new ActiveXObject("MSXML2.DOMDocument");
996 doc.loadXML( xmlString );
998 throw new Error ("No XML parsing support in this browser.");
1004 DOMDoc.transformToDoc = function (xmlDoc, xslDoc)
1006 if ( window.XSLTProcessor ) {
1007 var proc = new XSLTProcessor();
1008 proc.importStylesheet( xslDoc );
1009 return proc.transformToDocument(xmlDoc);
1010 } else if ( window.ActiveXObject ) {
1011 return document.parseXmlFromString(xmlDoc.transformNode(xslDoc));
1013 alert( 'Unable to perform XSLT transformation in this browser' );
1019 Element_removeFromDoc = function (DOM_Element)
1021 DOM_Element.parentNode.removeChild(DOM_Element);
1024 Element_emptyChildren = function (DOM_Element)
1026 while( DOM_Element.firstChild ) {
1027 DOM_Element.removeChild( DOM_Element.firstChild )
1031 Element_appendTransformResult = function ( DOM_Element, xmlDoc, xslDoc )
1033 if ( window.XSLTProcessor ) {
1034 var proc = new XSLTProcessor();
1035 proc.importStylesheet( xslDoc );
1036 var docFrag = false;
1037 docFrag = proc.transformToFragment( xmlDoc, DOM_Element.ownerDocument );
1038 DOM_Element.appendChild(docFrag);
1039 } else if ( window.ActiveXObject ) {
1040 DOM_Element.innerHTML = xmlDoc.transformNode( xslDoc );
1042 alert( 'Unable to perform XSLT transformation in this browser' );
1046 Element_appendTextNode = function (DOM_Element, tagName, textContent )
1048 var node = DOM_Element.ownerDocument.createElement(tagName);
1049 var text = DOM_Element.ownerDocument.createTextNode(textContent);
1051 DOM_Element.appendChild(node);
1052 node.appendChild(text);
1057 Element_setTextContent = function ( DOM_Element, textContent )
1059 if (typeof DOM_Element.textContent !== "undefined") {
1060 DOM_Element.textContent = textContent;
1061 } else if (typeof DOM_Element.innerText !== "undefined" ) {
1062 DOM_Element.innerText = textContent;
1064 throw new Error("Cannot set text content of the node, no such method.");
1068 Element_getTextContent = function (DOM_Element)
1070 if ( typeof DOM_Element.textContent != 'undefined' ) {
1071 return DOM_Element.textContent;
1072 } else if (typeof DOM_Element.text != 'undefined') {
1073 return DOM_Element.text;
1075 throw new Error("Cannot get text content of the node, no such method.");
1079 Element_parseChildNodes = function (node)
1082 var hasChildElems = false;
1083 var textContent = '';
1085 if (node.hasChildNodes()) {
1086 var children = node.childNodes;
1087 for (var i = 0; i < children.length; i++) {
1088 var child = children[i];
1089 switch (child.nodeType) {
1090 case Node.ELEMENT_NODE:
1091 hasChildElems = true;
1092 var nodeName = child.nodeName;
1093 if (!(nodeName in parsed))
1094 parsed[nodeName] = [];
1095 parsed[nodeName].push(Element_parseChildNodes(child));
1097 case Node.TEXT_NODE:
1098 textContent += child.nodeValue;
1100 case Node.CDATA_SECTION_NODE:
1101 textContent += child.nodeValue;
1107 var attrs = node.attributes;
1108 for (var i = 0; i < attrs.length; i++) {
1109 hasChildElems = true;
1110 var attrName = '@' + attrs[i].nodeName;
1111 var attrValue = attrs[i].nodeValue;
1112 parsed[attrName] = attrValue;
1115 // if no nested elements/attrs set value to text
1117 parsed['#text'] = textContent;
1119 parsed = textContent;
1124 /* do not remove trailing bracket */