1 /* Licensed to the Apache Software Foundation (ASF) under one or more
  2  * contributor license agreements.  See the NOTICE file distributed with
  3  * this work for additional information regarding copyright ownership.
  4  * The ASF licenses this file to you under the Apache License, Version 2.0
  5  * (the "License"); you may not use this file except in compliance with
  6  * the License.  You may obtain a copy of the License at
  7  *
  8  *      http://www.apache.org/licenses/LICENSE-2.0
  9  *
 10  * Unless required by applicable law or agreed to in writing, software
 11  * distributed under the License is distributed on an "AS IS" BASIS,©
 12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 13  * See the License for the specific language governing permissions and
 14  * limitations under the License.
 15  */
 16 
 17 /**
 18  * @class
 19  * @name _Dom
 20  * @memberOf myfaces._impl._util
 21  * @extends myfaces._impl.core._Runtime
 22  * @description Object singleton collection of dom helper routines
 23  * (which in later incarnations will
 24  * get browser specific speed optimizations)
 25  *
 26  * Since we have to be as tight as possible
 27  * we will focus with our dom routines to only
 28  * the parts which our impl uses.
 29  * A jquery like query API would be nice
 30  * but this would increase up our codebase significantly
 31  *
 32  * <p>This class provides the proper fallbacks for ie8- and Firefox 3.6-</p>
 33  */
 34 _MF_SINGLTN(_PFX_UTIL + "_Dom", Object, /** @lends myfaces._impl._util._Dom.prototype */ {
 35 
 36     /*table elements which are used in various parts */
 37     TABLE_ELEMS:  {
 38         "thead": 1,
 39         "tbody": 1,
 40         "tr": 1,
 41         "th": 1,
 42         "td": 1,
 43         "tfoot" : 1
 44     },
 45 
 46     _Lang:  myfaces._impl._util._Lang,
 47     _RT:    myfaces._impl.core._Runtime,
 48     _dummyPlaceHolder:null,
 49 
 50     /**
 51      * standard constructor
 52      */
 53     constructor_: function() {
 54     },
 55 
 56     runCss: function(item/*, xmlData*/) {
 57 
 58         var  UDEF = "undefined",
 59                 _RT = this._RT,
 60                 _Lang = this._Lang,
 61                 applyStyle = function(item, style) {
 62                     var newSS = document.createElement("style");
 63 
 64                     newSS.setAttribute("rel", item.getAttribute("rel") || "stylesheet");
 65                     newSS.setAttribute("type", item.getAttribute("type") || "text/css");
 66                     document.getElementsByTagName("head")[0].appendChild(newSS);
 67                     //ie merrily again goes its own way
 68                     if (window.attachEvent && !_RT.isOpera && UDEF != typeof newSS.styleSheet && UDEF != newSS.styleSheet.cssText) newSS.styleSheet.cssText = style;
 69                     else newSS.appendChild(document.createTextNode(style));
 70                 },
 71 
 72                 execCss = function(item) {
 73                     var equalsIgnoreCase = _Lang.equalsIgnoreCase;
 74                     var tagName = item.tagName;
 75                     if (tagName && equalsIgnoreCase(tagName, "link") && equalsIgnoreCase(item.getAttribute("type"), "text/css")) {
 76                         applyStyle(item, "@import url('" + item.getAttribute("href") + "');");
 77                     } else if (tagName && equalsIgnoreCase(tagName, "style") && equalsIgnoreCase(item.getAttribute("type"), "text/css")) {
 78                         var innerText = [];
 79                         //compliant browsers know child nodes
 80                         var childNodes = item.childNodes;
 81                         if (childNodes) {
 82                             var len = childNodes.length;
 83                             for (var cnt = 0; cnt < len; cnt++) {
 84                                 innerText.push(childNodes[cnt].innerHTML || childNodes[cnt].data);
 85                             }
 86                             //non compliant ones innerHTML
 87                         } else if (item.innerHTML) {
 88                             innerText.push(item.innerHTML);
 89                         }
 90 
 91                         applyStyle(item, innerText.join(""));
 92                     }
 93                 };
 94 
 95         try {
 96             var scriptElements = this.findByTagNames(item, {"link":1,"style":1}, true);
 97             if (scriptElements == null) return;
 98             for (var cnt = 0; cnt < scriptElements.length; cnt++) {
 99                 execCss(scriptElements[cnt]);
100             }
101 
102         } finally {
103             //the usual ie6 fix code
104             //the IE6 garbage collector is broken
105             //nulling closures helps somewhat to reduce
106             //mem leaks, which are impossible to avoid
107             //at this browser
108             execCss = null;
109             applyStyle = null;
110         }
111     },
112 
113 
114     /**
115      * Run through the given Html item and execute the inline scripts
116      * (IE doesn't do this by itself)
117      * @param {Node} item
118      */
119     runScripts: function(item, xmlData) {
120         var _Lang = this._Lang,
121             _RT = this._RT,
122             finalScripts = [],
123             execScrpt = function(item) {
124                 var tagName = item.tagName;
125                 var type = item.type || "";
126                 //script type javascript has to be handled by eval, other types
127                 //must be handled by the browser
128                 if (tagName && _Lang.equalsIgnoreCase(tagName, "script") &&
129                         (type === "" ||
130                         _Lang.equalsIgnoreCase(type,"text/javascript") ||
131                         _Lang.equalsIgnoreCase(type,"javascript") ||
132                         _Lang.equalsIgnoreCase(type,"text/ecmascript") ||
133                         _Lang.equalsIgnoreCase(type,"ecmascript"))) {
134 
135                     var src = item.getAttribute('src');
136                     if ('undefined' != typeof src
137                             && null != src
138                             && src.length > 0
139                             ) {
140                         //we have to move this into an inner if because chrome otherwise chokes
141                         //due to changing the and order instead of relying on left to right
142                         //if jsf.js is already registered we do not replace it anymore
143                         if ((src.indexOf("ln=scripts") == -1 && src.indexOf("ln=javax.faces") == -1) || (src.indexOf("/jsf.js") == -1
144                                 && src.indexOf("/jsf-uncompressed.js") == -1)) {
145                             if (finalScripts.length) {
146                                 //script source means we have to eval the existing
147                                 //scripts before running the include
148                                 _RT.globalEval(finalScripts.join("\n"));
149 
150                                 finalScripts = [];
151                             }
152                             _RT.loadScriptEval(src, item.getAttribute('type'), false, "UTF-8", false);
153                         }
154 
155                     } else {
156                         // embedded script auto eval
157                         var test = (!xmlData) ? item.text : _Lang.serializeChilds(item);
158                         var go = true;
159                         while (go) {
160                             go = false;
161                             if (test.substring(0, 1) == " ") {
162                                 test = test.substring(1);
163                                 go = true;
164                             }
165                             if (test.substring(0, 4) == "<!--") {
166                                 test = test.substring(4);
167                                 go = true;
168                             }
169                             if (test.substring(0, 11) == "//<![CDATA[") {
170                                 test = test.substring(11);
171                                 go = true;
172                             }
173                         }
174                         // we have to run the script under a global context
175                         //we store the script for less calls to eval
176                         finalScripts.push(test);
177 
178                     }
179                 }
180             };
181         try {
182             var scriptElements = this.findByTagName(item, "script", true);
183             if (scriptElements == null) return;
184             for (var cnt = 0; cnt < scriptElements.length; cnt++) {
185                 execScrpt(scriptElements[cnt]);
186             }
187             if (finalScripts.length) {
188                 _RT.globalEval(finalScripts.join("\n"));
189             }
190         } catch (e) {
191             //we are now in accordance with the rest of the system of showing errors only in development mode
192             //the default error output is alert we always can override it with
193             //window.myfaces = window.myfaces || {};
194             //myfaces.config =  myfaces.config || {};
195             //myfaces.config.defaultErrorOutput = console.error;
196             if(jsf.getProjectStage() === "Development") {
197                 var defaultErrorOutput = myfaces._impl.core._Runtime.getGlobalConfig("defaultErrorOutput", alert);
198                 defaultErrorOutput("Error in evaluated javascript:"+ (e.message || e.description || e));
199             }
200         } finally {
201             //the usual ie6 fix code
202             //the IE6 garbage collector is broken
203             //nulling closures helps somewhat to reduce
204             //mem leaks, which are impossible to avoid
205             //at this browser
206             execScrpt = null;
207         }
208     },
209 
210 
211     /**
212      * determines to fetch a node
213      * from its id or name, the name case
214      * only works if the element is unique in its name
215      * @param {String} elem
216      */
217     byIdOrName: function(elem) {
218         if (!elem) return null;
219         if (!this._Lang.isString(elem)) return elem;
220 
221         var ret = this.byId(elem);
222         if (ret) return ret;
223         //we try the unique name fallback
224         var items = document.getElementsByName(elem);
225         return ((items.length == 1) ? items[0] : null);
226     },
227 
228     /**
229      * node id or name, determines the valid form identifier of a node
230      * depending on its uniqueness
231      *
232      * Usually the id is chosen for an elem, but if the id does not
233      * exist we try a name fallback. If the passed element has a unique
234      * name we can use that one as subsequent identifier.
235      *
236      *
237      * @param {String} elem
238      */
239     nodeIdOrName: function(elem) {
240         if (elem) {
241             //just to make sure that the pas
242 
243             elem = this.byId(elem);
244             if (!elem) return null;
245             //detached element handling, we also store the element name
246             //to get a fallback option in case the identifier is not determinable
247             // anymore, in case of a framework induced detachment the element.name should
248             // be shared if the identifier is not determinable anymore
249             //the downside of this method is the element name must be unique
250             //which in case of jsf it is
251             var elementId = elem.id || elem.name;
252             if ((elem.id == null || elem.id == '') && elem.name) {
253                 elementId = elem.name;
254 
255                 //last check for uniqueness
256                 if (document.getElementsByName(elementId).length > 1) {
257                     //no unique element name so we need to perform
258                     //a return null to let the caller deal with this issue
259                     return null;
260                 }
261             }
262             return elementId;
263         }
264         return null;
265     },
266 
267     deleteItems: function(items) {
268         if (! items || ! items.length) return;
269         for (var cnt = 0; cnt < items.length; cnt++) {
270             this.deleteItem(items[cnt]);
271         }
272     },
273 
274     /**
275      * Simple delete on an existing item
276      */
277     deleteItem: function(itemIdToReplace) {
278         var item = this.byId(itemIdToReplace);
279         if (!item) {
280             throw this._Lang.makeException(new Error(),null, null, this._nameSpace, "deleteItem",  "_Dom.deleteItem  Unknown Html-Component-ID: " + itemIdToReplace);
281         }
282 
283         this._removeNode(item, false);
284     },
285 
286     /**
287      * creates a node upon a given node name
288      * @param nodeName {String} the node name to be created
289      * @param attrs {Array} a set of attributes to be set
290      */
291     createElement: function(nodeName, attrs) {
292         var ret = document.createElement(nodeName);
293         if (attrs) {
294             for (var key in attrs) {
295                 if(!attrs.hasOwnProperty(key)) continue;
296                 this.setAttribute(ret, key, attrs[key]);
297             }
298         }
299         return ret;
300     },
301 
302     /**
303      * Checks whether the browser is dom compliant.
304      * Dom compliant means that it performs the basic dom operations safely
305      * without leaking and also is able to perform a native setAttribute
306      * operation without freaking out
307      *
308      *
309      * Not dom compliant browsers are all microsoft browsers in quirks mode
310      * and ie6 and ie7 to some degree in standards mode
311      * and pretty much every browser who cannot create ranges
312      * (older mobile browsers etc...)
313      *
314      * We dont do a full browser detection here because it probably is safer
315      * to test for existing features to make an assumption about the
316      * browsers capabilities
317      */
318     isDomCompliant: function() {
319         return true;
320     },
321 
322     /**
323      * proper insert before which takes tables into consideration as well as
324      * browser deficiencies
325      * @param item the node to insert before
326      * @param markup the markup to be inserted
327      */
328     insertBefore: function(item, markup) {
329         this._assertStdParams(item, markup, "insertBefore");
330 
331         markup = this._Lang.trim(markup);
332         if (markup === "") return null;
333 
334         var evalNodes = this._buildEvalNodes(item, markup),
335                 currentRef = item,
336                 parentNode = item.parentNode,
337                 ret = [];
338         for (var cnt = evalNodes.length - 1; cnt >= 0; cnt--) {
339             currentRef = parentNode.insertBefore(evalNodes[cnt], currentRef);
340             ret.push(currentRef);
341         }
342         ret = ret.reverse();
343         this._eval(ret);
344         return ret;
345     },
346 
347     /**
348      * proper insert before which takes tables into consideration as well as
349      * browser deficiencies
350      * @param item the node to insert before
351      * @param markup the markup to be inserted
352      */
353     insertAfter: function(item, markup) {
354         this._assertStdParams(item, markup, "insertAfter");
355         markup = this._Lang.trim(markup);
356         if (markup === "") return null;
357 
358         var evalNodes = this._buildEvalNodes(item, markup),
359                 currentRef = item,
360                 parentNode = item.parentNode,
361                 ret = [];
362 
363         for (var cnt = 0; cnt < evalNodes.length; cnt++) {
364             if (currentRef.nextSibling) {
365                 //Winmobile 6 has problems with this strategy, but it is not really fixable
366                 currentRef = parentNode.insertBefore(evalNodes[cnt], currentRef.nextSibling);
367             } else {
368                 currentRef = parentNode.appendChild(evalNodes[cnt]);
369             }
370             ret.push(currentRef);
371         }
372         this._eval(ret);
373         return ret;
374     },
375 
376     propertyToAttribute: function(name) {
377         if (name === 'className') {
378             return 'class';
379         } else if (name === 'xmllang') {
380             return 'xml:lang';
381         } else {
382             return name.toLowerCase();
383         }
384     },
385 
386     isFunctionNative: function(func) {
387         return /^\s*function[^{]+{\s*\[native code\]\s*}\s*$/.test(String(func));
388     },
389 
390     detectAttributes: function(element) {
391         //test if 'hasAttribute' method is present and its native code is intact
392         //for example, Prototype can add its own implementation if missing
393         if (element.hasAttribute && this.isFunctionNative(element.hasAttribute)) {
394             return function(name) {
395                 return element.hasAttribute(name);
396             }
397         } else {
398             try {
399                 //when accessing .getAttribute method without arguments does not throw an error then the method is not available
400                 element.getAttribute;
401 
402                 var html = element.outerHTML;
403                 var startTag = html.match(/^<[^>]*>/)[0];
404                 return function(name) {
405                     return startTag.indexOf(name + '=') > -1;
406                 }
407             } catch (ex) {
408                 return function(name) {
409                     return element.getAttribute(name);
410                 }
411             }
412         }
413     },
414 
415     /**
416      * copy all attributes from one element to another - except id
417      * @param target element to copy attributes to
418      * @param source element to copy attributes from
419      * @ignore
420      */
421     cloneAttributes: function(target, source) {
422 
423         // enumerate core element attributes - without 'dir' as special case
424         var coreElementProperties = ['className', 'title', 'lang', 'xmllang'];
425         // enumerate additional input element attributes
426         var inputElementProperties = [
427             'name', 'value', 'size', 'maxLength', 'src', 'alt', 'useMap', 'tabIndex', 'accessKey', 'accept', 'type'
428         ];
429         // enumerate additional boolean input attributes
430         var inputElementBooleanProperties = [
431             'checked', 'disabled', 'readOnly'
432         ];
433 
434         // Enumerate all the names of the event listeners
435         var listenerNames =
436             [ 'onclick', 'ondblclick', 'onmousedown', 'onmousemove', 'onmouseout',
437                 'onmouseover', 'onmouseup', 'onkeydown', 'onkeypress', 'onkeyup',
438                 'onhelp', 'onblur', 'onfocus', 'onchange', 'onload', 'onunload', 'onabort',
439                 'onreset', 'onselect', 'onsubmit'
440             ];
441 
442         var sourceAttributeDetector = this.detectAttributes(source);
443         var targetAttributeDetector = this.detectAttributes(target);
444 
445         var isInputElement = target.nodeName.toLowerCase() === 'input';
446         var propertyNames = isInputElement ? coreElementProperties.concat(inputElementProperties) : coreElementProperties;
447         var isXML = !source.ownerDocument.contentType || source.ownerDocument.contentType == 'text/xml';
448         for (var iIndex = 0, iLength = propertyNames.length; iIndex < iLength; iIndex++) {
449             var propertyName = propertyNames[iIndex];
450             var attributeName = this.propertyToAttribute(propertyName);
451             if (sourceAttributeDetector(attributeName)) {
452 
453                 //With IE 7 (quirks or standard mode) and IE 8/9 (quirks mode only),
454                 //you cannot get the attribute using 'class'. You must use 'className'
455                 //which is the same value you use to get the indexed property. The only
456                 //reliable way to detect this (without trying to evaluate the browser
457                 //mode and version) is to compare the two return values using 'className'
458                 //to see if they exactly the same.  If they are, then use the property
459                 //name when using getAttribute.
460                 if( attributeName == 'class'){
461                     if( this._RT.browser.isIE && (source.getAttribute(propertyName) === source[propertyName]) ){
462                         attributeName = propertyName;
463                     }
464                 }
465 
466                 var newValue = isXML ? source.getAttribute(attributeName) : source[propertyName];
467                 var oldValue = target[propertyName];
468                 if (oldValue != newValue) {
469                     target[propertyName] = newValue;
470                 }
471             } else {
472                 target.removeAttribute(attributeName);
473                 if (attributeName == "value") {
474                     target[propertyName] = '';
475                 }
476             }
477         }
478 
479         var booleanPropertyNames = isInputElement ? inputElementBooleanProperties : [];
480         for (var jIndex = 0, jLength = booleanPropertyNames.length; jIndex < jLength; jIndex++) {
481             var booleanPropertyName = booleanPropertyNames[jIndex];
482             var newBooleanValue = source[booleanPropertyName];
483             var oldBooleanValue = target[booleanPropertyName];
484             if (oldBooleanValue != newBooleanValue) {
485                 target[booleanPropertyName] = newBooleanValue;
486             }
487         }
488 
489         //'style' attribute special case
490         if (sourceAttributeDetector('style')) {
491             var newStyle;
492             var oldStyle;
493             if (this._RT.browser.isIE) {
494                 newStyle = source.style.cssText;
495                 oldStyle = target.style.cssText;
496                 if (newStyle != oldStyle) {
497                     target.style.cssText = newStyle;
498                 }
499             } else {
500                 newStyle = source.getAttribute('style');
501                 oldStyle = target.getAttribute('style');
502                 if (newStyle != oldStyle) {
503                     target.setAttribute('style', newStyle);
504                 }
505             }
506         } else if (targetAttributeDetector('style')){
507             target.removeAttribute('style');
508         }
509 
510         // Special case for 'dir' attribute
511         if (!this._RT.browser.isIE && source.dir != target.dir) {
512             if (sourceAttributeDetector('dir')) {
513                 target.dir = source.dir;
514             } else if (targetAttributeDetector('dir')) {
515                 target.dir = '';
516             }
517         }
518 
519         for (var lIndex = 0, lLength = listenerNames.length; lIndex < lLength; lIndex++) {
520             var name = listenerNames[lIndex];
521             target[name] = source[name] ? source[name] : null;
522             if (source[name]) {
523                 source[name] = null;
524             }
525         }
526 
527         //clone HTML5 data-* attributes
528         try{
529             var targetDataset = target.dataset;
530             var sourceDataset = source.dataset;
531             if (targetDataset || sourceDataset) {
532                 //cleanup the dataset
533                 for (var tp in targetDataset) {
534                     delete targetDataset[tp];
535                 }
536                 //copy dataset's properties
537                 for (var sp in sourceDataset) {
538                     targetDataset[sp] = sourceDataset[sp];
539                 }
540             }
541         } catch (ex) {
542             //most probably dataset properties are not supported
543         }
544     },
545     //from
546     // http://blog.vishalon.net/index.php/javascript-getting-and-setting-caret-position-in-textarea/
547     getCaretPosition:function (ctrl) {
548         var caretPos = 0;
549 
550         try {
551 
552             // other browsers make it simpler by simply having a selection start element
553             if (ctrl.selectionStart || ctrl.selectionStart == '0')
554                 caretPos = ctrl.selectionStart;
555             // ie 5 quirks mode as second option because
556             // this option is flakey in conjunction with text areas
557             // TODO move this into the quirks class
558             else if (document.selection) {
559                 ctrl.focus();
560                 var selection = document.selection.createRange();
561                 //the selection now is start zero
562                 selection.moveStart('character', -ctrl.value.length);
563                 //the caretposition is the selection start
564                 caretPos = selection.text.length;
565             }
566         } catch (e) {
567             //now this is ugly, but not supported input types throw errors for selectionStart
568             //this way we are future proof by having not to define every selection enabled
569             //input in an if (which will be a lot in the near future with html5)
570         }
571         return caretPos;
572     },
573 
574     setCaretPosition:function (ctrl, pos) {
575 
576         if (ctrl.createTextRange) {
577             var range = ctrl.createTextRange();
578             range.collapse(true);
579             range.moveEnd('character', pos);
580             range.moveStart('character', pos);
581             range.select();
582         }
583         //IE quirks mode again, TODO move this into the quirks class
584         else if (ctrl.setSelectionRange) {
585             ctrl.focus();
586             //the selection range is our caret position
587             ctrl.setSelectionRange(pos, pos);
588         }
589     },
590 
591     /**
592      * outerHTML replacement which works cross browserlike
593      * but still is speed optimized
594      *
595      * @param item the item to be replaced
596      * @param markup the markup for the replacement
597      * @param preserveFocus, tries to preserve the focus within the outerhtml operation
598      * if set to true a focus preservation algorithm based on document.activeElement is
599      * used to preserve the focus at the exactly same location as it was
600      *
601      */
602     outerHTML : function(item, markup, preserveFocus) {
603         this._assertStdParams(item, markup, "outerHTML");
604         markup = this._Lang.trim(markup);
605         // we can work on a single element in a cross browser fashion
606         // regarding the focus thanks to the
607         // icefaces team for providing the code
608         if (item.nodeName.toLowerCase() === 'input') {
609             var replacingInput = this._buildEvalNodes(item, markup)[0];
610             this.cloneAttributes(item, replacingInput);
611             return item;
612         } else {
613             if (markup !== "") {
614                 var ret = null;
615 
616                 var focusElementId = null;
617                 var caretPosition = 0;
618                 if (preserveFocus && 'undefined' != typeof document.activeElement) {
619                     focusElementId = (document.activeElement) ? document.activeElement.id : null;
620                     caretPosition = this.getCaretPosition(document.activeElement);
621                 }
622                 // we try to determine the browsers compatibility
623                 // level to standards dom level 2 via various methods
624                 if (this.isDomCompliant()) {
625                     ret = this._outerHTMLCompliant(item, markup);
626                 } else {
627                     //call into abstract method
628                     ret = this._outerHTMLNonCompliant(item, markup);
629                 }
630                 if (focusElementId) {
631                     var newFocusElement = this.byId(focusElementId);
632                     if (newFocusElement && newFocusElement.nodeName.toLowerCase() === 'input') {
633                         //just in case the replacement element is not focusable anymore
634                         if ("undefined" != typeof newFocusElement.focus) {
635                             newFocusElement.focus();
636                         }
637                     }
638                     if (newFocusElement && caretPosition) {
639                         //zero caret position is set automatically on focus
640                         this.setCaretPosition(newFocusElement, caretPosition);
641                     }
642                 }
643 
644                 // and remove the old item
645                 //first we have to save the node newly insert for easier access in our eval part
646                 this._eval(ret);
647                 return ret;
648             }
649             // and remove the old item, in case of an empty newtag and do nothing else
650             this._removeNode(item, false);
651             return null;
652         }
653     },
654 
655     /**
656      * detaches a set of nodes from their parent elements
657      * in a browser independend manner
658      * @param {Object} items the items which need to be detached
659      * @return {Array} an array of nodes with the detached dom nodes
660      */
661     detach: function(items) {
662         var ret = [];
663         if ('undefined' != typeof items.nodeType) {
664             if (items.parentNode) {
665                 ret.push(items.parentNode.removeChild(items));
666             } else {
667                 ret.push(items);
668             }
669             return ret;
670         }
671         //all ies treat node lists not as arrays so we have to take
672         //an intermediate step
673         var nodeArr = this._Lang.objToArray(items);
674         for (var cnt = 0; cnt < nodeArr.length; cnt++) {
675             ret.push(nodeArr[cnt].parentNode.removeChild(nodeArr[cnt]));
676         }
677         return ret;
678     },
679 
680     _outerHTMLCompliant: function(item, markup) {
681         //table element replacements like thead, tbody etc... have to be treated differently
682         var evalNodes = this._buildEvalNodes(item, markup);
683 
684         if (evalNodes.length == 1) {
685             var ret = evalNodes[0];
686             item.parentNode.replaceChild(ret, item);
687             return ret;
688         } else {
689             return this.replaceElements(item, evalNodes);
690         }
691     },
692 
693     /**
694      * checks if the provided element is a subelement of a table element
695      * @param item
696      */
697     _isTableElement: function(item) {
698         return !!this.TABLE_ELEMS[(item.nodeName || item.tagName).toLowerCase()];
699     },
700 
701     /**
702      * non ie browsers do not have problems with embedded scripts or any other construct
703      * we simply can use an innerHTML in a placeholder
704      *
705      * @param markup the markup to be used
706      */
707     _buildNodesCompliant: function(markup) {
708         var dummyPlaceHolder = this.getDummyPlaceHolder(); //document.createElement("div");
709         dummyPlaceHolder.innerHTML = markup;
710         return this._Lang.objToArray(dummyPlaceHolder.childNodes);
711     },
712 
713 
714 
715 
716     /**
717      * builds up a correct dom subtree
718      * if the markup is part of table nodes
719      * The usecase for this is to allow subtable rendering
720      * like single rows thead or tbody
721      *
722      * @param item
723      * @param markup
724      */
725     _buildTableNodes: function(item, markup) {
726         var itemNodeName = (item.nodeName || item.tagName).toLowerCase();
727 
728         var tmpNodeName = itemNodeName;
729         var depth = 0;
730         while (tmpNodeName != "table") {
731             item = item.parentNode;
732             tmpNodeName = (item.nodeName || item.tagName).toLowerCase();
733             depth++;
734         }
735 
736         var dummyPlaceHolder = this.getDummyPlaceHolder();
737         if (itemNodeName == "td") {
738             dummyPlaceHolder.innerHTML = "<table><tbody><tr>" + markup + "</tr></tbody></table>";
739         } else {
740             dummyPlaceHolder.innerHTML = "<table>" + markup + "</table>";
741         }
742 
743         for (var cnt = 0; cnt < depth; cnt++) {
744             dummyPlaceHolder = dummyPlaceHolder.childNodes[0];
745         }
746 
747         return this.detach(dummyPlaceHolder.childNodes);
748     },
749 
750     _removeChildNodes: function(node /*, breakEventsOpen */) {
751         if (!node) return;
752         node.innerHTML = "";
753     },
754 
755 
756 
757     _removeNode: function(node /*, breakEventsOpen*/) {
758         if (!node) return;
759         var parentNode = node.parentNode;
760         if (parentNode) //if the node has a parent
761             parentNode.removeChild(node);
762     },
763 
764 
765     /**
766      * build up the nodes from html markup in a browser independend way
767      * so that it also works with table nodes
768      *
769      * @param item the parent item upon the nodes need to be processed upon after building
770      * @param markup the markup to be built up
771      */
772     _buildEvalNodes: function(item, markup) {
773         var evalNodes = null;
774         if (this._isTableElement(item)) {
775             evalNodes = this._buildTableNodes(item, markup);
776         } else {
777             var nonIEQuirks = (!this._RT.browser.isIE || this._RT.browser.isIE > 8);
778             //ie8 has a special problem it still has the swallow scripts and other
779             //elements bug, but it is mostly dom compliant so we have to give it a special
780             //treatment, IE9 finally fixes that issue finally after 10 years
781             evalNodes = (this.isDomCompliant() &&  nonIEQuirks) ?
782                     this._buildNodesCompliant(markup) :
783                     //ie8 or quirks mode browsers
784                     this._buildNodesNonCompliant(markup);
785         }
786         return evalNodes;
787     },
788 
789     /**
790      * we have lots of methods with just an item and a markup as params
791      * this method builds an assertion for those methods to reduce code
792      *
793      * @param item  the item to be tested
794      * @param markup the markup
795      * @param caller caller function
796      * @param {optional} params array of assertion param names
797      */
798     _assertStdParams: function(item, markup, caller, params) {
799         //internal error
800         if (!caller) {
801             throw this._Lang.makeException(new Error(), null, null, this._nameSpace, "_assertStdParams",  "Caller must be set for assertion");
802         }
803         var _Lang = this._Lang,
804                 ERR_PROV = "ERR_MUST_BE_PROVIDED1",
805                 DOM = "myfaces._impl._util._Dom.",
806                 finalParams = params || ["item", "markup"];
807 
808         if (!item || !markup) {
809             _Lang.makeException(new Error(), null, null,DOM, ""+caller,  _Lang.getMessage(ERR_PROV, null, DOM +"."+ caller, (!item) ? finalParams[0] : finalParams[1]));
810             //throw Error(_Lang.getMessage(ERR_PROV, null, DOM + caller, (!item) ? params[0] : params[1]));
811         }
812     },
813 
814     /**
815      * internal eval handler used by various functions
816      * @param _nodeArr
817      */
818     _eval: function(_nodeArr) {
819         if (this.isManualScriptEval()) {
820             var isArr = _nodeArr instanceof Array;
821             if (isArr && _nodeArr.length) {
822                 for (var cnt = 0; cnt < _nodeArr.length; cnt++) {
823                     this.runScripts(_nodeArr[cnt]);
824                 }
825             } else if (!isArr) {
826                 this.runScripts(_nodeArr);
827             }
828         }
829     },
830 
831     /**
832      * for performance reasons we work with replaceElement and replaceElements here
833      * after measuring performance it has shown that passing down an array instead
834      * of a single node makes replaceElement twice as slow, however
835      * a single node case is the 95% case
836      *
837      * @param item
838      * @param evalNode
839      */
840     replaceElement: function(item, evalNode) {
841         //browsers with defect garbage collection
842         item.parentNode.insertBefore(evalNode, item);
843         this._removeNode(item, false);
844     },
845 
846 
847     /**
848      * replaces an element with another element or a set of elements
849      *
850      * @param item the item to be replaced
851      *
852      * @param evalNodes the elements
853      */
854     replaceElements: function (item, evalNodes) {
855         var evalNodesDefined = evalNodes && 'undefined' != typeof evalNodes.length;
856         if (!evalNodesDefined) {
857             throw this._Lang.makeException(new Error(), null, null, this._nameSpace, "replaceElements",  this._Lang.getMessage("ERR_REPLACE_EL"));
858         }
859 
860         var parentNode = item.parentNode,
861 
862                 sibling = item.nextSibling,
863                 resultArr = this._Lang.objToArray(evalNodes);
864 
865         for (var cnt = 0; cnt < resultArr.length; cnt++) {
866             if (cnt == 0) {
867                 this.replaceElement(item, resultArr[cnt]);
868             } else {
869                 if (sibling) {
870                     parentNode.insertBefore(resultArr[cnt], sibling);
871                 } else {
872                     parentNode.appendChild(resultArr[cnt]);
873                 }
874             }
875         }
876         return resultArr;
877     },
878 
879     /**
880      * optimized search for an array of tag names
881      * deep scan will always be performed.
882      * @param fragment the fragment which should be searched for
883      * @param tagNames an map indx of tag names which have to be found
884      *
885      */
886     findByTagNames: function(fragment, tagNames) {
887         this._assertStdParams(fragment, tagNames, "findByTagNames", ["fragment", "tagNames"]);
888 
889         var nodeType = fragment.nodeType;
890         if (nodeType != 1 && nodeType != 9 && nodeType != 11) return null;
891 
892         //we can use the shortcut
893         if (fragment.querySelectorAll) {
894             var query = [];
895             for (var key in tagNames) {
896                 if(!tagNames.hasOwnProperty(key)) continue;
897                 query.push(key);
898             }
899             var res = [];
900             if (fragment.tagName && tagNames[fragment.tagName.toLowerCase()]) {
901                 res.push(fragment);
902             }
903             return res.concat(this._Lang.objToArray(fragment.querySelectorAll(query.join(", "))));
904         }
905 
906         //now the filter function checks case insensitively for the tag names needed
907         var filter = function(node) {
908             return node.tagName && tagNames[node.tagName.toLowerCase()];
909         };
910 
911         //now we run an optimized find all on it
912         try {
913             return this.findAll(fragment, filter, true);
914         } finally {
915             //the usual IE6 is broken, fix code
916             filter = null;
917         }
918     },
919 
920     /**
921      * determines the number of nodes according to their tagType
922      *
923      * @param {Node} fragment (Node or fragment) the fragment to be investigated
924      * @param {String} tagName the tag name (lowercase)
925      * (the normal usecase is false, which means if the element is found only its
926      * adjacent elements will be scanned, due to the recursive descension
927      * this should work out with elements with different nesting depths but not being
928      * parent and child to each other
929      *
930      * @return the child elements as array or null if nothing is found
931      *
932      */
933     findByTagName : function(fragment, tagName) {
934         this._assertStdParams(fragment, tagName, "findByTagName", ["fragment", "tagName"]);
935         var _Lang = this._Lang,
936                 nodeType = fragment.nodeType;
937         if (nodeType != 1 && nodeType != 9 && nodeType != 11) return null;
938 
939         //remapping to save a few bytes
940 
941         var ret = _Lang.objToArray(fragment.getElementsByTagName(tagName));
942         if (fragment.tagName && _Lang.equalsIgnoreCase(fragment.tagName, tagName)) ret.unshift(fragment);
943         return ret;
944     },
945 
946     findByName : function(fragment, name) {
947         this._assertStdParams(fragment, name, "findByName", ["fragment", "name"]);
948 
949         var nodeType = fragment.nodeType;
950         if (nodeType != 1 && nodeType != 9 && nodeType != 11) return null;
951 
952         var ret = this._Lang.objToArray(fragment.getElementsByName(name));
953         if (fragment.name == name) ret.unshift(fragment);
954         return ret;
955     },
956 
957     /**
958      * a filtered findAll for subdom treewalking
959      * (which uses browser optimizations wherever possible)
960      *
961      * @param {|Node|} rootNode the rootNode so start the scan
962      * @param filter filter closure with the syntax {boolean} filter({Node} node)
963      * @param deepScan if set to true or not set at all a deep scan is performed (for form scans it does not make much sense to deeply scan)
964      */
965     findAll : function(rootNode, filter, deepScan) {
966         this._Lang.assertType(filter, "function");
967         deepScan = !!deepScan;
968 
969         if (document.createTreeWalker && NodeFilter) {
970             return this._iteratorSearchAll(rootNode, filter, deepScan);
971         } else {
972             //will not be called in dom level3 compliant browsers
973             return this._recursionSearchAll(rootNode, filter, deepScan);
974         }
975     },
976 
977     /**
978      * the faster dom iterator based search, works on all newer browsers
979      * except ie8 which already have implemented the dom iterator functions
980      * of html 5 (which is pretty all standard compliant browsers)
981      *
982      * The advantage of this method is a faster tree iteration compared
983      * to the normal recursive tree walking.
984      *
985      * @param rootNode the root node to be iterated over
986      * @param filter the iteration filter
987      * @param deepScan if set to true a deep scan is performed
988      */
989     _iteratorSearchAll: function(rootNode, filter, deepScan) {
990         var retVal = [];
991         //Works on firefox and webkit, opera and ie have to use the slower fallback mechanis
992         //we have a tree walker in place this allows for an optimized deep scan
993         if (filter(rootNode)) {
994 
995             retVal.push(rootNode);
996             if (!deepScan) {
997                 return retVal;
998             }
999         }
1000         //we use the reject mechanism to prevent a deep scan reject means any
1001         //child elements will be omitted from the scan
1002         var FILTER_ACCEPT = NodeFilter.FILTER_ACCEPT,
1003                 FILTER_SKIP = NodeFilter.FILTER_SKIP,
1004                 FILTER_REJECT = NodeFilter.FILTER_REJECT;
1005 
1006         var walkerFilter = function (node) {
1007             var retCode = (filter(node)) ? FILTER_ACCEPT : FILTER_SKIP;
1008             retCode = (!deepScan && retCode == FILTER_ACCEPT) ? FILTER_REJECT : retCode;
1009             if (retCode == FILTER_ACCEPT || retCode == FILTER_REJECT) {
1010                 retVal.push(node);
1011             }
1012             return retCode;
1013         };
1014 
1015         var treeWalker = document.createTreeWalker(rootNode, NodeFilter.SHOW_ELEMENT, walkerFilter, false);
1016         //noinspection StatementWithEmptyBodyJS
1017         while (treeWalker.nextNode());
1018         return retVal;
1019     },
1020 
1021     /**
1022      * bugfixing for ie6 which does not cope properly with setAttribute
1023      */
1024     setAttribute : function(node, attr, val) {
1025         this._assertStdParams(node, attr, "setAttribute", ["fragment", "name"]);
1026         if (!node.setAttribute) {
1027             return;
1028         }
1029 
1030         if (attr === 'disabled') {
1031             node.disabled = val === 'disabled' || val === 'true';
1032         } else if (attr === 'checked') {
1033             node.checked = val === 'checked' || val === 'on' || val === 'true';
1034         } else if (attr == 'readonly') {
1035             node.readOnly = val === 'readonly' || val === 'true';
1036         } else {
1037             node.setAttribute(attr, val);
1038         }
1039     },
1040 
1041     /**
1042      * fuzzy form detection which tries to determine the form
1043      * an item has been detached.
1044      *
1045      * The problem is some Javascript libraries simply try to
1046      * detach controls by reusing the names
1047      * of the detached input controls. Most of the times,
1048      * the name is unique in a jsf scenario, due to the inherent form mapping.
1049      * One way or the other, we will try to fix that by
1050      * identifying the proper form over the name
1051      *
1052      * We do it in several ways, in case of no form null is returned
1053      * in case of multiple forms we check all elements with a given name (which we determine
1054      * out of a name or id of the detached element) and then iterate over them
1055      * to find whether they are in a form or not.
1056      *
1057      * If only one element within a form and a given identifier found then we can pull out
1058      * and move on
1059      *
1060      * We cannot do much further because in case of two identical named elements
1061      * all checks must fail and the first elements form is served.
1062      *
1063      * Note, this method is only triggered in case of the issuer or an ajax request
1064      * is a detached element, otherwise already existing code has served the correct form.
1065      *
1066      * This method was added because of
1067      * https://issues.apache.org/jira/browse/MYFACES-2599
1068      * to support the integration of existing ajax libraries which do heavy dom manipulation on the
1069      * controls side (Dojos Dijit library for instance).
1070      *
1071      * @param {Node} elem - element as source, can be detached, undefined or null
1072      *
1073      * @return either null or a form node if it could be determined
1074      *
1075      * TODO move this into extended and replace it with a simpler algorithm
1076      */
1077     fuzzyFormDetection : function(elem) {
1078         var forms = document.forms, _Lang = this._Lang;
1079 
1080         if (!forms || !forms.length) {
1081             return null;
1082         }
1083 
1084         // This will not work well on portlet case, because we cannot be sure
1085         // the returned form is right one.
1086         //we can cover that case by simply adding one of our config params
1087         //the default is the weaker, but more correct portlet code
1088         //you can override it with myfaces_config.no_portlet_env = true globally
1089         else if (1 == forms.length && this._RT.getGlobalConfig("no_portlet_env", false)) {
1090             return forms[0];
1091         }
1092 
1093         //before going into the more complicated stuff we try the simple approach
1094         var finalElem = this.byId(elem);
1095         var fetchForm = _Lang.hitch(this, function(elem) {
1096             //element of type form then we are already
1097             //at form level for the issuing element
1098             //https://issues.apache.org/jira/browse/MYFACES-2793
1099 
1100             return (_Lang.equalsIgnoreCase(elem.tagName, "form")) ? elem :
1101                     ( this.html5FormDetection(elem) || this.getParent(elem, "form"));
1102         });
1103 
1104         if (finalElem) {
1105             var elemForm = fetchForm(finalElem);
1106             if (elemForm) return elemForm;
1107         }
1108 
1109         /**
1110          * name check
1111          */
1112         var foundElements = [];
1113         var name = (_Lang.isString(elem)) ? elem : elem.name;
1114         //id detection did not work
1115         if (!name) return null;
1116         /**
1117          * the lesser chance is the elements which have the same name
1118          * (which is the more likely case in case of a brute dom replacement)
1119          */
1120         var nameElems = document.getElementsByName(name);
1121         if (nameElems) {
1122             for (var cnt = 0; cnt < nameElems.length && foundElements.length < 2; cnt++) {
1123                 // we already have covered the identifier case hence we only can deal with names,
1124                 var foundForm = fetchForm(nameElems[cnt]);
1125                 if (foundForm) {
1126                     foundElements.push(foundForm);
1127                 }
1128             }
1129         }
1130 
1131         return (1 == foundElements.length ) ? foundElements[0] : null;
1132     },
1133 
1134     html5FormDetection: function(/*item*/) {
1135         return null;
1136     },
1137 
1138 
1139     /**
1140      * gets a parent of an item with a given tagname
1141      * @param {Node} item - child element
1142      * @param {String} tagName - TagName of parent element
1143      */
1144     getParent : function(item, tagName) {
1145 
1146         if (!item) {
1147             throw this._Lang.makeException(new Error(), null, null, this._nameSpace, "getParent",
1148                     this._Lang.getMessage("ERR_MUST_BE_PROVIDED1", null, "_Dom.getParent", "item {DomNode}"));
1149         }
1150 
1151         var _Lang = this._Lang;
1152         var searchClosure = function(parentItem) {
1153             return parentItem && parentItem.tagName
1154                     && _Lang.equalsIgnoreCase(parentItem.tagName, tagName);
1155         };
1156         try {
1157             return this.getFilteredParent(item, searchClosure);
1158         } finally {
1159             searchClosure = null;
1160             _Lang = null;
1161         }
1162     },
1163 
1164     /**
1165      * A parent walker which uses
1166      * a filter closure for filtering
1167      *
1168      * @param {Node} item the root item to ascend from
1169      * @param {function} filter the filter closure
1170      */
1171     getFilteredParent : function(item, filter) {
1172         this._assertStdParams(item, filter, "getFilteredParent", ["item", "filter"]);
1173 
1174         //search parent tag parentName
1175         var parentItem = (item.parentNode) ? item.parentNode : null;
1176 
1177         while (parentItem && !filter(parentItem)) {
1178             parentItem = parentItem.parentNode;
1179         }
1180         return (parentItem) ? parentItem : null;
1181     },
1182 
1183     /**
1184      * cross ported from dojo
1185      * fetches an attribute from a node
1186      *
1187      * @param {String} node the node
1188      * @param {String} attr the attribute
1189      * @return the attributes value or null
1190      */
1191     getAttribute : function(/* HTMLElement */node, /* string */attr) {
1192         return node.getAttribute(attr);
1193     },
1194 
1195     /**
1196      * checks whether the given node has an attribute attached
1197      *
1198      * @param {String|Object} node the node to search for
1199      * @param {String} attr the attribute to search for
1200      * @true if the attribute was found
1201      */
1202     hasAttribute : function(/* HTMLElement */node, /* string */attr) {
1203         //	summary
1204         //	Determines whether or not the specified node carries a value for the attribute in question.
1205         return this.getAttribute(node, attr) ? true : false;	//	boolean
1206     },
1207 
1208     /**
1209      * concatenation routine which concats all childnodes of a node which
1210      * contains a set of CDATA blocks to one big string
1211      * @param {Node} node the node to concat its blocks for
1212      */
1213     concatCDATABlocks : function(/*Node*/ node) {
1214         var cDataBlock = [];
1215         // response may contain several blocks
1216         for (var i = 0; i < node.childNodes.length; i++) {
1217             cDataBlock.push(node.childNodes[i].data);
1218         }
1219         return cDataBlock.join('');
1220     },
1221 
1222     //all modern browsers evaluate the scripts
1223     //manually this is a w3d recommendation
1224     isManualScriptEval: function() {
1225         return true;
1226     },
1227 
1228     /**
1229      * jsf2.2
1230      * checks if there is a fileupload element within
1231      * the executes list
1232      *
1233      * @param executes the executes list
1234      * @return {Boolean} true if there is a fileupload element
1235      */
1236     isMultipartCandidate:function (executes) {
1237         if (this._Lang.isString(executes)) {
1238             executes = this._Lang.strToArray(executes, /\s+/);
1239         }
1240 
1241         for (var cnt = 0, len = executes.length; cnt < len ; cnt ++) {
1242             var element = this.byId(executes[cnt]);
1243             var inputs = this.findByTagName(element, "input", true);
1244             for (var cnt2 = 0, len2 = inputs.length; cnt2 < len2 ; cnt2++) {
1245                 if (this.getAttribute(inputs[cnt2], "type") == "file") return true;
1246             }
1247         }
1248         return false;
1249     },
1250 
1251     insertFirst: function(newNode) {
1252         var body = document.body;
1253         if (body.childNodes.length > 0) {
1254             body.insertBefore(newNode, body.firstChild);
1255         } else {
1256             body.appendChild(newNode);
1257         }
1258     },
1259 
1260     byId: function(id) {
1261         return this._Lang.byId(id);
1262     },
1263 
1264     getDummyPlaceHolder: function() {
1265         this._dummyPlaceHolder = this._dummyPlaceHolder ||this.createElement("div");
1266         return this._dummyPlaceHolder;
1267     },
1268 
1269     getNamedElementFromForm: function(form, elementId) {
1270         return form[elementId];
1271     }
1272 });
1273 
1274 
1275