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         // we can work on a single element in a cross browser fashion
605         // regarding the focus thanks to the
606         // icefaces team for providing the code
607         if (item.nodeName.toLowerCase() === 'input') {
608             var replacingInput = this._buildEvalNodes(item, markup)[0];
609             this.cloneAttributes(item, replacingInput);
610             return item;
611         } else {
612             markup = this._Lang.trim(markup);
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     isFunctionNative: function(func) {
656         return /^\s*function[^{]+{\s*\[native code\]\s*}\s*$/.test(String(func));
657     },
658 
659     detectAttributes: function(element) {
660         //test if 'hasAttribute' method is present and its native code is intact
661         //for example, Prototype can add its own implementation if missing
662         if (element.hasAttribute && this.isFunctionNative(element.hasAttribute)) {
663             return function(name) {
664                 return element.hasAttribute(name);
665             }
666         } else {
667             try {
668                 //when accessing .getAttribute method without arguments does not throw an error then the method is not available
669                 element.getAttribute;
670 
671                 var html = element.outerHTML;
672                 var startTag = html.match(/^<[^>]*>/)[0];
673                 return function(name) {
674                     return startTag.indexOf(name + '=') > -1;
675                 }
676             } catch (ex) {
677                 return function(name) {
678                     return element.getAttribute(name);
679                 }
680             }
681         }
682     },
683 
684     /**
685      * detaches a set of nodes from their parent elements
686      * in a browser independend manner
687      * @param {Object} items the items which need to be detached
688      * @return {Array} an array of nodes with the detached dom nodes
689      */
690     detach: function(items) {
691         var ret = [];
692         if ('undefined' != typeof items.nodeType) {
693             if (items.parentNode) {
694                 ret.push(items.parentNode.removeChild(items));
695             } else {
696                 ret.push(items);
697             }
698             return ret;
699         }
700         //all ies treat node lists not as arrays so we have to take
701         //an intermediate step
702         var nodeArr = this._Lang.objToArray(items);
703         for (var cnt = 0; cnt < nodeArr.length; cnt++) {
704             ret.push(nodeArr[cnt].parentNode.removeChild(nodeArr[cnt]));
705         }
706         return ret;
707     },
708 
709     _outerHTMLCompliant: function(item, markup) {
710         //table element replacements like thead, tbody etc... have to be treated differently
711         var evalNodes = this._buildEvalNodes(item, markup);
712 
713         if (evalNodes.length == 1) {
714             var ret = evalNodes[0];
715             item.parentNode.replaceChild(ret, item);
716             return ret;
717         } else {
718             return this.replaceElements(item, evalNodes);
719         }
720     },
721 
722     /**
723      * checks if the provided element is a subelement of a table element
724      * @param item
725      */
726     _isTableElement: function(item) {
727         return !!this.TABLE_ELEMS[(item.nodeName || item.tagName).toLowerCase()];
728     },
729 
730     /**
731      * non ie browsers do not have problems with embedded scripts or any other construct
732      * we simply can use an innerHTML in a placeholder
733      *
734      * @param markup the markup to be used
735      */
736     _buildNodesCompliant: function(markup) {
737         var dummyPlaceHolder = this.getDummyPlaceHolder(); //document.createElement("div");
738         dummyPlaceHolder.innerHTML = markup;
739         return this._Lang.objToArray(dummyPlaceHolder.childNodes);
740     },
741 
742 
743 
744 
745     /**
746      * builds up a correct dom subtree
747      * if the markup is part of table nodes
748      * The usecase for this is to allow subtable rendering
749      * like single rows thead or tbody
750      *
751      * @param item
752      * @param markup
753      */
754     _buildTableNodes: function(item, markup) {
755         var itemNodeName = (item.nodeName || item.tagName).toLowerCase();
756 
757         var tmpNodeName = itemNodeName;
758         var depth = 0;
759         while (tmpNodeName != "table") {
760             item = item.parentNode;
761             tmpNodeName = (item.nodeName || item.tagName).toLowerCase();
762             depth++;
763         }
764 
765         var dummyPlaceHolder = this.getDummyPlaceHolder();
766         if (itemNodeName == "td") {
767             dummyPlaceHolder.innerHTML = "<table><tbody><tr>" + markup + "</tr></tbody></table>";
768         } else {
769             dummyPlaceHolder.innerHTML = "<table>" + markup + "</table>";
770         }
771 
772         for (var cnt = 0; cnt < depth; cnt++) {
773             dummyPlaceHolder = dummyPlaceHolder.childNodes[0];
774         }
775 
776         return this.detach(dummyPlaceHolder.childNodes);
777     },
778 
779     _removeChildNodes: function(node /*, breakEventsOpen */) {
780         if (!node) return;
781         node.innerHTML = "";
782     },
783 
784 
785 
786     _removeNode: function(node /*, breakEventsOpen*/) {
787         if (!node) return;
788         var parentNode = node.parentNode;
789         if (parentNode) //if the node has a parent
790             parentNode.removeChild(node);
791     },
792 
793 
794     /**
795      * build up the nodes from html markup in a browser independend way
796      * so that it also works with table nodes
797      *
798      * @param item the parent item upon the nodes need to be processed upon after building
799      * @param markup the markup to be built up
800      */
801     _buildEvalNodes: function(item, markup) {
802         var evalNodes = null;
803         if (this._isTableElement(item)) {
804             evalNodes = this._buildTableNodes(item, markup);
805         } else {
806             var nonIEQuirks = (!this._RT.browser.isIE || this._RT.browser.isIE > 8);
807             //ie8 has a special problem it still has the swallow scripts and other
808             //elements bug, but it is mostly dom compliant so we have to give it a special
809             //treatment, IE9 finally fixes that issue finally after 10 years
810             evalNodes = (this.isDomCompliant() &&  nonIEQuirks) ?
811                     this._buildNodesCompliant(markup) :
812                     //ie8 or quirks mode browsers
813                     this._buildNodesNonCompliant(markup);
814         }
815         return evalNodes;
816     },
817 
818     /**
819      * we have lots of methods with just an item and a markup as params
820      * this method builds an assertion for those methods to reduce code
821      *
822      * @param item  the item to be tested
823      * @param markup the markup
824      * @param caller caller function
825      * @param {optional} params array of assertion param names
826      */
827     _assertStdParams: function(item, markup, caller, params) {
828         //internal error
829         if (!caller) {
830             throw this._Lang.makeException(new Error(), null, null, this._nameSpace, "_assertStdParams",  "Caller must be set for assertion");
831         }
832         var _Lang = this._Lang,
833                 ERR_PROV = "ERR_MUST_BE_PROVIDED1",
834                 DOM = "myfaces._impl._util._Dom.",
835                 finalParams = params || ["item", "markup"];
836 
837         if (!item || !markup) {
838             _Lang.makeException(new Error(), null, null,DOM, ""+caller,  _Lang.getMessage(ERR_PROV, null, DOM +"."+ caller, (!item) ? finalParams[0] : finalParams[1]));
839             //throw Error(_Lang.getMessage(ERR_PROV, null, DOM + caller, (!item) ? params[0] : params[1]));
840         }
841     },
842 
843     /**
844      * internal eval handler used by various functions
845      * @param _nodeArr
846      */
847     _eval: function(_nodeArr) {
848         if (this.isManualScriptEval()) {
849             var isArr = _nodeArr instanceof Array;
850             if (isArr && _nodeArr.length) {
851                 for (var cnt = 0; cnt < _nodeArr.length; cnt++) {
852                     this.runScripts(_nodeArr[cnt]);
853                 }
854             } else if (!isArr) {
855                 this.runScripts(_nodeArr);
856             }
857         }
858     },
859 
860     /**
861      * for performance reasons we work with replaceElement and replaceElements here
862      * after measuring performance it has shown that passing down an array instead
863      * of a single node makes replaceElement twice as slow, however
864      * a single node case is the 95% case
865      *
866      * @param item
867      * @param evalNode
868      */
869     replaceElement: function(item, evalNode) {
870         //browsers with defect garbage collection
871         item.parentNode.insertBefore(evalNode, item);
872         this._removeNode(item, false);
873     },
874 
875 
876     /**
877      * replaces an element with another element or a set of elements
878      *
879      * @param item the item to be replaced
880      *
881      * @param evalNodes the elements
882      */
883     replaceElements: function (item, evalNodes) {
884         var evalNodesDefined = evalNodes && 'undefined' != typeof evalNodes.length;
885         if (!evalNodesDefined) {
886             throw this._Lang.makeException(new Error(), null, null, this._nameSpace, "replaceElements",  this._Lang.getMessage("ERR_REPLACE_EL"));
887         }
888 
889         var parentNode = item.parentNode,
890 
891                 sibling = item.nextSibling,
892                 resultArr = this._Lang.objToArray(evalNodes);
893 
894         for (var cnt = 0; cnt < resultArr.length; cnt++) {
895             if (cnt == 0) {
896                 this.replaceElement(item, resultArr[cnt]);
897             } else {
898                 if (sibling) {
899                     parentNode.insertBefore(resultArr[cnt], sibling);
900                 } else {
901                     parentNode.appendChild(resultArr[cnt]);
902                 }
903             }
904         }
905         return resultArr;
906     },
907 
908     /**
909      * optimized search for an array of tag names
910      * deep scan will always be performed.
911      * @param fragment the fragment which should be searched for
912      * @param tagNames an map indx of tag names which have to be found
913      *
914      */
915     findByTagNames: function(fragment, tagNames) {
916         this._assertStdParams(fragment, tagNames, "findByTagNames", ["fragment", "tagNames"]);
917 
918         var nodeType = fragment.nodeType;
919         if (nodeType != 1 && nodeType != 9 && nodeType != 11) return null;
920 
921         //we can use the shortcut
922         if (fragment.querySelectorAll) {
923             var query = [];
924             for (var key in tagNames) {
925                 if(!tagNames.hasOwnProperty(key)) continue;
926                 query.push(key);
927             }
928             var res = [];
929             if (fragment.tagName && tagNames[fragment.tagName.toLowerCase()]) {
930                 res.push(fragment);
931             }
932             return res.concat(this._Lang.objToArray(fragment.querySelectorAll(query.join(", "))));
933         }
934 
935         //now the filter function checks case insensitively for the tag names needed
936         var filter = function(node) {
937             return node.tagName && tagNames[node.tagName.toLowerCase()];
938         };
939 
940         //now we run an optimized find all on it
941         try {
942             return this.findAll(fragment, filter, true);
943         } finally {
944             //the usual IE6 is broken, fix code
945             filter = null;
946         }
947     },
948 
949     /**
950      * determines the number of nodes according to their tagType
951      *
952      * @param {Node} fragment (Node or fragment) the fragment to be investigated
953      * @param {String} tagName the tag name (lowercase)
954      * (the normal usecase is false, which means if the element is found only its
955      * adjacent elements will be scanned, due to the recursive descension
956      * this should work out with elements with different nesting depths but not being
957      * parent and child to each other
958      *
959      * @return the child elements as array or null if nothing is found
960      *
961      */
962     findByTagName : function(fragment, tagName) {
963         this._assertStdParams(fragment, tagName, "findByTagName", ["fragment", "tagName"]);
964         var _Lang = this._Lang,
965                 nodeType = fragment.nodeType;
966         if (nodeType != 1 && nodeType != 9 && nodeType != 11) return null;
967 
968         //remapping to save a few bytes
969 
970         var ret = _Lang.objToArray(fragment.getElementsByTagName(tagName));
971         if (fragment.tagName && _Lang.equalsIgnoreCase(fragment.tagName, tagName)) ret.unshift(fragment);
972         return ret;
973     },
974 
975     findByName : function(fragment, name) {
976         this._assertStdParams(fragment, name, "findByName", ["fragment", "name"]);
977 
978         var nodeType = fragment.nodeType;
979         if (nodeType != 1 && nodeType != 9 && nodeType != 11) return null;
980 
981         var ret = this._Lang.objToArray(fragment.getElementsByName(name));
982         if (fragment.name == name) ret.unshift(fragment);
983         return ret;
984     },
985 
986     /**
987      * a filtered findAll for subdom treewalking
988      * (which uses browser optimizations wherever possible)
989      *
990      * @param {|Node|} rootNode the rootNode so start the scan
991      * @param filter filter closure with the syntax {boolean} filter({Node} node)
992      * @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)
993      */
994     findAll : function(rootNode, filter, deepScan) {
995         this._Lang.assertType(filter, "function");
996         deepScan = !!deepScan;
997 
998         if (document.createTreeWalker && NodeFilter) {
999             return this._iteratorSearchAll(rootNode, filter, deepScan);
1000         } else {
1001             //will not be called in dom level3 compliant browsers
1002             return this._recursionSearchAll(rootNode, filter, deepScan);
1003         }
1004     },
1005 
1006     /**
1007      * the faster dom iterator based search, works on all newer browsers
1008      * except ie8 which already have implemented the dom iterator functions
1009      * of html 5 (which is pretty all standard compliant browsers)
1010      *
1011      * The advantage of this method is a faster tree iteration compared
1012      * to the normal recursive tree walking.
1013      *
1014      * @param rootNode the root node to be iterated over
1015      * @param filter the iteration filter
1016      * @param deepScan if set to true a deep scan is performed
1017      */
1018     _iteratorSearchAll: function(rootNode, filter, deepScan) {
1019         var retVal = [];
1020         //Works on firefox and webkit, opera and ie have to use the slower fallback mechanis
1021         //we have a tree walker in place this allows for an optimized deep scan
1022         if (filter(rootNode)) {
1023 
1024             retVal.push(rootNode);
1025             if (!deepScan) {
1026                 return retVal;
1027             }
1028         }
1029         //we use the reject mechanism to prevent a deep scan reject means any
1030         //child elements will be omitted from the scan
1031         var FILTER_ACCEPT = NodeFilter.FILTER_ACCEPT,
1032                 FILTER_SKIP = NodeFilter.FILTER_SKIP,
1033                 FILTER_REJECT = NodeFilter.FILTER_REJECT;
1034 
1035         var walkerFilter = function (node) {
1036             var retCode = (filter(node)) ? FILTER_ACCEPT : FILTER_SKIP;
1037             retCode = (!deepScan && retCode == FILTER_ACCEPT) ? FILTER_REJECT : retCode;
1038             if (retCode == FILTER_ACCEPT || retCode == FILTER_REJECT) {
1039                 retVal.push(node);
1040             }
1041             return retCode;
1042         };
1043 
1044         var treeWalker = document.createTreeWalker(rootNode, NodeFilter.SHOW_ELEMENT, walkerFilter, false);
1045         //noinspection StatementWithEmptyBodyJS
1046         while (treeWalker.nextNode());
1047         return retVal;
1048     },
1049 
1050     /**
1051      * bugfixing for ie6 which does not cope properly with setAttribute
1052      */
1053     setAttribute : function(node, attr, val) {
1054         this._assertStdParams(node, attr, "setAttribute", ["fragment", "name"]);
1055         if (!node.setAttribute) {
1056             return;
1057         }
1058 
1059         if (attr === 'disabled') {
1060             node.disabled = val === 'disabled' || val === 'true';
1061         } else if (attr === 'checked') {
1062             node.checked = val === 'checked' || val === 'on' || val === 'true';
1063         } else if (attr == 'readonly') {
1064             node.readOnly = val === 'readonly' || val === 'true';
1065         } else {
1066             node.setAttribute(attr, val);
1067         }
1068     },
1069 
1070     /**
1071      * fuzzy form detection which tries to determine the form
1072      * an item has been detached.
1073      *
1074      * The problem is some Javascript libraries simply try to
1075      * detach controls by reusing the names
1076      * of the detached input controls. Most of the times,
1077      * the name is unique in a jsf scenario, due to the inherent form mapping.
1078      * One way or the other, we will try to fix that by
1079      * identifying the proper form over the name
1080      *
1081      * We do it in several ways, in case of no form null is returned
1082      * in case of multiple forms we check all elements with a given name (which we determine
1083      * out of a name or id of the detached element) and then iterate over them
1084      * to find whether they are in a form or not.
1085      *
1086      * If only one element within a form and a given identifier found then we can pull out
1087      * and move on
1088      *
1089      * We cannot do much further because in case of two identical named elements
1090      * all checks must fail and the first elements form is served.
1091      *
1092      * Note, this method is only triggered in case of the issuer or an ajax request
1093      * is a detached element, otherwise already existing code has served the correct form.
1094      *
1095      * This method was added because of
1096      * https://issues.apache.org/jira/browse/MYFACES-2599
1097      * to support the integration of existing ajax libraries which do heavy dom manipulation on the
1098      * controls side (Dojos Dijit library for instance).
1099      *
1100      * @param {Node} elem - element as source, can be detached, undefined or null
1101      *
1102      * @return either null or a form node if it could be determined
1103      *
1104      * TODO move this into extended and replace it with a simpler algorithm
1105      */
1106     fuzzyFormDetection : function(elem) {
1107         var forms = document.forms, _Lang = this._Lang;
1108 
1109         if (!forms || !forms.length) {
1110             return null;
1111         }
1112 
1113         // This will not work well on portlet case, because we cannot be sure
1114         // the returned form is right one.
1115         //we can cover that case by simply adding one of our config params
1116         //the default is the weaker, but more correct portlet code
1117         //you can override it with myfaces_config.no_portlet_env = true globally
1118         else if (1 == forms.length && this._RT.getGlobalConfig("no_portlet_env", false)) {
1119             return forms[0];
1120         }
1121 
1122         //before going into the more complicated stuff we try the simple approach
1123         var finalElem = this.byId(elem);
1124         var fetchForm = _Lang.hitch(this, function(elem) {
1125             //element of type form then we are already
1126             //at form level for the issuing element
1127             //https://issues.apache.org/jira/browse/MYFACES-2793
1128 
1129             return (_Lang.equalsIgnoreCase(elem.tagName, "form")) ? elem :
1130                     ( this.html5FormDetection(elem) || this.getParent(elem, "form"));
1131         });
1132 
1133         if (finalElem) {
1134             var elemForm = fetchForm(finalElem);
1135             if (elemForm) return elemForm;
1136         }
1137 
1138         /**
1139          * name check
1140          */
1141         var foundElements = [];
1142         var name = (_Lang.isString(elem)) ? elem : elem.name;
1143         //id detection did not work
1144         if (!name) return null;
1145         /**
1146          * the lesser chance is the elements which have the same name
1147          * (which is the more likely case in case of a brute dom replacement)
1148          */
1149         var nameElems = document.getElementsByName(name);
1150         if (nameElems) {
1151             for (var cnt = 0; cnt < nameElems.length && foundElements.length < 2; cnt++) {
1152                 // we already have covered the identifier case hence we only can deal with names,
1153                 var foundForm = fetchForm(nameElems[cnt]);
1154                 if (foundForm) {
1155                     foundElements.push(foundForm);
1156                 }
1157             }
1158         }
1159 
1160         return (1 == foundElements.length ) ? foundElements[0] : null;
1161     },
1162 
1163     html5FormDetection: function(/*item*/) {
1164         return null;
1165     },
1166 
1167 
1168     /**
1169      * gets a parent of an item with a given tagname
1170      * @param {Node} item - child element
1171      * @param {String} tagName - TagName of parent element
1172      */
1173     getParent : function(item, tagName) {
1174 
1175         if (!item) {
1176             throw this._Lang.makeException(new Error(), null, null, this._nameSpace, "getParent",
1177                     this._Lang.getMessage("ERR_MUST_BE_PROVIDED1", null, "_Dom.getParent", "item {DomNode}"));
1178         }
1179 
1180         var _Lang = this._Lang;
1181         var searchClosure = function(parentItem) {
1182             return parentItem && parentItem.tagName
1183                     && _Lang.equalsIgnoreCase(parentItem.tagName, tagName);
1184         };
1185         try {
1186             return this.getFilteredParent(item, searchClosure);
1187         } finally {
1188             searchClosure = null;
1189             _Lang = null;
1190         }
1191     },
1192 
1193     /**
1194      * A parent walker which uses
1195      * a filter closure for filtering
1196      *
1197      * @param {Node} item the root item to ascend from
1198      * @param {function} filter the filter closure
1199      */
1200     getFilteredParent : function(item, filter) {
1201         this._assertStdParams(item, filter, "getFilteredParent", ["item", "filter"]);
1202 
1203         //search parent tag parentName
1204         var parentItem = (item.parentNode) ? item.parentNode : null;
1205 
1206         while (parentItem && !filter(parentItem)) {
1207             parentItem = parentItem.parentNode;
1208         }
1209         return (parentItem) ? parentItem : null;
1210     },
1211 
1212     /**
1213      * cross ported from dojo
1214      * fetches an attribute from a node
1215      *
1216      * @param {String} node the node
1217      * @param {String} attr the attribute
1218      * @return the attributes value or null
1219      */
1220     getAttribute : function(/* HTMLElement */node, /* string */attr) {
1221         return node.getAttribute(attr);
1222     },
1223 
1224     /**
1225      * checks whether the given node has an attribute attached
1226      *
1227      * @param {String|Object} node the node to search for
1228      * @param {String} attr the attribute to search for
1229      * @true if the attribute was found
1230      */
1231     hasAttribute : function(/* HTMLElement */node, /* string */attr) {
1232         //	summary
1233         //	Determines whether or not the specified node carries a value for the attribute in question.
1234         return this.getAttribute(node, attr) ? true : false;	//	boolean
1235     },
1236 
1237     /**
1238      * concatenation routine which concats all childnodes of a node which
1239      * contains a set of CDATA blocks to one big string
1240      * @param {Node} node the node to concat its blocks for
1241      */
1242     concatCDATABlocks : function(/*Node*/ node) {
1243         var cDataBlock = [];
1244         // response may contain several blocks
1245         for (var i = 0; i < node.childNodes.length; i++) {
1246             cDataBlock.push(node.childNodes[i].data);
1247         }
1248         return cDataBlock.join('');
1249     },
1250 
1251     //all modern browsers evaluate the scripts
1252     //manually this is a w3d recommendation
1253     isManualScriptEval: function() {
1254         return true;
1255     },
1256 
1257     /**
1258      * jsf2.2
1259      * checks if there is a fileupload element within
1260      * the executes list
1261      *
1262      * @param executes the executes list
1263      * @return {Boolean} true if there is a fileupload element
1264      */
1265     isMultipartCandidate:function (executes) {
1266         if (this._Lang.isString(executes)) {
1267             executes = this._Lang.strToArray(executes, /\s+/);
1268         }
1269 
1270         for (var cnt = 0, len = executes.length; cnt < len ; cnt ++) {
1271             var element = this.byId(executes[cnt]);
1272             var inputs = this.findByTagName(element, "input", true);
1273             for (var cnt2 = 0, len2 = inputs.length; cnt2 < len2 ; cnt2++) {
1274                 if (this.getAttribute(inputs[cnt2], "type") == "file") return true;
1275             }
1276         }
1277         return false;
1278     },
1279 
1280     insertFirst: function(newNode) {
1281         var body = document.body;
1282         if (body.childNodes.length > 0) {
1283             body.insertBefore(newNode, body.firstChild);
1284         } else {
1285             body.appendChild(newNode);
1286         }
1287     },
1288 
1289     byId: function(id) {
1290         return this._Lang.byId(id);
1291     },
1292 
1293     getDummyPlaceHolder: function() {
1294         this._dummyPlaceHolder = this._dummyPlaceHolder ||this.createElement("div");
1295         return this._dummyPlaceHolder;
1296     },
1297 
1298     getNamedElementFromForm: function(form, elementId) {
1299         return form[elementId];
1300     }
1301 });
1302 
1303 
1304