Affichage d'un bouton de connexion, juste après la réinitialisation du mot de passe.
[Plinn.git] / skins / ajax_scripts / sarissa.js
1 /*
2 * ====================================================================
3 * About Sarissa: http://dev.abiss.gr/sarissa
4 * ====================================================================
5 * Sarissa is an ECMAScript library acting as a cross-browser wrapper for native XML APIs.
6 * The library supports Gecko based browsers like Mozilla and Firefox,
7 * Internet Explorer (5.5+ with MSXML3.0+), Konqueror, Safari and Opera
8 * @author: Copyright 2004-2007 Emmanouil Batsis, mailto: mbatsis at users full stop sourceforge full stop net
9 * ====================================================================
10 * Licence
11 * ====================================================================
12 * Sarissa is free software distributed under the GNU GPL version 2 (see <a href="gpl.txt">gpl.txt</a>) or higher,
13 * GNU LGPL version 2.1 (see <a href="lgpl.txt">lgpl.txt</a>) or higher and Apache Software License 2.0 or higher
14 * (see <a href="asl.txt">asl.txt</a>). This means you can choose one of the three and use that if you like. If
15 * you make modifications under the ASL, i would appreciate it if you submitted those.
16 * In case your copy of Sarissa does not include the license texts, you may find
17 * them online in various formats at <a href="http://www.gnu.org">http://www.gnu.org</a> and
18 * <a href="http://www.apache.org">http://www.apache.org</a>.
19 *
20 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY
21 * KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE
22 * WARRANTIES OF MERCHANTABILITY,FITNESS FOR A PARTICULAR PURPOSE
23 * AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
24 * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
25 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
26 * OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
27 * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
28 */
29 /**
30 * <p>Sarissa is a utility class. Provides "static" methods for DOMDocument,
31 * DOM Node serialization to XML strings and other utility goodies.</p>
32 * @constructor
33 * @static
34 */
35 function Sarissa(){}
36 Sarissa.VERSION = "0.9.9.3";
37 Sarissa.PARSED_OK = "Document contains no parsing errors";
38 Sarissa.PARSED_EMPTY = "Document is empty";
39 Sarissa.PARSED_UNKNOWN_ERROR = "Not well-formed or other error";
40 Sarissa.IS_ENABLED_TRANSFORM_NODE = false;
41 Sarissa.REMOTE_CALL_FLAG = "gr.abiss.sarissa.REMOTE_CALL_FLAG";
42 /** @private */
43 Sarissa._sarissa_iNsCounter = 0;
44 /** @private */
45 Sarissa._SARISSA_IEPREFIX4XSLPARAM = "";
46 /** @private */
47 Sarissa._SARISSA_HAS_DOM_IMPLEMENTATION = document.implementation && true;
48 /** @private */
49 Sarissa._SARISSA_HAS_DOM_CREATE_DOCUMENT = Sarissa._SARISSA_HAS_DOM_IMPLEMENTATION && document.implementation.createDocument;
50 /** @private */
51 Sarissa._SARISSA_HAS_DOM_FEATURE = Sarissa._SARISSA_HAS_DOM_IMPLEMENTATION && document.implementation.hasFeature;
52 /** @private */
53 Sarissa._SARISSA_IS_MOZ = Sarissa._SARISSA_HAS_DOM_CREATE_DOCUMENT && Sarissa._SARISSA_HAS_DOM_FEATURE;
54 /** @private */
55 Sarissa._SARISSA_IS_SAFARI = navigator.userAgent.toLowerCase().indexOf("safari") != -1 || navigator.userAgent.toLowerCase().indexOf("konqueror") != -1;
56 /** @private */
57 Sarissa._SARISSA_IS_SAFARI_OLD = Sarissa._SARISSA_IS_SAFARI && (parseInt((navigator.userAgent.match(/AppleWebKit\/(\d+)/)||{})[1], 10) < 420);
58 /** @private */
59 Sarissa._SARISSA_IS_IE = document.all && window.ActiveXObject && navigator.userAgent.toLowerCase().indexOf("msie") > -1 && navigator.userAgent.toLowerCase().indexOf("opera") == -1;
60 /** @private */
61 Sarissa._SARISSA_IS_OPERA = navigator.userAgent.toLowerCase().indexOf("opera") != -1;
62 if(!window.Node || !Node.ELEMENT_NODE){
63 Node = {ELEMENT_NODE: 1, ATTRIBUTE_NODE: 2, TEXT_NODE: 3, CDATA_SECTION_NODE: 4, ENTITY_REFERENCE_NODE: 5, ENTITY_NODE: 6, PROCESSING_INSTRUCTION_NODE: 7, COMMENT_NODE: 8, DOCUMENT_NODE: 9, DOCUMENT_TYPE_NODE: 10, DOCUMENT_FRAGMENT_NODE: 11, NOTATION_NODE: 12};
64 }
65
66 //This breaks for(x in o) loops in the old Safari
67 if(Sarissa._SARISSA_IS_SAFARI_OLD){
68 HTMLHtmlElement = document.createElement("html").constructor;
69 Node = HTMLElement = {};
70 HTMLElement.prototype = HTMLHtmlElement.__proto__.__proto__;
71 HTMLDocument = Document = document.constructor;
72 var x = new DOMParser();
73 XMLDocument = x.constructor;
74 Element = x.parseFromString("<Single />", "text/xml").documentElement.constructor;
75 x = null;
76 }
77 if(typeof XMLDocument == "undefined" && typeof Document !="undefined"){ XMLDocument = Document; }
78
79 // IE initialization
80 if(Sarissa._SARISSA_IS_IE){
81 // for XSLT parameter names, prefix needed by IE
82 Sarissa._SARISSA_IEPREFIX4XSLPARAM = "xsl:";
83 // used to store the most recent ProgID available out of the above
84 var _SARISSA_DOM_PROGID = "";
85 var _SARISSA_XMLHTTP_PROGID = "";
86 var _SARISSA_DOM_XMLWRITER = "";
87 /**
88 * Called when the sarissa.js file is parsed, to pick most recent
89 * ProgIDs for IE, then gets destroyed.
90 * @memberOf Sarissa
91 * @private
92 * @param idList an array of MSXML PROGIDs from which the most recent will be picked for a given object
93 * @param enabledList an array of arrays where each array has two items; the index of the PROGID for which a certain feature is enabled
94 */
95 Sarissa.pickRecentProgID = function (idList){
96 // found progID flag
97 var bFound = false, e;
98 var o2Store;
99 for(var i=0; i < idList.length && !bFound; i++){
100 try{
101 var oDoc = new ActiveXObject(idList[i]);
102 o2Store = idList[i];
103 bFound = true;
104 }catch (objException){
105 // trap; try next progID
106 e = objException;
107 }
108 }
109 if (!bFound) {
110 throw "Could not retrieve a valid progID of Class: " + idList[idList.length-1]+". (original exception: "+e+")";
111 }
112 idList = null;
113 return o2Store;
114 };
115 // pick best available MSXML progIDs
116 _SARISSA_DOM_PROGID = null;
117 _SARISSA_THREADEDDOM_PROGID = null;
118 _SARISSA_XSLTEMPLATE_PROGID = null;
119 _SARISSA_XMLHTTP_PROGID = null;
120 // commenting the condition out; we need to redefine XMLHttpRequest
121 // anyway as IE7 hardcodes it to MSXML3.0 causing version problems
122 // between different activex controls
123 //if(!window.XMLHttpRequest){
124 /**
125 * Emulate XMLHttpRequest
126 * @constructor
127 */
128 XMLHttpRequest = function() {
129 if(!_SARISSA_XMLHTTP_PROGID){
130 _SARISSA_XMLHTTP_PROGID = Sarissa.pickRecentProgID(["Msxml2.XMLHTTP.6.0", "MSXML2.XMLHTTP.3.0", "MSXML2.XMLHTTP", "Microsoft.XMLHTTP"]);
131 }
132 return new ActiveXObject(_SARISSA_XMLHTTP_PROGID);
133 };
134 //}
135 // we dont need this anymore
136 //============================================
137 // Factory methods (IE)
138 //============================================
139 // see non-IE version
140 Sarissa.getDomDocument = function(sUri, sName){
141 if(!_SARISSA_DOM_PROGID){
142 _SARISSA_DOM_PROGID = Sarissa.pickRecentProgID(["Msxml2.DOMDocument.6.0", "Msxml2.DOMDocument.3.0", "MSXML2.DOMDocument", "MSXML.DOMDocument", "Microsoft.XMLDOM"]);
143 }
144 var oDoc = new ActiveXObject(_SARISSA_DOM_PROGID);
145 // if a root tag name was provided, we need to load it in the DOM object
146 if (sName){
147 // create an artifical namespace prefix
148 // or reuse existing prefix if applicable
149 var prefix = "";
150 if(sUri){
151 if(sName.indexOf(":") > 1){
152 prefix = sName.substring(0, sName.indexOf(":"));
153 sName = sName.substring(sName.indexOf(":")+1);
154 }else{
155 prefix = "a" + (Sarissa._sarissa_iNsCounter++);
156 }
157 }
158 // use namespaces if a namespace URI exists
159 if(sUri){
160 oDoc.loadXML('<' + prefix+':'+sName + " xmlns:" + prefix + "=\"" + sUri + "\"" + " />");
161 } else {
162 oDoc.loadXML('<' + sName + " />");
163 }
164 }
165 return oDoc;
166 };
167 // see non-IE version
168 Sarissa.getParseErrorText = function (oDoc) {
169 var parseErrorText = Sarissa.PARSED_OK;
170 if(oDoc && oDoc.parseError && oDoc.parseError.errorCode && oDoc.parseError.errorCode != 0){
171 parseErrorText = "XML Parsing Error: " + oDoc.parseError.reason +
172 "\nLocation: " + oDoc.parseError.url +
173 "\nLine Number " + oDoc.parseError.line + ", Column " +
174 oDoc.parseError.linepos +
175 ":\n" + oDoc.parseError.srcText +
176 "\n";
177 for(var i = 0; i < oDoc.parseError.linepos;i++){
178 parseErrorText += "-";
179 }
180 parseErrorText += "^\n";
181 }
182 else if(oDoc.documentElement === null){
183 parseErrorText = Sarissa.PARSED_EMPTY;
184 }
185 return parseErrorText;
186 };
187 // see non-IE version
188 Sarissa.setXpathNamespaces = function(oDoc, sNsSet) {
189 oDoc.setProperty("SelectionLanguage", "XPath");
190 oDoc.setProperty("SelectionNamespaces", sNsSet);
191 };
192 /**
193 * A class that reuses the same XSLT stylesheet for multiple transforms.
194 * @constructor
195 */
196 XSLTProcessor = function(){
197 if(!_SARISSA_XSLTEMPLATE_PROGID){
198 _SARISSA_XSLTEMPLATE_PROGID = Sarissa.pickRecentProgID(["Msxml2.XSLTemplate.6.0", "MSXML2.XSLTemplate.3.0"]);
199 }
200 this.template = new ActiveXObject(_SARISSA_XSLTEMPLATE_PROGID);
201 this.processor = null;
202 };
203 /**
204 * Imports the given XSLT DOM and compiles it to a reusable transform
205 * <b>Note:</b> If the stylesheet was loaded from a URL and contains xsl:import or xsl:include elements,it will be reloaded to resolve those
206 * @argument xslDoc The XSLT DOMDocument to import
207 */
208 XSLTProcessor.prototype.importStylesheet = function(xslDoc){
209 if(!_SARISSA_THREADEDDOM_PROGID){
210 _SARISSA_THREADEDDOM_PROGID = Sarissa.pickRecentProgID(["MSXML2.FreeThreadedDOMDocument.6.0", "MSXML2.FreeThreadedDOMDocument.3.0"]);
211 }
212 xslDoc.setProperty("SelectionLanguage", "XPath");
213 xslDoc.setProperty("SelectionNamespaces", "xmlns:xsl='http://www.w3.org/1999/XSL/Transform'");
214 // convert stylesheet to free threaded
215 var converted = new ActiveXObject(_SARISSA_THREADEDDOM_PROGID);
216 // make included/imported stylesheets work if exist and xsl was originally loaded from url
217 try{
218 converted.resolveExternals = true;
219 converted.setProperty("AllowDocumentFunction", true);
220 }
221 catch(e){
222 // Ignore. "AllowDocumentFunction" is only supported in MSXML 3.0 SP4 and later.
223 }
224 if(xslDoc.url && xslDoc.selectSingleNode("//xsl:*[local-name() = 'import' or local-name() = 'include']") != null){
225 converted.async = false;
226 converted.load(xslDoc.url);
227 }
228 else {
229 converted.loadXML(xslDoc.xml);
230 }
231 converted.setProperty("SelectionNamespaces", "xmlns:xsl='http://www.w3.org/1999/XSL/Transform'");
232 var output = converted.selectSingleNode("//xsl:output");
233 //this.outputMethod = output ? output.getAttribute("method") : "html";
234 if(output) {
235 this.outputMethod = output.getAttribute("method");
236 }
237 else {
238 delete this.outputMethod;
239 }
240 this.template.stylesheet = converted;
241 this.processor = this.template.createProcessor();
242 // for getParameter and clearParameters
243 this.paramsSet = [];
244 };
245
246 /**
247 * Transform the given XML DOM and return the transformation result as a new DOM document
248 * @argument sourceDoc The XML DOMDocument to transform
249 * @return The transformation result as a DOM Document
250 */
251 XSLTProcessor.prototype.transformToDocument = function(sourceDoc){
252 // fix for bug 1549749
253 var outDoc;
254 if(_SARISSA_THREADEDDOM_PROGID){
255 this.processor.input=sourceDoc;
256 outDoc=new ActiveXObject(_SARISSA_DOM_PROGID);
257 this.processor.output=outDoc;
258 this.processor.transform();
259 return outDoc;
260 }
261 else{
262 if(!_SARISSA_DOM_XMLWRITER){
263 _SARISSA_DOM_XMLWRITER = Sarissa.pickRecentProgID(["Msxml2.MXXMLWriter.6.0", "Msxml2.MXXMLWriter.3.0", "MSXML2.MXXMLWriter", "MSXML.MXXMLWriter", "Microsoft.XMLDOM"]);
264 }
265 this.processor.input = sourceDoc;
266 outDoc = new ActiveXObject(_SARISSA_DOM_XMLWRITER);
267 this.processor.output = outDoc;
268 this.processor.transform();
269 var oDoc = new ActiveXObject(_SARISSA_DOM_PROGID);
270 oDoc.loadXML(outDoc.output+"");
271 return oDoc;
272 }
273 };
274
275 /**
276 * Transform the given XML DOM and return the transformation result as a new DOM fragment.
277 * <b>Note</b>: The xsl:output method must match the nature of the owner document (XML/HTML).
278 * @argument sourceDoc The XML DOMDocument to transform
279 * @argument ownerDoc The owner of the result fragment
280 * @return The transformation result as a DOM Document
281 */
282 XSLTProcessor.prototype.transformToFragment = function (sourceDoc, ownerDoc) {
283 this.processor.input = sourceDoc;
284 this.processor.transform();
285 var s = this.processor.output;
286 var f = ownerDoc.createDocumentFragment();
287 var container;
288 if (this.outputMethod == 'text') {
289 f.appendChild(ownerDoc.createTextNode(s));
290 } else if (ownerDoc.body && ownerDoc.body.innerHTML) {
291 container = ownerDoc.createElement('div');
292 container.innerHTML = s;
293 while (container.hasChildNodes()) {
294 f.appendChild(container.firstChild);
295 }
296 }
297 else {
298 var oDoc = new ActiveXObject(_SARISSA_DOM_PROGID);
299 if (s.substring(0, 5) == '<?xml') {
300 s = s.substring(s.indexOf('?>') + 2);
301 }
302 var xml = ''.concat('<my>', s, '</my>');
303 oDoc.loadXML(xml);
304 container = oDoc.documentElement;
305 while (container.hasChildNodes()) {
306 f.appendChild(container.firstChild);
307 }
308 }
309 return f;
310 };
311
312 /**
313 * Set global XSLT parameter of the imported stylesheet
314 * @argument nsURI The parameter namespace URI
315 * @argument name The parameter base name
316 * @argument value The new parameter value
317 */
318 XSLTProcessor.prototype.setParameter = function(nsURI, name, value){
319 // make value a zero length string if null to allow clearing
320 value = value ? value : "";
321 // nsURI is optional but cannot be null
322 if(nsURI){
323 this.processor.addParameter(name, value, nsURI);
324 }else{
325 this.processor.addParameter(name, value);
326 }
327 // update updated params for getParameter
328 nsURI = "" + (nsURI || "");
329 if(!this.paramsSet[nsURI]){
330 this.paramsSet[nsURI] = [];
331 }
332 this.paramsSet[nsURI][name] = value;
333 };
334 /**
335 * Gets a parameter if previously set by setParameter. Returns null
336 * otherwise
337 * @argument name The parameter base name
338 * @argument value The new parameter value
339 * @return The parameter value if reviously set by setParameter, null otherwise
340 */
341 XSLTProcessor.prototype.getParameter = function(nsURI, name){
342 nsURI = "" + (nsURI || "");
343 if(this.paramsSet[nsURI] && this.paramsSet[nsURI][name]){
344 return this.paramsSet[nsURI][name];
345 }else{
346 return null;
347 }
348 };
349
350 /**
351 * Clear parameters (set them to default values as defined in the stylesheet itself)
352 */
353 XSLTProcessor.prototype.clearParameters = function(){
354 for(var nsURI in this.paramsSet){
355 for(var name in this.paramsSet[nsURI]){
356 if(nsURI!=""){
357 this.processor.addParameter(name, "", nsURI);
358 }else{
359 this.processor.addParameter(name, "");
360 }
361 }
362 }
363 this.paramsSet = [];
364 };
365 }else{ /* end IE initialization, try to deal with real browsers now ;-) */
366 if(Sarissa._SARISSA_HAS_DOM_CREATE_DOCUMENT){
367 /**
368 * <p>Ensures the document was loaded correctly, otherwise sets the
369 * parseError to -1 to indicate something went wrong. Internal use</p>
370 * @private
371 */
372 Sarissa.__handleLoad__ = function(oDoc){
373 Sarissa.__setReadyState__(oDoc, 4);
374 };
375 /**
376 * <p>Attached by an event handler to the load event. Internal use.</p>
377 * @private
378 */
379 _sarissa_XMLDocument_onload = function(){
380 Sarissa.__handleLoad__(this);
381 };
382 /**
383 * <p>Sets the readyState property of the given DOM Document object.
384 * Internal use.</p>
385 * @memberOf Sarissa
386 * @private
387 * @argument oDoc the DOM Document object to fire the
388 * readystatechange event
389 * @argument iReadyState the number to change the readystate property to
390 */
391 Sarissa.__setReadyState__ = function(oDoc, iReadyState){
392 oDoc.readyState = iReadyState;
393 oDoc.readystate = iReadyState;
394 if (oDoc.onreadystatechange != null && typeof oDoc.onreadystatechange == "function") {
395 oDoc.onreadystatechange();
396 }
397 };
398
399 Sarissa.getDomDocument = function(sUri, sName){
400 var oDoc = document.implementation.createDocument(sUri?sUri:null, sName?sName:null, null);
401 if(!oDoc.onreadystatechange){
402
403 /**
404 * <p>Emulate IE's onreadystatechange attribute</p>
405 */
406 oDoc.onreadystatechange = null;
407 }
408 if(!oDoc.readyState){
409 /**
410 * <p>Emulates IE's readyState property, which always gives an integer from 0 to 4:</p>
411 * <ul><li>1 == LOADING,</li>
412 * <li>2 == LOADED,</li>
413 * <li>3 == INTERACTIVE,</li>
414 * <li>4 == COMPLETED</li></ul>
415 */
416 oDoc.readyState = 0;
417 }
418 oDoc.addEventListener("load", _sarissa_XMLDocument_onload, false);
419 return oDoc;
420 };
421 if(window.XMLDocument){
422 // do nothing
423 }// TODO: check if the new document has content before trying to copynodes, check for error handling in DOM 3 LS
424 else if(Sarissa._SARISSA_HAS_DOM_FEATURE && window.Document && !Document.prototype.load && document.implementation.hasFeature('LS', '3.0')){
425 //Opera 9 may get the XPath branch which gives creates XMLDocument, therefore it doesn't reach here which is good
426 /**
427 * <p>Factory method to obtain a new DOM Document object</p>
428 * @memberOf Sarissa
429 * @argument sUri the namespace of the root node (if any)
430 * @argument sUri the local name of the root node (if any)
431 * @returns a new DOM Document
432 */
433 Sarissa.getDomDocument = function(sUri, sName){
434 var oDoc = document.implementation.createDocument(sUri?sUri:null, sName?sName:null, null);
435 return oDoc;
436 };
437 }
438 else {
439 Sarissa.getDomDocument = function(sUri, sName){
440 var oDoc = document.implementation.createDocument(sUri?sUri:null, sName?sName:null, null);
441 // looks like safari does not create the root element for some unknown reason
442 if(oDoc && (sUri || sName) && !oDoc.documentElement){
443 oDoc.appendChild(oDoc.createElementNS(sUri, sName));
444 }
445 return oDoc;
446 };
447 }
448 }//if(Sarissa._SARISSA_HAS_DOM_CREATE_DOCUMENT)
449 }
450 //==========================================
451 // Common stuff
452 //==========================================
453 if(!window.DOMParser){
454 if(Sarissa._SARISSA_IS_SAFARI){
455 /*
456 * DOMParser is a utility class, used to construct DOMDocuments from XML strings
457 * @constructor
458 */
459 DOMParser = function() { };
460 /**
461 * Construct a new DOM Document from the given XMLstring
462 * @param sXml the given XML string
463 * @param contentType the content type of the document the given string represents (one of text/xml, application/xml, application/xhtml+xml).
464 * @return a new DOM Document from the given XML string
465 */
466 DOMParser.prototype.parseFromString = function(sXml, contentType){
467 var xmlhttp = new XMLHttpRequest();
468 xmlhttp.open("GET", "data:text/xml;charset=utf-8," + encodeURIComponent(sXml), false);
469 xmlhttp.send(null);
470 return xmlhttp.responseXML;
471 };
472 }else if(Sarissa.getDomDocument && Sarissa.getDomDocument() && Sarissa.getDomDocument(null, "bar").xml){
473 DOMParser = function() { };
474 DOMParser.prototype.parseFromString = function(sXml, contentType){
475 var doc = Sarissa.getDomDocument();
476 doc.loadXML(sXml);
477 return doc;
478 };
479 }
480 }
481
482 if((typeof(document.importNode) == "undefined") && Sarissa._SARISSA_IS_IE){
483 try{
484 /**
485 * Implementation of importNode for the context window document in IE.
486 * If <code>oNode</code> is a TextNode, <code>bChildren</code> is ignored.
487 * @param oNode the Node to import
488 * @param bChildren whether to include the children of oNode
489 * @returns the imported node for further use
490 */
491 document.importNode = function(oNode, bChildren){
492 var tmp;
493 if (oNode.nodeName=='#text') {
494 return document.createTextNode(oNode.data);
495 }
496 else {
497 if(oNode.nodeName == "tbody" || oNode.nodeName == "tr"){
498 tmp = document.createElement("table");
499 }
500 else if(oNode.nodeName == "td"){
501 tmp = document.createElement("tr");
502 }
503 else if(oNode.nodeName == "option"){
504 tmp = document.createElement("select");
505 }
506 else{
507 tmp = document.createElement("div");
508 }
509 if(bChildren){
510 tmp.innerHTML = oNode.xml ? oNode.xml : oNode.outerHTML;
511 }else{
512 tmp.innerHTML = oNode.xml ? oNode.cloneNode(false).xml : oNode.cloneNode(false).outerHTML;
513 }
514 return tmp.getElementsByTagName("*")[0];
515 }
516 };
517 }catch(e){ }
518 }
519 if(!Sarissa.getParseErrorText){
520 /**
521 * <p>Returns a human readable description of the parsing error. Usefull
522 * for debugging. Tip: append the returned error string in a &lt;pre&gt;
523 * element if you want to render it.</p>
524 * <p>Many thanks to Christian Stocker for the initial patch.</p>
525 * @memberOf Sarissa
526 * @argument oDoc The target DOM document
527 * @returns The parsing error description of the target Document in
528 * human readable form (preformated text)
529 */
530 Sarissa.getParseErrorText = function (oDoc){
531 var parseErrorText = Sarissa.PARSED_OK;
532 if(!oDoc.documentElement){
533 parseErrorText = Sarissa.PARSED_EMPTY;
534 } else if(oDoc.documentElement.tagName == "parsererror"){
535 parseErrorText = oDoc.documentElement.firstChild.data;
536 parseErrorText += "\n" + oDoc.documentElement.firstChild.nextSibling.firstChild.data;
537 } else if(oDoc.getElementsByTagName("parsererror").length > 0){
538 var parsererror = oDoc.getElementsByTagName("parsererror")[0];
539 parseErrorText = Sarissa.getText(parsererror, true)+"\n";
540 } else if(oDoc.parseError && oDoc.parseError.errorCode != 0){
541 parseErrorText = Sarissa.PARSED_UNKNOWN_ERROR;
542 }
543 return parseErrorText;
544 };
545 }
546 /**
547 * Get a string with the concatenated values of all string nodes under the given node
548 * @memberOf Sarissa
549 * @argument oNode the given DOM node
550 * @argument deep whether to recursively scan the children nodes of the given node for text as well. Default is <code>false</code>
551 */
552 Sarissa.getText = function(oNode, deep){
553 var s = "";
554 var nodes = oNode.childNodes;
555 for(var i=0; i < nodes.length; i++){
556 var node = nodes[i];
557 var nodeType = node.nodeType;
558 if(nodeType == Node.TEXT_NODE || nodeType == Node.CDATA_SECTION_NODE){
559 s += node.data;
560 } else if(deep === true && (nodeType == Node.ELEMENT_NODE || nodeType == Node.DOCUMENT_NODE || nodeType == Node.DOCUMENT_FRAGMENT_NODE)){
561 s += Sarissa.getText(node, true);
562 }
563 }
564 return s;
565 };
566 if(!window.XMLSerializer && Sarissa.getDomDocument && Sarissa.getDomDocument("","foo", null).xml){
567 /**
568 * Utility class to serialize DOM Node objects to XML strings
569 * @constructor
570 */
571 XMLSerializer = function(){};
572 /**
573 * Serialize the given DOM Node to an XML string
574 * @param oNode the DOM Node to serialize
575 */
576 XMLSerializer.prototype.serializeToString = function(oNode) {
577 return oNode.xml;
578 };
579 }
580
581 /**
582 * Strips tags from the given markup string. If the given string is
583 * <code>undefined</code>, <code>null</code> or empty, it is returned as is.
584 * @memberOf Sarissa
585 */
586 Sarissa.stripTags = function (s) {
587 return s?s.replace(/<[^>]+>/g,""):s;
588 };
589 /**
590 * <p>Deletes all child nodes of the given node</p>
591 * @memberOf Sarissa
592 * @argument oNode the Node to empty
593 */
594 Sarissa.clearChildNodes = function(oNode) {
595 // need to check for firstChild due to opera 8 bug with hasChildNodes
596 while(oNode.firstChild) {
597 oNode.removeChild(oNode.firstChild);
598 }
599 };
600 /**
601 * <p> Copies the childNodes of nodeFrom to nodeTo</p>
602 * <p> <b>Note:</b> The second object's original content is deleted before
603 * the copy operation, unless you supply a true third parameter</p>
604 * @memberOf Sarissa
605 * @argument nodeFrom the Node to copy the childNodes from
606 * @argument nodeTo the Node to copy the childNodes to
607 * @argument bPreserveExisting whether to preserve the original content of nodeTo, default is false
608 */
609 Sarissa.copyChildNodes = function(nodeFrom, nodeTo, bPreserveExisting) {
610 if(Sarissa._SARISSA_IS_SAFARI && nodeTo.nodeType == Node.DOCUMENT_NODE){ // SAFARI_OLD ??
611 nodeTo = nodeTo.documentElement; //Apparently there's a bug in safari where you can't appendChild to a document node
612 }
613
614 if((!nodeFrom) || (!nodeTo)){
615 throw "Both source and destination nodes must be provided";
616 }
617 if(!bPreserveExisting){
618 Sarissa.clearChildNodes(nodeTo);
619 }
620 var ownerDoc = nodeTo.nodeType == Node.DOCUMENT_NODE ? nodeTo : nodeTo.ownerDocument;
621 var nodes = nodeFrom.childNodes;
622 var i;
623 if(typeof(ownerDoc.importNode) != "undefined") {
624 for(i=0;i < nodes.length;i++) {
625 nodeTo.appendChild(ownerDoc.importNode(nodes[i], true));
626 }
627 } else {
628 for(i=0;i < nodes.length;i++) {
629 nodeTo.appendChild(nodes[i].cloneNode(true));
630 }
631 }
632 };
633
634 /**
635 * <p> Moves the childNodes of nodeFrom to nodeTo</p>
636 * <p> <b>Note:</b> The second object's original content is deleted before
637 * the move operation, unless you supply a true third parameter</p>
638 * @memberOf Sarissa
639 * @argument nodeFrom the Node to copy the childNodes from
640 * @argument nodeTo the Node to copy the childNodes to
641 * @argument bPreserveExisting whether to preserve the original content of nodeTo, default is
642 */
643 Sarissa.moveChildNodes = function(nodeFrom, nodeTo, bPreserveExisting) {
644 if((!nodeFrom) || (!nodeTo)){
645 throw "Both source and destination nodes must be provided";
646 }
647 if(!bPreserveExisting){
648 Sarissa.clearChildNodes(nodeTo);
649 }
650 var nodes = nodeFrom.childNodes;
651 // if within the same doc, just move, else copy and delete
652 if(nodeFrom.ownerDocument == nodeTo.ownerDocument){
653 while(nodeFrom.firstChild){
654 nodeTo.appendChild(nodeFrom.firstChild);
655 }
656 } else {
657 var ownerDoc = nodeTo.nodeType == Node.DOCUMENT_NODE ? nodeTo : nodeTo.ownerDocument;
658 var i;
659 if(typeof(ownerDoc.importNode) != "undefined") {
660 for(i=0;i < nodes.length;i++) {
661 nodeTo.appendChild(ownerDoc.importNode(nodes[i], true));
662 }
663 }else{
664 for(i=0;i < nodes.length;i++) {
665 nodeTo.appendChild(nodes[i].cloneNode(true));
666 }
667 }
668 Sarissa.clearChildNodes(nodeFrom);
669 }
670 };
671
672 /**
673 * <p>Serialize any <strong>non</strong> DOM object to an XML string. All properties are serialized using the property name
674 * as the XML element name. Array elements are rendered as <code>array-item</code> elements,
675 * using their index/key as the value of the <code>key</code> attribute.</p>
676 * @memberOf Sarissa
677 * @argument anyObject the object to serialize
678 * @argument objectName a name for that object
679 * @return the XML serialization of the given object as a string
680 */
681 Sarissa.xmlize = function(anyObject, objectName, indentSpace){
682 indentSpace = indentSpace?indentSpace:'';
683 var s = indentSpace + '<' + objectName + '>';
684 var isLeaf = false;
685 if(!(anyObject instanceof Object) || anyObject instanceof Number || anyObject instanceof String || anyObject instanceof Boolean || anyObject instanceof Date){
686 s += Sarissa.escape(""+anyObject);
687 isLeaf = true;
688 }else{
689 s += "\n";
690 var isArrayItem = anyObject instanceof Array;
691 for(var name in anyObject){
692 s += Sarissa.xmlize(anyObject[name], (isArrayItem?"array-item key=\""+name+"\"":name), indentSpace + " ");
693 }
694 s += indentSpace;
695 }
696 return (s += (objectName.indexOf(' ')!=-1?"</array-item>\n":"</" + objectName + ">\n"));
697 };
698
699 /**
700 * Escape the given string chacters that correspond to the five predefined XML entities
701 * @memberOf Sarissa
702 * @param sXml the string to escape
703 */
704 Sarissa.escape = function(sXml){
705 return sXml.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/"/g, "&quot;").replace(/'/g, "&apos;");
706 };
707
708 /**
709 * Unescape the given string. This turns the occurences of the predefined XML
710 * entities to become the characters they represent correspond to the five predefined XML entities
711 * @memberOf Sarissa
712 * @param sXml the string to unescape
713 */
714 Sarissa.unescape = function(sXml){
715 return sXml.replace(/&apos;/g,"'").replace(/&quot;/g,"\"").replace(/&gt;/g,">").replace(/&lt;/g,"<").replace(/&amp;/g,"&");
716 };
717
718 /** @private */
719 Sarissa.updateCursor = function(oTargetElement, sValue) {
720 if(oTargetElement && oTargetElement.style && oTargetElement.style.cursor != undefined ){
721 oTargetElement.style.cursor = sValue;
722 }
723 };
724
725 /**
726 * Asynchronously update an element with response of a GET request on the given URL. Passing a configured XSLT
727 * processor will result in transforming and updating oNode before using it to update oTargetElement.
728 * You can also pass a callback function to be executed when the update is finished. The function will be called as
729 * <code>functionName(oNode, oTargetElement);</code>
730 * @memberOf Sarissa
731 * @param sFromUrl the URL to make the request to
732 * @param oTargetElement the element to update
733 * @param xsltproc (optional) the transformer to use on the returned
734 * content before updating the target element with it
735 * @param callback (optional) a Function object to execute once the update is finished successfuly, called as <code>callback(sFromUrl, oTargetElement)</code>.
736 * In case an exception is thrown during execution, the callback is called as called as <code>callback(sFromUrl, oTargetElement, oException)</code>
737 * @param skipCache (optional) whether to skip any cache
738 */
739 Sarissa.updateContentFromURI = function(sFromUrl, oTargetElement, xsltproc, callback, skipCache) {
740 try{
741 Sarissa.updateCursor(oTargetElement, "wait");
742 var xmlhttp = new XMLHttpRequest();
743 xmlhttp.open("GET", sFromUrl, true);
744 xmlhttp.onreadystatechange = function() {
745 if (xmlhttp.readyState == 4) {
746 try{
747 var oDomDoc = xmlhttp.responseXML;
748 if(oDomDoc && Sarissa.getParseErrorText(oDomDoc) == Sarissa.PARSED_OK){
749 Sarissa.updateContentFromNode(xmlhttp.responseXML, oTargetElement, xsltproc);
750 callback(sFromUrl, oTargetElement);
751 }
752 else{
753 throw Sarissa.getParseErrorText(oDomDoc);
754 }
755 }
756 catch(e){
757 if(callback){
758 callback(sFromUrl, oTargetElement, e);
759 }
760 else{
761 throw e;
762 }
763 }
764 }
765 };
766 if (skipCache) {
767 var oldage = "Sat, 1 Jan 2000 00:00:00 GMT";
768 xmlhttp.setRequestHeader("If-Modified-Since", oldage);
769 }
770 xmlhttp.send("");
771 }
772 catch(e){
773 Sarissa.updateCursor(oTargetElement, "auto");
774 if(callback){
775 callback(sFromUrl, oTargetElement, e);
776 }
777 else{
778 throw e;
779 }
780 }
781 };
782
783 /**
784 * Update an element's content with the given DOM node. Passing a configured XSLT
785 * processor will result in transforming and updating oNode before using it to update oTargetElement.
786 * You can also pass a callback function to be executed when the update is finished. The function will be called as
787 * <code>functionName(oNode, oTargetElement);</code>
788 * @memberOf Sarissa
789 * @param oNode the URL to make the request to
790 * @param oTargetElement the element to update
791 * @param xsltproc (optional) the transformer to use on the given
792 * DOM node before updating the target element with it
793 */
794 Sarissa.updateContentFromNode = function(oNode, oTargetElement, xsltproc) {
795 try {
796 Sarissa.updateCursor(oTargetElement, "wait");
797 Sarissa.clearChildNodes(oTargetElement);
798 // check for parsing errors
799 var ownerDoc = oNode.nodeType == Node.DOCUMENT_NODE?oNode:oNode.ownerDocument;
800 if(ownerDoc.parseError && ownerDoc.parseError.errorCode != 0) {
801 var pre = document.createElement("pre");
802 pre.appendChild(document.createTextNode(Sarissa.getParseErrorText(ownerDoc)));
803 oTargetElement.appendChild(pre);
804 }
805 else {
806 // transform if appropriate
807 if(xsltproc) {
808 oNode = xsltproc.transformToDocument(oNode);
809 }
810 // be smart, maybe the user wants to display the source instead
811 if(oTargetElement.tagName.toLowerCase() == "textarea" || oTargetElement.tagName.toLowerCase() == "input") {
812 oTargetElement.value = new XMLSerializer().serializeToString(oNode);
813 }
814 else {
815 // ok that was not smart; it was paranoid. Keep up the good work by trying to use DOM instead of innerHTML
816 if(oNode.nodeType == Node.DOCUMENT_NODE || oNode.ownerDocument.documentElement == oNode) {
817 oTargetElement.innerHTML = new XMLSerializer().serializeToString(oNode);
818 }
819 else{
820 oTargetElement.appendChild(oTargetElement.ownerDocument.importNode(oNode, true));
821 }
822 }
823 }
824 }
825 catch(e) {
826 throw e;
827 }
828 finally{
829 Sarissa.updateCursor(oTargetElement, "auto");
830 }
831 };
832
833
834 /**
835 * Creates an HTTP URL query string from the given HTML form data
836 * @memberOf Sarissa
837 */
838 Sarissa.formToQueryString = function(oForm){
839 var qs = "";
840 for(var i = 0;i < oForm.elements.length;i++) {
841 var oField = oForm.elements[i];
842 var sFieldName = oField.getAttribute("name") ? oField.getAttribute("name") : oField.getAttribute("id");
843 // ensure we got a proper name/id and that the field is not disabled
844 if(sFieldName &&
845 ((!oField.disabled) || oField.type == "hidden")) {
846 switch(oField.type) {
847 case "hidden":
848 case "text":
849 case "textarea":
850 case "password":
851 qs += sFieldName + "=" + encodeURIComponent(oField.value) + "&";
852 break;
853 case "select-one":
854 qs += sFieldName + "=" + encodeURIComponent(oField.options[oField.selectedIndex].value) + "&";
855 break;
856 case "select-multiple":
857 for (var j = 0; j < oField.length; j++) {
858 var optElem = oField.options[j];
859 if (optElem.selected === true) {
860 qs += sFieldName + "[]" + "=" + encodeURIComponent(optElem.value) + "&";
861 }
862 }
863 break;
864 case "checkbox":
865 case "radio":
866 if(oField.checked) {
867 qs += sFieldName + "=" + encodeURIComponent(oField.value) + "&";
868 }
869 break;
870 }
871 }
872 }
873 // return after removing last '&'
874 return qs.substr(0, qs.length - 1);
875 };
876
877
878 /**
879 * Asynchronously update an element with response of an XMLHttpRequest-based emulation of a form submission. <p>The form <code>action</code> and
880 * <code>method</code> attributess will be followed. Passing a configured XSLT processor will result in
881 * transforming and updating the server response before using it to update the target element.
882 * You can also pass a callback function to be executed when the update is finished. The function will be called as
883 * <code>functionName(oNode, oTargetElement);</code></p>
884 * <p>Here is an example of using this in a form element:</p>
885 * <pre name="code" class="xml">
886 * &lt;div id="targetId"&gt; this content will be updated&lt;/div&gt;
887 * &lt;form action="/my/form/handler" method="post"
888 * onbeforesubmit="return Sarissa.updateContentFromForm(this, document.getElementById('targetId'));"&gt;<pre>
889 * <p>If JavaScript is supported, the form will not be submitted. Instead, Sarissa will
890 * scan the form and make an appropriate AJAX request, also adding a parameter
891 * to signal to the server that this is an AJAX call. The parameter is
892 * constructed as <code>Sarissa.REMOTE_CALL_FLAG = "=true"</code> so you can change the name in your webpage
893 * simply by assigning another value to Sarissa.REMOTE_CALL_FLAG. If JavaScript is not supported
894 * the form will be submitted normally.
895 * @memberOf Sarissa
896 * @param oForm the form submition to emulate
897 * @param oTargetElement the element to update
898 * @param xsltproc (optional) the transformer to use on the returned
899 * content before updating the target element with it
900 * @param callback (optional) a Function object to execute once the update is finished successfuly, called as <code>callback(oNode, oTargetElement)</code>.
901 * In case an exception occurs during excecution and a callback function was provided, the exception is cought and the callback is called as
902 * <code>callback(oForm, oTargetElement, exception)</code>
903 */
904 Sarissa.updateContentFromForm = function(oForm, oTargetElement, xsltproc, callback) {
905 try{
906 Sarissa.updateCursor(oTargetElement, "wait");
907 // build parameters from form fields
908 var params = Sarissa.formToQueryString(oForm) + "&" + Sarissa.REMOTE_CALL_FLAG + "=true";
909 var xmlhttp = new XMLHttpRequest();
910 var bUseGet = oForm.getAttribute("method") && oForm.getAttribute("method").toLowerCase() == "get";
911 if(bUseGet) {
912 xmlhttp.open("GET", oForm.getAttribute("action")+"?"+params, true);
913 }
914 else{
915 xmlhttp.open('POST', oForm.getAttribute("action"), true);
916 xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
917 xmlhttp.setRequestHeader("Content-length", params.length);
918 xmlhttp.setRequestHeader("Connection", "close");
919 }
920 xmlhttp.onreadystatechange = function() {
921 try{
922 if (xmlhttp.readyState == 4) {
923 var oDomDoc = xmlhttp.responseXML;
924 if(oDomDoc && Sarissa.getParseErrorText(oDomDoc) == Sarissa.PARSED_OK){
925 Sarissa.updateContentFromNode(xmlhttp.responseXML, oTargetElement, xsltproc);
926 callback(oForm, oTargetElement);
927 }
928 else{
929 throw Sarissa.getParseErrorText(oDomDoc);
930 }
931 }
932 }
933 catch(e){
934 if(callback){
935 callback(oForm, oTargetElement, e);
936 }
937 else{
938 throw e;
939 }
940 }
941 };
942 xmlhttp.send(bUseGet?"":params);
943 }
944 catch(e){
945 Sarissa.updateCursor(oTargetElement, "auto");
946 if(callback){
947 callback(oForm, oTargetElement, e);
948 }
949 else{
950 throw e;
951 }
952 }
953 return false;
954 };
955
956 // EOF