1 /*
  2  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
  3  *
  4  * Copyright 1997-2016 Sun Microsystems, Inc. All rights reserved.
  5  *
  6  * The contents of this file are subject to the terms of either the GNU
  7  * General Public License Version 2 only ("GPL") or the Common Development
  8  * and Distribution License("CDDL") (collectively, the "License").  You
  9  * may not use this file except in compliance with the License. You can obtain
 10  * a copy of the License at https://glassfish.java.net/public/CDDL+GPL.html
 11  * or glassfish/bootstrap/legal/LICENSE.txt.  See the License for the specific
 12  * language governing permissions and limitations under the License.
 13  *
 14  * When distributing the software, include this License Header Notice in each
 15  * file and include the License file at glassfish/bootstrap/legal/LICENSE.txt.
 16  * Sun designates this particular file as subject to the "Classpath" exception
 17  * as provided by Sun in the GPL Version 2 section of the License file that
 18  * accompanied this code.  If applicable, add the following below the License
 19  * Header, with the fields enclosed by brackets [] replaced by your own
 20  * identifying information: "Portions Copyrighted [year]
 21  * [name of copyright owner]"
 22  *
 23  * Contributor(s):
 24  *
 25  * If you wish your version of this file to be governed by only the CDDL or
 26  * only the GPL Version 2, indicate your decision by adding "[Contributor]
 27  * elects to include this software in this distribution under the [CDDL or GPL
 28  * Version 2] license."  If you don't indicate a single choice of license, a
 29  * recipient has the option to distribute your version of this file under
 30  * either the CDDL, the GPL Version 2 or to extend the choice of license to
 31  * its licensees as provided above.  However, if you add GPL Version 2 code
 32  * and therefore, elected the GPL Version 2 license, then the option applies
 33  * only if the new code is made subject to such option by the copyright
 34  * holder.
 35  *
 36  *
 37  * This file incorporates work covered by the following copyright and
 38  * permission notices:
 39  *
 40  * Copyright 2004 The Apache Software Foundation
 41  * Copyright 2004-2008 Emmanouil Batsis, mailto: mbatsis at users full stop sourceforge full stop net
 42  *
 43  * Licensed under the Apache License, Version 2.0 (the "License");
 44  * you may not use this file except in compliance with the License.
 45  * You may obtain a copy of the License at
 46  *
 47  *     http://www.apache.org/licenses/LICENSE-2.0
 48  *
 49  * Unless required by applicable law or agreed to in writing, software
 50  * distributed under the License is distributed on an "AS IS" BASIS,
 51  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 52  * See the License for the specific language governing permissions and
 53  * limitations under the License.
 54  */
 55 
 56 /**
 57  @project JSF JavaScript Library
 58  @version 2.2
 59  @description This is the standard implementation of the JSF JavaScript Library.
 60  */
 61 
 62 // Detect if this is already loaded, and if loaded, if it's a higher version
 63 if (!((jsf && jsf.specversion && jsf.specversion >= 23000 ) &&
 64       (jsf.implversion && jsf.implversion >= 3))) {
 65 
 66     /**
 67      * <span class="changed_modified_2_2">The top level global namespace
 68      * for JavaServer Faces functionality.</span>
 69 
 70      * @name jsf
 71      * @namespace
 72      */
 73     var jsf = {};
 74 
 75     /**
 76 
 77      * <span class="changed_modified_2_2 changed_modified_2_3">The namespace for Ajax
 78      * functionality.</span>
 79 
 80      * @name jsf.ajax
 81      * @namespace
 82      * @exec
 83      */
 84     jsf.ajax = function() {
 85 
 86         var eventListeners = [];
 87         var errorListeners = [];
 88 
 89         var delayHandler = null;
 90         /**
 91          * Determine if the current browser is part of Microsoft's failed attempt at
 92          * standards modification.
 93          * @ignore
 94          */
 95         var isIE = function isIE() {
 96             if (typeof isIECache !== "undefined") {
 97                 return isIECache;
 98             }
 99             isIECache =
100                    document.all && window.ActiveXObject &&
101                    navigator.userAgent.toLowerCase().indexOf("msie") > -1 &&
102                    navigator.userAgent.toLowerCase().indexOf("opera") == -1;
103             return isIECache;
104         };
105         var isIECache;
106 
107         /**
108          * Determine the version of IE.
109          * @ignore
110          */
111         var getIEVersion = function getIEVersion() {
112             if (typeof IEVersionCache !== "undefined") {
113                 return IEVersionCache;
114             }
115             if (/MSIE ([0-9]+)/.test(navigator.userAgent)) {
116                 IEVersionCache = parseInt(RegExp.$1);
117             } else {
118                 IEVersionCache = -1;
119             }
120             return IEVersionCache;
121         }
122         var IEVersionCache;
123 
124         /**
125          * Determine if loading scripts into the page executes the script.
126          * This is instead of doing a complicated browser detection algorithm.  Some do, some don't.
127          * @returns {boolean} does including a script in the dom execute it?
128          * @ignore
129          */
130         var isAutoExec = function isAutoExec() {
131             try {
132                 if (typeof isAutoExecCache !== "undefined") {
133                     return isAutoExecCache;
134                 }
135                 var autoExecTestString = "<script>var mojarra = mojarra || {};mojarra.autoExecTest = true;</script>";
136                 var tempElement = document.createElement('span');
137                 tempElement.innerHTML = autoExecTestString;
138                 var body = document.getElementsByTagName('body')[0];
139                 var tempNode = body.appendChild(tempElement);
140                 if (mojarra && mojarra.autoExecTest) {
141                     isAutoExecCache = true;
142                     delete mojarra.autoExecTest;
143                 } else {
144                     isAutoExecCache = false;
145                 }
146                 deleteNode(tempNode);
147                 return isAutoExecCache;
148             } catch (ex) {
149                 // OK, that didn't work, we'll have to make an assumption
150                 if (typeof isAutoExecCache === "undefined") {
151                     isAutoExecCache = false;
152                 }
153                 return isAutoExecCache;
154             }
155         };
156         var isAutoExecCache;
157 
158         /**
159          * @ignore
160          */
161         var getTransport = function getTransport(context) {
162             var returnVal;
163             // Here we check for encoding type for file upload(s).
164             // This is where we would also include a check for the existence of
165             // input file control for the current form (see hasInputFileControl
166             // function) but IE9 (at least) seems to render controls outside of
167             // form.
168             if (typeof context !== 'undefined' && context !== null &&
169                 context.includesInputFile &&
170                 context.form.enctype === "multipart/form-data") {
171                 returnVal = new FrameTransport(context);
172                 return returnVal;
173             }
174             var methods = [
175                 function() {
176                     return new XMLHttpRequest();
177                 },
178                 function() {
179                     return new ActiveXObject('Msxml2.XMLHTTP');
180                 },
181                 function() {
182                     return new ActiveXObject('Microsoft.XMLHTTP');
183                 }
184             ];
185 
186             for (var i = 0, len = methods.length; i < len; i++) {
187                 try {
188                     returnVal = methods[i]();
189                 } catch(e) {
190                     continue;
191                 }
192                 return returnVal;
193             }
194             throw new Error('Could not create an XHR object.');
195         };
196         
197         /**
198          * Used for iframe based communication (instead of XHR).
199          * @ignore
200          */
201         var FrameTransport = function FrameTransport(context) {
202             this.context = context;
203             this.frame = null;
204             this.FRAME_ID = "JSFFrameId";
205             this.FRAME_PARTIAL_ID = "Faces-Request";
206             this.partial = null;
207             this.aborted = false;
208             this.responseText = null;
209             this.responseXML = null;
210             this.readyState = 0;
211             this.requestHeader = {};
212             this.status = null;
213             this.method = null;
214             this.url = null;
215             this.requestParams = null;
216         };
217         
218         /**
219          * Extends FrameTransport an adds method functionality.
220          * @ignore
221          */
222         FrameTransport.prototype = {
223             
224             /**
225              *@ignore
226              */
227             setRequestHeader:function(key, value) {
228                 if (typeof(value) !== "undefined") {
229                     this.requestHeader[key] = value;  
230                 }
231             },
232             
233             /**
234              * Creates the hidden iframe and sets readystate.
235              * @ignore
236              */
237             open:function(method, url, async) {
238                 this.method = method;
239                 this.url = url;
240                 this.async = async;
241                 this.frame = document.getElementById(this.FRAME_ID);
242                 if (this.frame) {
243                     this.frame.parentNode.removeChild(this.frame);
244                     this.frame = null;
245                 }
246                 if (!this.frame) {  
247                     if ((!isIE() && !isIE9Plus())) {
248                         this.frame = document.createElement('iframe');
249                         this.frame.src = "about:blank";
250                         this.frame.id = this.FRAME_ID;
251                         this.frame.name = this.FRAME_ID;
252                         this.frame.type = "content";
253                         this.frame.collapsed = "true";
254                         this.frame.style = "visibility:hidden";   
255                         this.frame.width = "0";
256                         this.frame.height = "0";
257                         this.frame.style = "border:0";
258                         this.frame.frameBorder = 0;
259                         document.body.appendChild(this.frame);
260                         this.frame.onload = bind(this, this.callback);
261                     } else {
262                         var div = document.createElement("div");
263                         div.id = "frameDiv";
264                         div.innerHTML = "<iframe id='" + this.FRAME_ID + "' name='" + this.FRAME_ID + "' style='display:none;' src='about:blank' type='content' onload='this.onload_cb();'  ></iframe>";
265                         document.body.appendChild(div);
266                         this.frame = document.getElementById(this.FRAME_ID);
267                         this.frame.onload_cb = bind(this, this.callback);
268                     }
269                 }
270                 // Create to send "Faces-Request" param with value "partial/ajax"
271                 // For iframe approach we are sending as request parameter
272                 // For non-iframe (xhr ajax) it is sent in the request header
273                 this.partial = document.createElement("input");
274                 this.partial.setAttribute("type", "hidden");
275                 this.partial.setAttribute("id", this.FRAME_PARTIAL_ID);
276                 this.partial.setAttribute("name", this.FRAME_PARTIAL_ID);
277                 this.partial.setAttribute("value", "partial/ajax");
278                 this.context.form.appendChild(this.partial);
279   
280                 this.readyState = 1;                         
281             },
282             
283             /**
284              * Sets the form target to iframe, sets up request parameters
285              * and submits the form.
286              * @ignore
287              */
288             send: function(data) {
289                 var evt = {};
290                 this.context.form.target = this.frame.name;
291                 this.context.form.method = this.method;
292                 if (this.url) {
293                     this.context.form.action = this.url;
294                 }
295 
296                 this.readyState = 3;
297 
298                 this.onreadystatechange(evt);
299                 
300                 var ddata = decodeURIComponent(data);
301                 var dataArray = ddata.split("&");
302                 var input;
303                 this.requestParams = new Array();
304                 for (var i=0; i<dataArray.length; i++) {
305                     var nameValue = dataArray[i].split("=");
306                     if (nameValue[0] === this.context.namingContainerPrefix + "javax.faces.source" ||
307                         nameValue[0] === this.context.namingContainerPrefix + "javax.faces.partial.event" ||
308                         nameValue[0] === this.context.namingContainerPrefix + "javax.faces.partial.execute" ||
309                         nameValue[0] === this.context.namingContainerPrefix + "javax.faces.partial.render" ||
310                         nameValue[0] === this.context.namingContainerPrefix + "javax.faces.partial.ajax" ||
311                         nameValue[0] === this.context.namingContainerPrefix + "javax.faces.behavior.event") {
312                         input = document.createElement("input");
313                         input.setAttribute("type", "hidden");
314                         input.setAttribute("id", nameValue[0]);
315                         input.setAttribute("name", nameValue[0]);
316                         input.setAttribute("value", nameValue[1]);
317                         this.context.form.appendChild(input);
318                         this.requestParams.push(nameValue[0]);
319                     }
320                 }
321                 this.requestParams.push(this.FRAME_PARTIAL_ID);
322                 this.context.form.submit();
323             },
324             
325             /**
326              *@ignore
327              */
328             abort:function() {
329                 this.aborted = true; 
330             },
331             
332             /**
333              *@ignore
334              */
335             onreadystatechange:function(evt) {
336                 
337             },
338             
339             /**
340              * Extracts response from iframe document, sets readystate.
341              * @ignore
342              */
343             callback: function() {
344                 if (this.aborted) {
345                     return;
346                 }
347                 var iFrameDoc;
348                 var docBody;
349                 try {
350                     var evt = {};
351                     iFrameDoc = this.frame.contentWindow.document || 
352                         this.frame.contentDocument || this.frame.document;
353                     docBody = iFrameDoc.body || iFrameDoc.documentElement;
354                     this.responseText = docBody.innerHTML;
355                     this.responseXML = iFrameDoc.XMLDocument || iFrameDoc;
356                     this.status = 201;
357                     this.readyState = 4;  
358 
359                     this.onreadystatechange(evt);                
360                 } finally {
361                     this.cleanupReqParams();
362                 }               
363             },
364             
365             /**
366              *@ignore
367              */
368             cleanupReqParams: function() {
369                 for (var i=0; i<this.requestParams.length; i++) {
370                     var elements = this.context.form.childNodes;
371                     for (var j=0; j<elements.length; j++) {
372                         if (!elements[j].type === "hidden") {
373                             continue;
374                         }
375                         if (elements[j].name === this.requestParams[i]) {
376                             var node = this.context.form.removeChild(elements[j]);
377                             node = null;                           
378                             break;
379                         }
380                     }   
381                 }
382             }
383         };
384         
385        
386         /**
387          *Utility function that binds function to scope.
388          *@ignore
389          */
390         var bind = function(scope, fn) {
391             return function () {
392                 fn.apply(scope, arguments);
393             };
394         };
395 
396         /**
397          * Utility function that determines if a file control exists
398          * for the form.
399          * @ignore
400          */
401         var hasInputFileControl = function(form) {
402             var returnVal = false;
403             var inputs = form.getElementsByTagName("input");
404             if (inputs !== null && typeof inputs !=="undefined") {
405                 for (var i=0; i<inputs.length; i++) {
406                     if (inputs[i].type === "file") {
407                         returnVal = true;
408                         break;
409                     }
410                 }    
411             }
412             return returnVal;
413         };
414         
415         /**
416          * Find instance of passed String via getElementById
417          * @ignore
418          */
419         var $ = function $() {
420             var results = [], element;
421             for (var i = 0; i < arguments.length; i++) {
422                 element = arguments[i];
423                 if (typeof element == 'string') {
424                     element = document.getElementById(element);
425                 }
426                 results.push(element);
427             }
428             return results.length > 1 ? results : results[0];
429         };
430 
431         /**
432          * Get the form element which encloses the supplied element.
433          * @param element - element to act against in search
434          * @returns form element representing enclosing form, or first form if none found.
435          * @ignore
436          */
437         var getForm = function getForm(element) {
438             if (element) {
439                 var form = $(element);
440                 while (form) {
441 
442                     if (form.nodeName && (form.nodeName.toLowerCase() == 'form')) {
443                         return form;
444                     }
445                     if (form.form) {
446                         return form.form;
447                     }
448                     if (form.parentNode) {
449                         form = form.parentNode;
450                     } else {
451                         form = null;
452                     }
453                 }
454                 return document.forms[0];
455             }
456             return null;
457         };
458 
459         /**
460          * Get an array of all JSF form elements which need their view state to be updated.
461          * This covers at least the form that submitted the request and any form that is covered in the render target list.
462          * 
463          * @param context An object containing the request context, including the following properties:
464          * the source element, per call onerror callback function, per call onevent callback function, the render
465          * instructions, the submitting form ID, the naming container ID and naming container prefix.
466          * @ignore
467          */
468         var getFormsToUpdate = function getFormsToUpdate(context) {
469             var formsToUpdate = [];
470 
471             var add = function(element) {
472                 if (element) {
473                     if (element.nodeName 
474                         && element.nodeName.toLowerCase() == "form" 
475                         && element.method == "post" 
476                         && element.id 
477                         && element.elements 
478                         && element.id.indexOf(context.namingContainerPrefix) == 0)
479                     {
480                         formsToUpdate.push(element);
481                     }
482                     else {
483                         var forms = element.getElementsByTagName("form");
484     
485                         for (var i = 0; i < forms.length; i++) {
486                             add(forms[i]);
487                         }
488                     }
489                 }
490             }
491 
492             if (context.formId) {
493                 add(document.getElementById(context.formId));
494             }
495 
496             if (context.render) {
497                 if (context.render.indexOf("@all") >= 0) {
498                     add(document);
499                 }
500                 else {
501                     var clientIds = context.render.split(" ");
502 
503                     for (var i = 0; i < clientIds.length; i++) {
504                         if (clientIds.hasOwnProperty(i)) {
505                             add(document.getElementById(clientIds[i]));
506                         }
507                     }
508                 }
509             }
510 
511             return formsToUpdate;
512         }
513 
514         /**
515          * <p>Namespace given space separated parameters if necessary (only
516          * call this if there is a namingContainerPrefix!).  This
517          * function is here for backwards compatibility with manual
518          * jsf.ajax.request() calls written before Spec790 changes.</p>
519 
520          * @param parameters Spaceseparated string of parameters as
521          * usually specified in f:ajax execute and render attributes.
522 
523          * @param sourceClientId The client ID of the f:ajax
524          * source. This is to be used for prefixing relative target
525          * client IDs.
526 
527          * It's expected that this already starts with
528          * namingContainerPrefix.
529 
530          * @param namingContainerPrefix The naming container prefix (the
531          * view root ID suffixed with separator character).
532 
533          * This is to be used for prefixing absolute target client IDs.
534          * @ignore
535          */
536         var namespaceParametersIfNecessary = function namespaceParametersIfNecessary(parameters, sourceClientId, namingContainerPrefix) {
537             if (sourceClientId.indexOf(namingContainerPrefix) != 0) {
538                 return parameters; // Unexpected source client ID; let's silently do nothing.
539             }
540 
541             var targetClientIds = parameters.replace(/^\s+|\s+$/g, '').split(/\s+/g);
542 
543             for (var i = 0; i < targetClientIds.length; i++) {
544                 var targetClientId = targetClientIds[i];
545 
546                 if (targetClientId.indexOf(jsf.separatorchar) == 0) {
547                     targetClientId = targetClientId.substring(1);
548 
549                     if (targetClientId.indexOf(namingContainerPrefix) != 0) {
550                         targetClientId = namingContainerPrefix + targetClientId;
551                     }
552                 }
553                 else if (targetClientId.indexOf(namingContainerPrefix) != 0) {
554                     var parentClientId = sourceClientId.substring(0, sourceClientId.lastIndexOf(jsf.separatorchar));
555 
556                     if (namingContainerPrefix + targetClientId == parentClientId) {
557                         targetClientId = parentClientId;
558                     }
559                     else {
560                         targetClientId = parentClientId + jsf.separatorchar + targetClientId;
561                     }
562                 }
563 
564                 targetClientIds[i] = targetClientId;
565             }
566 
567             return targetClientIds.join(' ');
568         };
569 
570         /**
571          * Check if a value exists in an array
572          * @ignore
573          */
574         var isInArray = function isInArray(array, value) {
575             for (var i = 0; i < array.length; i++) {
576                 if (array[i] === value) {
577                     return true;
578                 }
579             }
580             return false;
581         };
582 
583 
584         /**
585          * Evaluate JavaScript code in a global context.
586          * @param src JavaScript code to evaluate
587          * @ignore
588          */
589         var globalEval = function globalEval(src) {
590             if (window.execScript) {
591                 window.execScript(src);
592                 return;
593             }
594             // We have to wrap the call in an anon function because of a firefox bug, where this is incorrectly set
595             // We need to explicitly call window.eval because of a Chrome peculiarity
596             /**
597              * @ignore
598              */
599             var fn = function() {
600                 window.eval.call(window,src);
601             };
602             fn();
603         };
604 
605         /**
606          * Get all scripts from supplied string, return them as an array for later processing.
607          * @param str
608          * @returns {array} of script text
609          * @ignore
610          */
611         var stripScripts = function stripScripts(str) {
612             // Regex to find all scripts in a string
613             var findscripts = /<script[^>]*>([\S\s]*?)<\/script>/igm;
614             // Regex to find one script, to isolate it's content [2] and attributes [1]
615             var findscript = /<script([^>]*)>([\S\s]*?)<\/script>/im;
616             // Regex to find type attribute
617             var findtype = /type="([\S]*?)"/im;
618             var initialnodes = [];
619             var scripts = [];
620             initialnodes = str.match(findscripts);
621             while (!!initialnodes && initialnodes.length > 0) {
622                 var scriptStr = [];
623                 scriptStr = initialnodes.shift().match(findscript);
624                 // check the type - skip if it not javascript type
625                 var type = [];
626                 type = scriptStr[1].match(findtype);
627                 if ( !!type && type[1]) {
628                     if (type[1] !== "text/javascript") {
629                         continue;
630                     }
631                 }
632                 scripts.push(scriptStr);
633             }
634             return scripts;
635         };
636 
637         /**
638          * Run an array of script nodes,
639          * @param scripts Array of script nodes.
640          * @ignore
641          */
642         var runScripts = function runScripts(scripts) {
643             if (!scripts || scripts.length === 0) {
644                 return;
645             }
646 
647             var loadedScripts = document.getElementsByTagName("script");
648             var loadedScriptUrls = [];
649 
650             for (var i = 0; i < loadedScripts.length; i++) {
651                 var scriptNode = loadedScripts[i];
652                 var url = scriptNode.getAttribute("src");
653 
654                 if (url) {
655                     loadedScriptUrls.push(url);
656                 }
657             }
658 
659             var head = document.head || document.getElementsByTagName('head')[0] || document.documentElement;
660             runScript(head, loadedScriptUrls, scripts, 0);
661         };
662 
663         /**
664          * Run script at given index.
665          * @param head Document's head.
666          * @param loadedScriptUrls URLs of scripts which are already loaded.
667          * @param scripts Array of script nodes.
668          * @param index Index of script to be loaded.
669          * @ignore
670          */
671         var runScript = function runScript(head, loadedScriptUrls, scripts, index) {
672             if (index >= scripts.length) {
673                 return;
674             }
675 
676             // Regex to find src attribute
677             var findsrc = /src="([\S]*?)"/im;
678             // Regex to remove leading cruft
679             var stripStart = /^\s*(<!--)*\s*(\/\/)*\s*(\/\*)*\s*\n*\**\n*\s*\*.*\n*\s*\*\/(<!\[CDATA\[)*/;
680 
681             var scriptStr = scripts[index];
682             var src = scriptStr[1].match(findsrc);
683             var scriptLoadedViaUrl = false;
684 
685             if (!!src && src[1]) {
686                 // if this is a file, load it
687                 var url = src[1];
688                 // if this is already loaded, don't load it
689                 // it's never necessary, and can make debugging difficult
690                 if (loadedScriptUrls.indexOf(url) < 0) {
691                     // create script node
692                     var scriptNode = document.createElement('script');
693                     var parserElement = document.createElement('div');
694                     parserElement.innerHTML = scriptStr[0];
695                     cloneAttributes(scriptNode, parserElement.firstChild);
696                     deleteNode(parserElement);
697                     scriptNode.type = 'text/javascript';
698                     scriptNode.src = url; // add the src to the script node
699                     scriptNode.onload = scriptNode.onreadystatechange = function(_, abort) {
700                         if (abort || !scriptNode.readyState || /loaded|complete/.test(scriptNode.readyState)) {
701                             scriptNode.onload = scriptNode.onreadystatechange = null; // IE memory leak fix.
702                             scriptNode = null;
703                             runScript(head, loadedScriptUrls, scripts, index + 1); // Run next script.
704                         }
705                     };
706                     head.insertBefore(scriptNode, null); // add it to end of the head (and don't remove it)
707                     scriptLoadedViaUrl = true;
708                 }
709             } else if (!!scriptStr && scriptStr[2]) {
710                 // else get content of tag, without leading CDATA and such
711                 var script = scriptStr[2].replace(stripStart,"");
712 
713                 if (!!script) {
714                     // create script node
715                     var scriptNode = document.createElement('script');
716                     scriptNode.type = 'text/javascript';
717                     scriptNode.text = script; // add the code to the script node
718                     head.appendChild(scriptNode); // add it to the head
719                     head.removeChild(scriptNode); // then remove it
720                 }
721             }
722 
723             if (!scriptLoadedViaUrl) {
724                 runScript(head, loadedScriptUrls, scripts, index + 1); // Run next script.
725             }
726         };
727 
728         /**
729          * Get all stylesheets from supplied string and run them all.
730          * @param str
731          * @ignore
732          */
733         var stripAndRunStylesheets = function stripAndRunStylesheets(str) {
734             // Regex to find all links in a string
735             var findlinks = /<link[^>]*\/>/igm;
736             // Regex to find one link, to isolate its attributes [1]
737             var findlink = /<link([^>]*)\/>/im;
738             // Regex to find type attribute
739             var findtype = /type="([\S]*?)"/im;
740             var findhref = /href="([\S]*?)"/im;
741 
742             var stylesheets = [];
743             var loadedStylesheetUrls = null;
744             var head = document.head || document.getElementsByTagName('head')[0] || document.documentElement;
745             var parserElement = null;
746 
747             var initialnodes = str.match(findlinks);
748             while (!!initialnodes && initialnodes.length > 0) {
749                 var linkStr = initialnodes.shift().match(findlink);
750                 // check the type - skip if it not css type
751                 var type = linkStr[1].match(findtype);
752                 if (!type || type[1] !== "text/css") {
753                     continue;
754                 }
755                 var href = linkStr[1].match(findhref);
756                 if (!!href && href[1]) {
757                     if (loadedStylesheetUrls === null) {
758                         var loadedLinks = document.getElementsByTagName("link");
759                         loadedStylesheetUrls = [];
760 
761                         for (var i = 0; i < loadedLinks.length; i++) {
762                             var linkNode = loadedLinks[i];
763                             
764                             if (linkNode.getAttribute("type") === "text/css") {
765                                 var url = linkNode.getAttribute("href");
766 
767                                 if (url) {
768                                     loadedStylesheetUrls.push(url);
769                                 }
770                             }
771                         }
772                     }
773 
774                     var url = href[1];
775 
776                     if (loadedStylesheetUrls.indexOf(url) < 0) {
777                         // create stylesheet node
778                         parserElement = parserElement !== null ? parserElement : document.createElement('div');
779                         parserElement.innerHTML = linkStr[0];
780                         var linkNode = parserElement.firstChild;
781                         linkNode.type = 'text/css';
782                         linkNode.rel = 'stylesheet';
783                         linkNode.href = url;
784                         head.insertBefore(linkNode, null); // add it to end of the head (and don't remove it)
785                     }
786                 }
787             }
788 
789             deleteNode(parserElement);
790         };
791 
792         /**
793          * Replace DOM element with a new tagname and supplied innerHTML
794          * @param element element to replace
795          * @param tempTagName new tag name to replace with
796          * @param src string new content for element
797          * @ignore
798          */
799         var elementReplaceStr = function elementReplaceStr(element, tempTagName, src) {
800 
801             var temp = document.createElement(tempTagName);
802             if (element.id) {
803                 temp.id = element.id;
804             }
805 
806             // Creating a head element isn't allowed in IE, and faulty in most browsers,
807             // so it is not allowed
808             if (element.nodeName.toLowerCase() === "head") {
809                 throw new Error("Attempted to replace a head element - this is not allowed.");
810             } else {
811                 var scripts = [];
812                 if (isAutoExec()) {
813                     temp.innerHTML = src;
814                 } else {
815                     // Get scripts from text
816                     scripts = stripScripts(src);
817                     // Remove scripts from text
818                     src = src.replace(/<script[^>]*type="text\/javascript"*>([\S\s]*?)<\/script>/igm,"");
819                     temp.innerHTML = src;
820                 }
821             }
822 
823             replaceNode(temp, element);            
824             cloneAttributes(temp, element);
825             runScripts(scripts);
826 
827         };
828 
829         /**
830          * Get a string with the concatenated values of all string nodes under the given node
831          * @param  oNode the given DOM node
832          * @param  deep boolean - whether to recursively scan the children nodes of the given node for text as well. Default is <code>false</code>
833          * @ignore
834          * Note:  This code originally from Sarissa: http://dev.abiss.gr/sarissa
835          * It has been modified to fit into the overall codebase
836          */
837         var getText = function getText(oNode, deep) {
838             var Node = {ELEMENT_NODE: 1, ATTRIBUTE_NODE: 2, TEXT_NODE: 3, CDATA_SECTION_NODE: 4,
839                 ENTITY_REFERENCE_NODE: 5,  ENTITY_NODE: 6, PROCESSING_INSTRUCTION_NODE: 7,
840                 COMMENT_NODE: 8, DOCUMENT_NODE: 9, DOCUMENT_TYPE_NODE: 10,
841                 DOCUMENT_FRAGMENT_NODE: 11, NOTATION_NODE: 12};
842 
843             var s = "";
844             var nodes = oNode.childNodes;
845             for (var i = 0; i < nodes.length; i++) {
846                 var node = nodes[i];
847                 var nodeType = node.nodeType;
848                 if (nodeType == Node.TEXT_NODE || nodeType == Node.CDATA_SECTION_NODE) {
849                     s += node.data;
850                 } else if (deep === true && (nodeType == Node.ELEMENT_NODE ||
851                                              nodeType == Node.DOCUMENT_NODE ||
852                                              nodeType == Node.DOCUMENT_FRAGMENT_NODE)) {
853                     s += getText(node, true);
854                 }
855             }
856             return s;
857         };
858 
859         var PARSED_OK = "Document contains no parsing errors";
860         var PARSED_EMPTY = "Document is empty";
861         var PARSED_UNKNOWN_ERROR = "Not well-formed or other error";
862         var getParseErrorText;
863         if (isIE()) {
864             /**
865              * Note: This code orginally from Sarissa: http://dev.abiss.gr/sarissa
866              * @ignore
867              */
868             getParseErrorText = function (oDoc) {
869                 var parseErrorText = PARSED_OK;
870                 if (oDoc && oDoc.parseError && oDoc.parseError.errorCode && oDoc.parseError.errorCode !== 0) {
871                     parseErrorText = "XML Parsing Error: " + oDoc.parseError.reason +
872                                      "\nLocation: " + oDoc.parseError.url +
873                                      "\nLine Number " + oDoc.parseError.line + ", Column " +
874                                      oDoc.parseError.linepos +
875                                      ":\n" + oDoc.parseError.srcText +
876                                      "\n";
877                     for (var i = 0; i < oDoc.parseError.linepos; i++) {
878                         parseErrorText += "-";
879                     }
880                     parseErrorText += "^\n";
881                 }
882                 else if (oDoc.documentElement === null) {
883                     parseErrorText = PARSED_EMPTY;
884                 }
885                 return parseErrorText;
886             };
887         } else { // (non-IE)
888 
889             /**
890              * <p>Returns a human readable description of the parsing error. Useful
891              * for debugging. Tip: append the returned error string in a <pre>
892              * element if you want to render it.</p>
893              * @param  oDoc The target DOM document
894              * @returns {String} The parsing error description of the target Document in
895              *          human readable form (preformated text)
896              * @ignore
897              * Note:  This code orginally from Sarissa: http://dev.abiss.gr/sarissa
898              */
899             getParseErrorText = function (oDoc) {
900                 var parseErrorText = PARSED_OK;
901                 if ((!oDoc) || (!oDoc.documentElement)) {
902                     parseErrorText = PARSED_EMPTY;
903                 } else if (oDoc.documentElement.tagName == "parsererror") {
904                     parseErrorText = oDoc.documentElement.firstChild.data;
905                     parseErrorText += "\n" + oDoc.documentElement.firstChild.nextSibling.firstChild.data;
906                 } else if (oDoc.getElementsByTagName("parsererror").length > 0) {
907                     var parsererror = oDoc.getElementsByTagName("parsererror")[0];
908                     parseErrorText = getText(parsererror, true) + "\n";
909                 } else if (oDoc.parseError && oDoc.parseError.errorCode !== 0) {
910                     parseErrorText = PARSED_UNKNOWN_ERROR;
911                 }
912                 return parseErrorText;
913             };
914         }
915 
916         if ((typeof(document.importNode) == "undefined") && isIE()) {
917             try {
918                 /**
919                  * Implementation of importNode for the context window document in IE.
920                  * If <code>oNode</code> is a TextNode, <code>bChildren</code> is ignored.
921                  * @param oNode the Node to import
922                  * @param bChildren whether to include the children of oNode
923                  * @returns the imported node for further use
924                  * @ignore
925                  * Note:  This code orginally from Sarissa: http://dev.abiss.gr/sarissa
926                  */
927                 document.importNode = function(oNode, bChildren) {
928                     var tmp;
929                     if (oNode.nodeName == '#text') {
930                         return document.createTextNode(oNode.data);
931                     }
932                     else {
933                         if (oNode.nodeName == "tbody" || oNode.nodeName == "tr") {
934                             tmp = document.createElement("table");
935                         }
936                         else if (oNode.nodeName == "td") {
937                             tmp = document.createElement("tr");
938                         }
939                         else if (oNode.nodeName == "option") {
940                             tmp = document.createElement("select");
941                         }
942                         else {
943                             tmp = document.createElement("div");
944                         }
945                         if (bChildren) {
946                             tmp.innerHTML = oNode.xml ? oNode.xml : oNode.outerHTML;
947                         } else {
948                             tmp.innerHTML = oNode.xml ? oNode.cloneNode(false).xml : oNode.cloneNode(false).outerHTML;
949                         }
950                         return tmp.getElementsByTagName("*")[0];
951                     }
952                 };
953             } catch(e) {
954             }
955         }
956         // Setup Node type constants for those browsers that don't have them (IE)
957         var Node = {ELEMENT_NODE: 1, ATTRIBUTE_NODE: 2, TEXT_NODE: 3, CDATA_SECTION_NODE: 4,
958             ENTITY_REFERENCE_NODE: 5,  ENTITY_NODE: 6, PROCESSING_INSTRUCTION_NODE: 7,
959             COMMENT_NODE: 8, DOCUMENT_NODE: 9, DOCUMENT_TYPE_NODE: 10,
960             DOCUMENT_FRAGMENT_NODE: 11, NOTATION_NODE: 12};
961 
962         // PENDING - add support for removing handlers added via DOM 2 methods
963         /**
964          * Delete all events attached to a node
965          * @param node
966          * @ignore
967          */
968         var clearEvents = function clearEvents(node) {
969             if (!node) {
970                 return;
971             }
972 
973             // don't do anything for text and comment nodes - unnecessary
974             if (node.nodeType == Node.TEXT_NODE || node.nodeType == Node.COMMENT_NODE) {
975                 return;
976             }
977 
978             var events = ['abort', 'blur', 'change', 'error', 'focus', 'load', 'reset', 'resize', 'scroll', 'select', 'submit', 'unload',
979             'keydown', 'keypress', 'keyup', 'click', 'mousedown', 'mousemove', 'mouseout', 'mouseover', 'mouseup', 'dblclick' ];
980             try {
981                 for (var e in events) {
982                     if (events.hasOwnProperty(e)) {
983                         node[e] = null;
984                     }
985                 }
986             } catch (ex) {
987                 // it's OK if it fails, at least we tried
988             }
989         };
990 
991         /**
992          * Determine if this current browser is IE9 or greater
993          * @param node
994          * @ignore
995          */
996         var isIE9Plus = function isIE9Plus() {
997             var iev = getIEVersion();
998             if (iev >= 9) {
999                 return true;
1000             } else {
1001                 return false;
1002             }
1003         }
1004 
1005 
1006         /**
1007          * Deletes node
1008          * @param node
1009          * @ignore
1010          */
1011         var deleteNode = function deleteNode(node) {
1012             if (!node) {
1013                 return;
1014             }
1015             if (!node.parentNode) {
1016                 // if there's no parent, there's nothing to do
1017                 return;
1018             }
1019             if (!isIE() || (isIE() && isIE9Plus())) {
1020                 // nothing special required
1021                 node.parentNode.removeChild(node);
1022                 return;
1023             }
1024             // The rest of this code is specialcasing for IE
1025             if (node.nodeName.toLowerCase() === "body") {
1026                 // special case for removing body under IE.
1027                 deleteChildren(node);
1028                 try {
1029                     node.outerHTML = '';
1030                 } catch (ex) {
1031                     // fails under some circumstances, but not in RI
1032                     // supplied responses.  If we've gotten here, it's
1033                     // fairly safe to leave a lingering body tag rather than
1034                     // fail outright
1035                 }
1036                 return;
1037             }
1038             var temp = node.ownerDocument.createElement('div');
1039             var parent = node.parentNode;
1040             temp.appendChild(parent.removeChild(node));
1041             // Now clean up the temporary element
1042             try {
1043                 temp.outerHTML = ''; //prevent leak in IE
1044             } catch (ex) {
1045                 // at least we tried.  Fails in some circumstances,
1046                 // but not in RI supplied responses.  Better to leave a lingering
1047                 // temporary div than to fail outright.
1048             }
1049         };
1050 
1051         /**
1052          * Deletes all children of a node
1053          * @param node
1054          * @ignore
1055          */
1056         var deleteChildren = function deleteChildren(node) {
1057             if (!node) {
1058                 return;
1059             }
1060             for (var x = node.childNodes.length - 1; x >= 0; x--) { //delete all of node's children
1061                 var childNode = node.childNodes[x];
1062                 deleteNode(childNode);
1063             }
1064         };
1065 
1066         /**
1067          * <p> Copies the childNodes of nodeFrom to nodeTo</p>
1068          *
1069          * @param  nodeFrom the Node to copy the childNodes from
1070          * @param  nodeTo the Node to copy the childNodes to
1071          * @ignore
1072          * Note:  This code originally from Sarissa:  http://dev.abiss.gr/sarissa
1073          * It has been modified to fit into the overall codebase
1074          */
1075         var copyChildNodes = function copyChildNodes(nodeFrom, nodeTo) {
1076 
1077             if ((!nodeFrom) || (!nodeTo)) {
1078                 throw "Both source and destination nodes must be provided";
1079             }
1080 
1081             deleteChildren(nodeTo);
1082             var nodes = nodeFrom.childNodes;
1083             // if within the same doc, just move, else copy and delete
1084             if (nodeFrom.ownerDocument == nodeTo.ownerDocument) {
1085                 while (nodeFrom.firstChild) {
1086                     nodeTo.appendChild(nodeFrom.firstChild);
1087                 }
1088             } else {
1089                 var ownerDoc = nodeTo.nodeType == Node.DOCUMENT_NODE ? nodeTo : nodeTo.ownerDocument;
1090                 var i;
1091                 if (typeof(ownerDoc.importNode) != "undefined") {
1092                     for (i = 0; i < nodes.length; i++) {
1093                         nodeTo.appendChild(ownerDoc.importNode(nodes[i], true));
1094                     }
1095                 } else {
1096                     for (i = 0; i < nodes.length; i++) {
1097                         nodeTo.appendChild(nodes[i].cloneNode(true));
1098                     }
1099                 }
1100             }
1101         };
1102 
1103 
1104         /**
1105          * Replace one node with another.  Necessary for handling IE memory leak.
1106          * @param node
1107          * @param newNode
1108          * @ignore
1109          */
1110         var replaceNode = function replaceNode(newNode, node) {
1111                if(isIE()){
1112                     node.parentNode.insertBefore(newNode, node);
1113                     deleteNode(node);
1114                } else {
1115                     node.parentNode.replaceChild(newNode, node);
1116                }
1117         };
1118 
1119         /**
1120          * @ignore
1121          */
1122         var propertyToAttribute = function propertyToAttribute(name) {
1123             if (name === 'className') {
1124                 return 'class';
1125             } else if (name === 'xmllang') {
1126                 return 'xml:lang';
1127             } else {
1128                 return name.toLowerCase();
1129             }
1130         };
1131 
1132         /**
1133          * @ignore
1134          */
1135         var isFunctionNative = function isFunctionNative(func) {
1136             return /^\s*function[^{]+{\s*\[native code\]\s*}\s*$/.test(String(func));
1137         };
1138 
1139         /**
1140          * @ignore
1141          */
1142         var detectAttributes = function detectAttributes(element) {
1143             //test if 'hasAttribute' method is present and its native code is intact
1144             //for example, Prototype can add its own implementation if missing
1145             if (element.hasAttribute && isFunctionNative(element.hasAttribute)) {
1146                 return function(name) {
1147                     return element.hasAttribute(name);
1148                 }
1149             } else {
1150                 try {
1151                     //when accessing .getAttribute method without arguments does not throw an error then the method is not available
1152                     element.getAttribute;
1153 
1154                     var html = element.outerHTML;
1155                     var startTag = html.match(/^<[^>]*>/)[0];
1156                     return function(name) {
1157                         return startTag.indexOf(name + '=') > -1;
1158                     }
1159                 } catch (ex) {
1160                     return function(name) {
1161                         return element.getAttribute(name);
1162                     }
1163                 }
1164             }
1165         };
1166 
1167         /**
1168          * copy all attributes from one element to another - except id
1169          * @param target element to copy attributes to
1170          * @param source element to copy attributes from
1171          * @ignore
1172          */
1173         var cloneAttributes = function cloneAttributes(target, source) {
1174 
1175             // enumerate core element attributes - without 'dir' as special case
1176             var coreElementProperties = ['className', 'title', 'lang', 'xmllang'];
1177             // enumerate additional input element attributes
1178             var inputElementProperties = [
1179                 'name', 'value', 'size', 'maxLength', 'src', 'alt', 'useMap', 'tabIndex', 'accessKey', 'accept', 'type'
1180             ];
1181             // enumerate additional boolean input attributes
1182             var inputElementBooleanProperties = [
1183                 'checked', 'disabled', 'readOnly'
1184             ];
1185 
1186             // Enumerate all the names of the event listeners
1187             var listenerNames =
1188                 [ 'onclick', 'ondblclick', 'onmousedown', 'onmousemove', 'onmouseout',
1189                     'onmouseover', 'onmouseup', 'onkeydown', 'onkeypress', 'onkeyup',
1190                     'onhelp', 'onblur', 'onfocus', 'onchange', 'onload', 'onunload', 'onabort',
1191                     'onreset', 'onselect', 'onsubmit'
1192                 ];
1193 
1194             var sourceAttributeDetector = detectAttributes(source);
1195             var targetAttributeDetector = detectAttributes(target);
1196 
1197             var isInputElement = target.nodeName.toLowerCase() === 'input';
1198             var propertyNames = isInputElement ? coreElementProperties.concat(inputElementProperties) : coreElementProperties;
1199             var isXML = !source.ownerDocument.contentType || source.ownerDocument.contentType == 'text/xml';
1200             for (var iIndex = 0, iLength = propertyNames.length; iIndex < iLength; iIndex++) {
1201                 var propertyName = propertyNames[iIndex];
1202                 var attributeName = propertyToAttribute(propertyName);
1203                 if (sourceAttributeDetector(attributeName)) {
1204                 
1205                     //With IE 7 (quirks or standard mode) and IE 8/9 (quirks mode only), 
1206                     //you cannot get the attribute using 'class'. You must use 'className'
1207                     //which is the same value you use to get the indexed property. The only 
1208                     //reliable way to detect this (without trying to evaluate the browser
1209                     //mode and version) is to compare the two return values using 'className' 
1210                     //to see if they exactly the same.  If they are, then use the property
1211                     //name when using getAttribute.
1212                     if( attributeName == 'class'){
1213                         if( isIE() && (source.getAttribute(propertyName) === source[propertyName]) ){
1214                             attributeName = propertyName;
1215                         }
1216                     }
1217 
1218                     var newValue = isXML ? source.getAttribute(attributeName) : source[propertyName];
1219                     var oldValue = target[propertyName];
1220                     if (oldValue != newValue) {
1221                         target[propertyName] = newValue;
1222                     }
1223                 } else {
1224                     //setting property to '' seems to be the only cross-browser method for removing an attribute
1225                     //avoid setting 'value' property to '' for checkbox and radio input elements because then the
1226                     //'value' is used instead of the 'checked' property when the form is serialized by the browser
1227                     if (attributeName == "value" && (target.type != 'checkbox' && target.type != 'radio')) {
1228                          target[propertyName] = '';
1229                     }
1230                     target.removeAttribute(attributeName);
1231                 }
1232             }
1233 
1234             var booleanPropertyNames = isInputElement ? inputElementBooleanProperties : [];
1235             for (var jIndex = 0, jLength = booleanPropertyNames.length; jIndex < jLength; jIndex++) {
1236                 var booleanPropertyName = booleanPropertyNames[jIndex];
1237                 var newBooleanValue = source[booleanPropertyName];
1238                 var oldBooleanValue = target[booleanPropertyName];
1239                 if (oldBooleanValue != newBooleanValue) {
1240                     target[booleanPropertyName] = newBooleanValue;
1241                 }
1242             }
1243 
1244             //'style' attribute special case
1245             if (sourceAttributeDetector('style')) {
1246                 var newStyle;
1247                 var oldStyle;
1248                 if (isIE()) {
1249                     newStyle = source.style.cssText;
1250                     oldStyle = target.style.cssText;
1251                     if (newStyle != oldStyle) {
1252                         target.style.cssText = newStyle;
1253                     }
1254                 } else {
1255                     newStyle = source.getAttribute('style');
1256                     oldStyle = target.getAttribute('style');
1257                     if (newStyle != oldStyle) {
1258                         target.setAttribute('style', newStyle);
1259                     }
1260                 }
1261             } else if (targetAttributeDetector('style')){
1262                 target.removeAttribute('style');
1263             }
1264 
1265             // Special case for 'dir' attribute
1266             if (!isIE() && source.dir != target.dir) {
1267                 if (sourceAttributeDetector('dir')) {
1268                     target.dir = source.dir;
1269                 } else if (targetAttributeDetector('dir')) {
1270                     target.dir = '';
1271                 }
1272             }
1273 
1274             for (var lIndex = 0, lLength = listenerNames.length; lIndex < lLength; lIndex++) {
1275                 var name = listenerNames[lIndex];
1276                 target[name] = source[name] ? source[name] : null;
1277                 if (source[name]) {
1278                     source[name] = null;
1279                 }
1280             }
1281 
1282             //clone HTML5 data-* attributes
1283             try{
1284                 var targetDataset = target.dataset;
1285                 var sourceDataset = source.dataset;
1286                 if (targetDataset || sourceDataset) {
1287                     //cleanup the dataset
1288                     for (var tp in targetDataset) {
1289                         delete targetDataset[tp];
1290                     }
1291                     //copy dataset's properties
1292                     for (var sp in sourceDataset) {
1293                         targetDataset[sp] = sourceDataset[sp];
1294                     }
1295                 }
1296             } catch (ex) {
1297                 //most probably dataset properties are not supported
1298             }
1299         };
1300 
1301         /**
1302          * Replace an element from one document into another
1303          * @param newElement new element to put in document
1304          * @param origElement original element to replace
1305          * @ignore
1306          */
1307         var elementReplace = function elementReplace(newElement, origElement) {
1308             copyChildNodes(newElement, origElement);
1309             // sadly, we have to reparse all over again
1310             // to reregister the event handlers and styles
1311             // PENDING do some performance tests on large pages
1312             origElement.innerHTML = origElement.innerHTML;
1313 
1314             try {
1315                 cloneAttributes(origElement, newElement);
1316             } catch (ex) {
1317                 // if in dev mode, report an error, else try to limp onward
1318                 if (jsf.getProjectStage() == "Development") {
1319                     throw new Error("Error updating attributes");
1320                 }
1321             }
1322             deleteNode(newElement);
1323 
1324         };
1325 
1326         /**
1327          * Create a new document, then select the body element within it
1328          * @param docStr Stringified version of document to create
1329          * @return element the body element
1330          * @ignore
1331          */
1332         var getBodyElement = function getBodyElement(docStr) {
1333 
1334             var doc;  // intermediate document we'll create
1335             var body; // Body element to return
1336 
1337             if (typeof DOMParser !== "undefined") {  // FF, S, Chrome
1338                 doc = (new DOMParser()).parseFromString(docStr, "text/xml");
1339             } else if (typeof ActiveXObject !== "undefined") { // IE
1340                 doc = new ActiveXObject("MSXML2.DOMDocument");
1341                 doc.loadXML(docStr);
1342             } else {
1343                 throw new Error("You don't seem to be running a supported browser");
1344             }
1345 
1346             if (getParseErrorText(doc) !== PARSED_OK) {
1347                 throw new Error(getParseErrorText(doc));
1348             }
1349 
1350             body = doc.getElementsByTagName("body")[0];
1351 
1352             if (!body) {
1353                 throw new Error("Can't find body tag in returned document.");
1354             }
1355 
1356             return body;
1357         };
1358 
1359         /**
1360          * Find encoded url field for a given form.
1361          * @param form
1362          * @ignore
1363          */
1364         var getEncodedUrlElement = function getEncodedUrlElement(form) {
1365             var encodedUrlElement = form['javax.faces.encodedURL'];
1366 
1367             if (encodedUrlElement) {
1368                 return encodedUrlElement;
1369             } else {
1370                 var formElements = form.elements;
1371                 for (var i = 0, length = formElements.length; i < length; i++) {
1372                     var formElement = formElements[i];
1373                     if (formElement.name && (formElement.name.indexOf('javax.faces.encodedURL') >= 0)) {
1374                         return formElement;
1375                     }
1376                 }
1377             }
1378 
1379             return undefined;
1380         };
1381 
1382         /**
1383          * Update hidden state fields from the server into the DOM for any JSF forms which need to be updated.
1384          * This covers at least the form that submitted the request and any form that is covered in the render target list.
1385          * 
1386          * @param updateElement The update element of partial response holding the state value.
1387          * @param context An object containing the request context, including the following properties:
1388          * the source element, per call onerror callback function, per call onevent callback function, the render
1389          * instructions, the submitting form ID, the naming container ID and naming container prefix.
1390          * @param hiddenStateFieldName The hidden state field name, e.g. javax.faces.ViewState or javax.faces.ClientWindow 
1391          * @ignore
1392          */
1393         var updateHiddenStateFields = function updateHiddenStateFields(updateElement, context, hiddenStateFieldName) {
1394             var firstChild = updateElement.firstChild;
1395             var state = (typeof firstChild.wholeText !== 'undefined') ? firstChild.wholeText : firstChild.nodeValue;
1396             var formsToUpdate = getFormsToUpdate(context);
1397 
1398             for (var i = 0; i < formsToUpdate.length; i++) {
1399                 var formToUpdate = formsToUpdate[i];
1400                 var field = getHiddenStateField(formToUpdate, hiddenStateFieldName, context.namingContainerPrefix);
1401                 if (typeof field == "undefined") {
1402                     field = document.createElement("input");
1403                     field.type = "hidden";
1404                     field.name = context.namingContainerPrefix + hiddenStateFieldName;
1405                     formToUpdate.appendChild(field);
1406                 }
1407                 field.value = state;
1408             }
1409         }
1410 
1411         /**
1412          * Find hidden state field for a given form.
1413          * @param form The form to find hidden state field in.
1414          * @param hiddenStateFieldName The hidden state field name, e.g. javax.faces.ViewState or javax.faces.ClientWindow 
1415          * @param namingContainerPrefix The naming container prefix, if any (the view root ID suffixed with separator character).
1416          * @ignore
1417          */
1418         var getHiddenStateField = function getHiddenStateField(form, hiddenStateFieldName, namingContainerPrefix) {
1419             namingContainerPrefix = namingContainerPrefix || "";
1420             var field = form[namingContainerPrefix + hiddenStateFieldName];
1421 
1422             if (field) {
1423                 return field;
1424             }
1425             else {
1426                 var formElements = form.elements;
1427 
1428                 for (var i = 0, length = formElements.length; i < length; i++) {
1429                     var formElement = formElements[i];
1430 
1431                     if (formElement.name && (formElement.name.indexOf(hiddenStateFieldName) >= 0)) {
1432                         return formElement;
1433                     }
1434                 }
1435             }
1436 
1437             return undefined;
1438         };
1439 
1440         /**
1441          * Do update.
1442          * @param updateElement The update element of partial response.
1443          * @param context An object containing the request context, including the following properties:
1444          * the source element, per call onerror callback function, per call onevent callback function, the render
1445          * instructions, the submitting form ID, the naming container ID and naming container prefix.
1446          * @ignore
1447          */
1448         var doUpdate = function doUpdate(updateElement, context) {
1449             var id, content, markup;
1450             var scripts = []; // temp holding value for array of script nodes
1451 
1452             id = updateElement.getAttribute('id');
1453             var viewStateRegex = new RegExp(context.namingContainerPrefix + "javax.faces.ViewState" + jsf.separatorchar + ".+$");
1454             var windowIdRegex = new RegExp(context.namingContainerPrefix + "javax.faces.ClientWindow" + jsf.separatorchar + ".+$");
1455 
1456             if (id.match(viewStateRegex)) {
1457                 updateHiddenStateFields(updateElement, context, "javax.faces.ViewState");
1458                 return;
1459             } else if (id.match(windowIdRegex)) {
1460                 updateHiddenStateFields(updateElement, context, "javax.faces.ClientWindow");
1461                 return;
1462             }
1463 
1464             // join the CDATA sections in the markup
1465             markup = '';
1466             for (var j = 0; j < updateElement.childNodes.length; j++) {
1467                 content = updateElement.childNodes[j];
1468                 markup += content.nodeValue;
1469             }
1470 
1471             var src = markup;
1472 
1473             // If our special render all markup is present..
1474             if (id === "javax.faces.ViewRoot" || id === "javax.faces.ViewBody") {
1475 
1476                 // spec790: If UIViewRoot is currently being updated,
1477                 // then it means that ajax navigation has taken place.
1478                 // So, ensure that context.render has correct value for this condition,
1479                 // because this is not necessarily correclty specified during the request.
1480                 context.render = "@all";
1481 
1482                 var bodyStartEx = new RegExp("< *body[^>]*>", "gi");
1483                 var bodyEndEx = new RegExp("< */ *body[^>]*>", "gi");
1484                 var newsrc;
1485 
1486                 var docBody = document.getElementsByTagName("body")[0];
1487                 var bodyStart = bodyStartEx.exec(src);
1488 
1489                 if (bodyStart !== null) { // replace body tag
1490                     // First, try with XML manipulation
1491                     try {
1492                         // Get scripts from text
1493                         scripts = stripScripts(src);
1494                         // Remove scripts from text
1495                         newsrc = src.replace(/<script[^>]*type="text\/javascript"*>([\S\s]*?)<\/script>/igm, "");
1496                         elementReplace(getBodyElement(newsrc), docBody);
1497                         runScripts(scripts);
1498                     } catch (e) {
1499                         // OK, replacing the body didn't work with XML - fall back to quirks mode insert
1500                         var srcBody, bodyEnd;
1501                         // if src contains </body>
1502                         bodyEnd = bodyEndEx.exec(src);
1503                         if (bodyEnd !== null) {
1504                             srcBody = src.substring(bodyStartEx.lastIndex, bodyEnd.index);
1505                         } else { // can't find the </body> tag, punt
1506                             srcBody = src.substring(bodyStartEx.lastIndex);
1507                         }
1508                         // replace body contents with innerHTML - note, script handling happens within function
1509                         elementReplaceStr(docBody, "body", srcBody);
1510 
1511                     }
1512 
1513                 } else {  // replace body contents with innerHTML - note, script handling happens within function
1514                     elementReplaceStr(docBody, "body", src);
1515                 }
1516             } else if (id === "javax.faces.ViewHead") {
1517                 throw new Error("javax.faces.ViewHead not supported - browsers cannot reliably replace the head's contents");
1518             } else if (id === "javax.faces.Resource") {
1519                 stripAndRunStylesheets(src);
1520                 scripts = stripScripts(src);
1521                 runScripts(scripts);
1522             } else {
1523                 var element = $(id);
1524                 if (!element) {
1525                     throw new Error("During update: " + id + " not found");
1526                 }
1527 
1528                 if (context.namingContainerId && id == context.namingContainerId) {
1529                     // spec790: If UIViewRoot is a NamingContainer and this is currently being updated,
1530                     // then it means that ajax navigation has taken place.
1531                     // So, ensure that context.render has correct value for this condition,
1532                     // because this is not necessarily correclty specified during the request.
1533                     context.render = context.namingContainerId;
1534                 }
1535 
1536                 var parent = element.parentNode;
1537                 // Trim space padding before assigning to innerHTML
1538                 var html = src.replace(/^\s+/g, '').replace(/\s+$/g, '');
1539                 var parserElement = document.createElement('div');
1540                 var tag = element.nodeName.toLowerCase();
1541                 var tableElements = ['td', 'th', 'tr', 'tbody', 'thead', 'tfoot'];
1542                 var isInTable = false;
1543                 for (var tei = 0, tel = tableElements.length; tei < tel; tei++) {
1544                     if (tableElements[tei] == tag) {
1545                         isInTable = true;
1546                         break;
1547                     }
1548                 }
1549                 if (isInTable) {
1550 
1551                     if (isAutoExec()) {
1552                         // Create html
1553                         parserElement.innerHTML = '<table>' + html + '</table>';
1554                     } else {
1555                         // Get the scripts from the text
1556                         scripts = stripScripts(html);
1557                         // Remove scripts from text
1558                         html = html.replace(/<script[^>]*type="text\/javascript"*>([\S\s]*?)<\/script>/igm,"");
1559                         parserElement.innerHTML = '<table>' + html + '</table>';
1560                     }
1561                     var newElement = parserElement.firstChild;
1562                     //some browsers will also create intermediary elements such as table>tbody>tr>td
1563                     while ((null !== newElement) && (id !== newElement.id)) {
1564                         newElement = newElement.firstChild;
1565                     }
1566                     parent.replaceChild(newElement, element);
1567                     runScripts(scripts);
1568                 } else if (element.nodeName.toLowerCase() === 'input') {
1569                     // special case handling for 'input' elements
1570                     // in order to not lose focus when updating,
1571                     // input elements need to be added in place.
1572                     parserElement = document.createElement('div');
1573                     parserElement.innerHTML = html;
1574                     newElement = parserElement.firstChild;
1575 
1576                     cloneAttributes(element, newElement);
1577                     deleteNode(parserElement);
1578                 } else if (html.length > 0) {
1579                     if (isAutoExec()) {
1580                         // Create html
1581                         parserElement.innerHTML = html;
1582                     } else {
1583                         // Get the scripts from the text
1584                         scripts = stripScripts(html);
1585                         // Remove scripts from text
1586                         html = html.replace(/<script[^>]*type="text\/javascript"*>([\S\s]*?)<\/script>/igm,"");
1587                         parserElement.innerHTML = html;
1588                     }
1589                     replaceNode(parserElement.firstChild, element);
1590                     deleteNode(parserElement);
1591                     runScripts(scripts);
1592                 }
1593             }
1594         };
1595 
1596         /**
1597          * Delete a node specified by the element.
1598          * @param element
1599          * @ignore
1600          */
1601         var doDelete = function doDelete(element) {
1602             var id = element.getAttribute('id');
1603             var target = $(id);
1604             deleteNode(target);
1605         };
1606 
1607         /**
1608          * Insert a node specified by the element.
1609          * @param element
1610          * @ignore
1611          */
1612         var doInsert = function doInsert(element) {
1613             var tablePattern = new RegExp("<\\s*(td|th|tr|tbody|thead|tfoot)", "i");
1614             var scripts = [];
1615             var target = $(element.firstChild.getAttribute('id'));
1616             var parent = target.parentNode;
1617             var html = element.firstChild.firstChild.nodeValue;
1618             var isInTable = tablePattern.test(html);
1619 
1620             if (!isAutoExec())  {
1621                 // Get the scripts from the text
1622                 scripts = stripScripts(html);
1623                 // Remove scripts from text
1624                 html = html.replace(/<script[^>]*type="text\/javascript"*>([\S\s]*?)<\/script>/igm,"");
1625             }
1626             var tempElement = document.createElement('div');
1627             var newElement = null;
1628             if (isInTable)  {
1629                 tempElement.innerHTML = '<table>' + html + '</table>';
1630                 newElement = tempElement.firstChild;
1631                 //some browsers will also create intermediary elements such as table>tbody>tr>td
1632                 //test for presence of id on the new element since we do not have it directly
1633                 while ((null !== newElement) && ("" == newElement.id)) {
1634                     newElement = newElement.firstChild;
1635                 }
1636             } else {
1637                 tempElement.innerHTML = html;
1638                 newElement = tempElement.firstChild;
1639             }
1640 
1641             if (element.firstChild.nodeName === 'after') {
1642                 // Get the next in the list, to insert before
1643                 target = target.nextSibling;
1644             }  // otherwise, this is a 'before' element
1645             if (!!tempElement.innerHTML) { // check if only scripts were inserted - if so, do nothing here
1646                 parent.insertBefore(newElement, target);
1647             }
1648             runScripts(scripts);
1649             deleteNode(tempElement);
1650         };
1651 
1652         /**
1653          * Modify attributes of given element id.
1654          * @param element
1655          * @ignore
1656          */
1657         var doAttributes = function doAttributes(element) {
1658 
1659             // Get id of element we'll act against
1660             var id = element.getAttribute('id');
1661 
1662             var target = $(id);
1663 
1664             if (!target) {
1665                 throw new Error("The specified id: " + id + " was not found in the page.");
1666             }
1667 
1668             // There can be multiple attributes modified.  Loop through the list.
1669             var nodes = element.childNodes;
1670             for (var i = 0; i < nodes.length; i++) {
1671                 var name = nodes[i].getAttribute('name');
1672                 var value = nodes[i].getAttribute('value');
1673 
1674                 //boolean attribute handling code for all browsers
1675                 if (name === 'disabled') {
1676                     target.disabled = value === 'disabled' || value === 'true';
1677                     return;
1678                 } else if (name === 'checked') {
1679                     target.checked = value === 'checked' || value === 'on' || value === 'true';
1680                     return;
1681                 } else if (name == 'readonly') {
1682                     target.readOnly = value === 'readonly' || value === 'true';
1683                     return;
1684                 }
1685 
1686                 if (!isIE()) {
1687                     if (name === 'value') {
1688                         target.value = value;
1689                     } else {
1690                         target.setAttribute(name, value);
1691                     }
1692                 } else { // if it's IE, then quite a bit more work is required
1693                     if (name === 'class') {
1694                         target.className = value;
1695                     } else if (name === "for") {
1696                         name = 'htmlFor';
1697                         target.setAttribute(name, value, 0);
1698                     } else if (name === 'style') {
1699                         target.style.setAttribute('cssText', value, 0);
1700                     } else if (name.substring(0, 2) === 'on') {
1701                         var c = document.body.appendChild(document.createElement('span'));
1702                         try {
1703                             c.innerHTML = '<span ' + name + '="' + value + '"/>';
1704                             target[name] = c.firstChild[name];
1705                         } finally {
1706                             document.body.removeChild(c);
1707                         }
1708                     } else if (name === 'dir') {
1709                         if (jsf.getProjectStage() == 'Development') {
1710                             throw new Error("Cannot set 'dir' attribute in IE");
1711                         }
1712                     } else {
1713                         target.setAttribute(name, value, 0);
1714                     }
1715                 }
1716             }
1717         };
1718 
1719         /**
1720          * Eval the CDATA of the element.
1721          * @param element to eval
1722          * @ignore
1723          */
1724         var doEval = function doEval(element) {
1725             var evalText = '';
1726             var childNodes = element.childNodes;
1727             for (var i = 0; i < childNodes.length; i++) {
1728                 evalText += childNodes[i].nodeValue;
1729             }
1730             globalEval(evalText);
1731         };
1732 
1733         /**
1734          * Ajax Request Queue
1735          * @ignore
1736          */
1737         var Queue = new function Queue() {
1738 
1739             // Create the internal queue
1740             var queue = [];
1741 
1742 
1743             // the amount of space at the front of the queue, initialised to zero
1744             var queueSpace = 0;
1745 
1746             /** Returns the size of this Queue. The size of a Queue is equal to the number
1747              * of elements that have been enqueued minus the number of elements that have
1748              * been dequeued.
1749              * @ignore
1750              */
1751             this.getSize = function getSize() {
1752                 return queue.length - queueSpace;
1753             };
1754 
1755             /** Returns true if this Queue is empty, and false otherwise. A Queue is empty
1756              * if the number of elements that have been enqueued equals the number of
1757              * elements that have been dequeued.
1758              * @ignore
1759              */
1760             this.isEmpty = function isEmpty() {
1761                 return (queue.length === 0);
1762             };
1763 
1764             /** Enqueues the specified element in this Queue.
1765              *
1766              * @param element - the element to enqueue
1767              * @ignore
1768              */
1769             this.enqueue = function enqueue(element) {
1770                 // Queue the request
1771                 queue.push(element);
1772             };
1773 
1774 
1775             /** Dequeues an element from this Queue. The oldest element in this Queue is
1776              * removed and returned. If this Queue is empty then undefined is returned.
1777              *
1778              * @returns Object The element that was removed from the queue.
1779              * @ignore
1780              */
1781             this.dequeue = function dequeue() {
1782                 // initialise the element to return to be undefined
1783                 var element = undefined;
1784 
1785                 // check whether the queue is empty
1786                 if (queue.length) {
1787                     // fetch the oldest element in the queue
1788                     element = queue[queueSpace];
1789 
1790                     // update the amount of space and check whether a shift should occur
1791                     if (++queueSpace * 2 >= queue.length) {
1792                         // set the queue equal to the non-empty portion of the queue
1793                         queue = queue.slice(queueSpace);
1794                         // reset the amount of space at the front of the queue
1795                         queueSpace = 0;
1796                     }
1797                 }
1798                 // return the removed element
1799                 try {
1800                     return element;
1801                 } finally {
1802                     element = null; // IE 6 leak prevention
1803                 }
1804             };
1805 
1806             /** Returns the oldest element in this Queue. If this Queue is empty then
1807              * undefined is returned. This function returns the same value as the dequeue
1808              * function, but does not remove the returned element from this Queue.
1809              * @ignore
1810              */
1811             this.getOldestElement = function getOldestElement() {
1812                 // initialise the element to return to be undefined
1813                 var element = undefined;
1814 
1815                 // if the queue is not element then fetch the oldest element in the queue
1816                 if (queue.length) {
1817                     element = queue[queueSpace];
1818                 }
1819                 // return the oldest element
1820                 try {
1821                     return element;
1822                 } finally {
1823                     element = null; //IE 6 leak prevention
1824                 }
1825             };
1826         }();
1827 
1828 
1829         /**
1830          * AjaxEngine handles Ajax implementation details.
1831          * @ignore
1832          */
1833         var AjaxEngine = function AjaxEngine(context) {
1834 
1835             var req = {};                  // Request Object
1836             req.url = null;                // Request URL
1837             req.context = context;              // Context of request and response
1838             req.context.sourceid = null;   // Source of this request
1839             req.context.onerror = null;    // Error handler for request
1840             req.context.onevent = null;    // Event handler for request
1841             req.context.namingContainerId = null;   // If UIViewRoot is an instance of NamingContainer this represents its ID.
1842             req.context.namingContainerPrefix = null;   // If UIViewRoot is an instance of NamingContainer this represents its ID suffixed with separator character, else an empty string.
1843             req.xmlReq = null;             // XMLHttpRequest Object
1844             req.async = true;              // Default - Asynchronous
1845             req.parameters = {};           // Parameters For GET or POST
1846             req.queryString = null;        // Encoded Data For GET or POST
1847             req.method = null;             // GET or POST
1848             req.status = null;             // Response Status Code From Server
1849             req.fromQueue = false;         // Indicates if the request was taken off the queue before being sent. This prevents the request from entering the queue redundantly.
1850 
1851             req.que = Queue;
1852             
1853             // Get a transport Handle
1854             // The transport will be an iframe transport if the form
1855             // has multipart encoding type.  This is where we could
1856             // handle XMLHttpRequest Level2 as well (perhaps 
1857             // something like:  if ('upload' in req.xmlReq)'
1858             req.xmlReq = getTransport(context);
1859 
1860             if (req.xmlReq === null) {
1861                 return null;
1862             }
1863 
1864             /**
1865              * @ignore
1866              */
1867             function noop() {}
1868             
1869             // Set up request/response state callbacks
1870             /**
1871              * @ignore
1872              */
1873             req.xmlReq.onreadystatechange = function() {
1874                 if (req.xmlReq.readyState === 4) {
1875                     req.onComplete();
1876                     // next two lines prevent closure/ciruclar reference leaks
1877                     // of XHR instances in IE
1878                     req.xmlReq.onreadystatechange = noop;
1879                     req.xmlReq = null;
1880                 }
1881             };
1882 
1883             /**
1884              * This function is called when the request/response interaction
1885              * is complete.  If the return status code is successfull,
1886              * dequeue all requests from the queue that have completed.  If a
1887              * request has been found on the queue that has not been sent,
1888              * send the request.
1889              * @ignore
1890              */
1891             req.onComplete = function onComplete() {
1892                 if (req.xmlReq.status && (req.xmlReq.status >= 200 && req.xmlReq.status < 300)) {
1893                     sendEvent(req.xmlReq, req.context, "complete");
1894                     jsf.ajax.response(req.xmlReq, req.context);
1895                 } else {
1896                     sendEvent(req.xmlReq, req.context, "complete");
1897                     sendError(req.xmlReq, req.context, "httpError");
1898                 }
1899 
1900                 // Regardless of whether the request completed successfully (or not),
1901                 // dequeue requests that have been completed (readyState 4) and send
1902                 // requests that ready to be sent (readyState 0).
1903 
1904                 var nextReq = req.que.getOldestElement();
1905                 if (nextReq === null || typeof nextReq === 'undefined') {
1906                     return;
1907                 }
1908                 while ((typeof nextReq.xmlReq !== 'undefined' && nextReq.xmlReq !== null) &&
1909                        nextReq.xmlReq.readyState === 4) {
1910                     req.que.dequeue();
1911                     nextReq = req.que.getOldestElement();
1912                     if (nextReq === null || typeof nextReq === 'undefined') {
1913                         break;
1914                     }
1915                 }
1916                 if (nextReq === null || typeof nextReq === 'undefined') {
1917                     return;
1918                 }
1919                 if ((typeof nextReq.xmlReq !== 'undefined' && nextReq.xmlReq !== null) &&
1920                     nextReq.xmlReq.readyState === 0) {
1921                     nextReq.fromQueue = true;
1922                     nextReq.sendRequest();
1923                 }
1924             };
1925 
1926             /**
1927              * Utility method that accepts additional arguments for the AjaxEngine.
1928              * If an argument is passed in that matches an AjaxEngine property, the
1929              * argument value becomes the value of the AjaxEngine property.
1930              * Arguments that don't match AjaxEngine properties are added as
1931              * request parameters.
1932              * @ignore
1933              */
1934             req.setupArguments = function(args) {
1935                 for (var i in args) {
1936                     if (args.hasOwnProperty(i)) {
1937                         if (typeof req[i] === 'undefined') {
1938                             req.parameters[i] = args[i];
1939                         } else {
1940                             req[i] = args[i];
1941                         }
1942                     }
1943                 }
1944             };
1945 
1946             /**
1947              * This function does final encoding of parameters, determines the request method
1948              * (GET or POST) and sends the request using the specified url.
1949              * @ignore
1950              */
1951             req.sendRequest = function() {
1952                 if (req.xmlReq !== null) {
1953                     // if there is already a request on the queue waiting to be processed..
1954                     // just queue this request
1955                     if (!req.que.isEmpty()) {
1956                         if (!req.fromQueue) {
1957                             req.que.enqueue(req);
1958                             return;
1959                         }
1960                     }
1961                     // If the queue is empty, queue up this request and send
1962                     if (!req.fromQueue) {
1963                         req.que.enqueue(req);
1964                     }
1965                     // Some logic to get the real request URL
1966                     if (req.generateUniqueUrl && req.method == "GET") {
1967                         req.parameters["AjaxRequestUniqueId"] = new Date().getTime() + "" + req.requestIndex;
1968                     }
1969                     var content = null; // For POST requests, to hold query string
1970                     for (var i in req.parameters) {
1971                         if (req.parameters.hasOwnProperty(i)) {
1972                             if (req.queryString.length > 0) {
1973                                 req.queryString += "&";
1974                             }
1975                             req.queryString += encodeURIComponent(i) + "=" + encodeURIComponent(req.parameters[i]);
1976                         }
1977                     }
1978                     if (req.method === "GET") {
1979                         if (req.queryString.length > 0) {
1980                             req.url += ((req.url.indexOf("?") > -1) ? "&" : "?") + req.queryString;
1981                         }
1982                     }
1983                     req.xmlReq.open(req.method, req.url, req.async);
1984                     // note that we are including the charset=UTF-8 as part of the content type (even
1985                     // if encodeURIComponent encodes as UTF-8), because with some
1986                     // browsers it will not be set in the request.  Some server implementations need to 
1987                     // determine the character encoding from the request header content type.
1988                     if (req.method === "POST") {
1989                         if (typeof req.xmlReq.setRequestHeader !== 'undefined') {
1990                             req.xmlReq.setRequestHeader('Faces-Request', 'partial/ajax');
1991                             req.xmlReq.setRequestHeader('Content-type', 'application/x-www-form-urlencoded;charset=UTF-8');
1992                         }
1993                         content = req.queryString;
1994                     }
1995                     // note that async == false is not a supported feature.  We may change it in ways
1996                     // that break existing programs at any time, with no warning.
1997                     if(!req.async) {
1998                         req.xmlReq.onreadystatechange = null; // no need for readystate change listening
1999                     }
2000                     sendEvent(req.xmlReq, req.context, "begin");
2001                     req.xmlReq.send(content);
2002                     if(!req.async){
2003                         req.onComplete();
2004                 }
2005                 }
2006             };
2007 
2008             return req;
2009         };
2010 
2011         /**
2012          * Error handling callback.
2013          * Assumes that the request has completed.
2014          * @ignore
2015          */
2016         var sendError = function sendError(request, context, status, description, serverErrorName, serverErrorMessage) {
2017 
2018             // Possible errornames:
2019             // httpError
2020             // emptyResponse
2021             // serverError
2022             // malformedXML
2023 
2024             var sent = false;
2025             var data = {};  // data payload for function
2026             data.type = "error";
2027             data.status = status;
2028             data.source = context.sourceid;
2029             data.responseCode = request.status;
2030             data.responseXML = request.responseXML;
2031             data.responseText = request.responseText;
2032 
2033             // ensure data source is the dom element and not the ID
2034             // per 14.4.1 of the 2.0 specification.
2035             if (typeof data.source === 'string') {
2036                 data.source = document.getElementById(data.source);
2037             }
2038 
2039             if (description) {
2040                 data.description = description;
2041             } else if (status == "httpError") {
2042                 if (data.responseCode === 0) {
2043                     data.description = "The Http Transport returned a 0 status code.  This is usually the result of mixing ajax and full requests.  This is usually undesired, for both performance and data integrity reasons.";
2044                 } else {
2045                     data.description = "There was an error communicating with the server, status: " + data.responseCode;
2046                 }
2047             } else if (status == "serverError") {
2048                 data.description = serverErrorMessage;
2049             } else if (status == "emptyResponse") {
2050                 data.description = "An empty response was received from the server.  Check server error logs.";
2051             } else if (status == "malformedXML") {
2052                 if (getParseErrorText(data.responseXML) !== PARSED_OK) {
2053                     data.description = getParseErrorText(data.responseXML);
2054                 } else {
2055                     data.description = "An invalid XML response was received from the server.";
2056                 }
2057             }
2058 
2059             if (status == "serverError") {
2060                 data.errorName = serverErrorName;
2061                 data.errorMessage = serverErrorMessage;
2062             }
2063 
2064             // If we have a registered callback, send the error to it.
2065             if (context.onerror) {
2066                 context.onerror.call(null, data);
2067                 sent = true;
2068             }
2069 
2070             for (var i in errorListeners) {
2071                 if (errorListeners.hasOwnProperty(i)) {
2072                     errorListeners[i].call(null, data);
2073                     sent = true;
2074                 }
2075             }
2076 
2077             if (!sent && jsf.getProjectStage() === "Development") {
2078                 if (status == "serverError") {
2079                     alert("serverError: " + serverErrorName + " " + serverErrorMessage);
2080                 } else {
2081                     alert(status + ": " + data.description);
2082                 }
2083             }
2084         };
2085 
2086         /**
2087          * Event handling callback.
2088          * Request is assumed to have completed, except in the case of event = 'begin'.
2089          * @ignore
2090          */
2091         var sendEvent = function sendEvent(request, context, status) {
2092 
2093             var data = {};
2094             data.type = "event";
2095             data.status = status;
2096             data.source = context.sourceid;
2097             // ensure data source is the dom element and not the ID
2098             // per 14.4.1 of the 2.0 specification.
2099             if (typeof data.source === 'string') {
2100                 data.source = document.getElementById(data.source);
2101             }
2102             if (status !== 'begin') {
2103                 data.responseCode = request.status;
2104                 data.responseXML = request.responseXML;
2105                 data.responseText = request.responseText;
2106             }
2107 
2108             if (context.onevent) {
2109                 context.onevent.call(null, data);
2110             }
2111 
2112             for (var i in eventListeners) {
2113                 if (eventListeners.hasOwnProperty(i)) {
2114                     eventListeners[i].call(null, data);
2115                 }
2116             }
2117         };
2118 
2119         // Use module pattern to return the functions we actually expose
2120         return {
2121             /**
2122              * Register a callback for error handling.
2123              * <p><b>Usage:</b></p>
2124              * <pre><code>
2125              * jsf.ajax.addOnError(handleError);
2126              * ...
2127              * var handleError = function handleError(data) {
2128              * ...
2129              * }
2130              * </pre></code>
2131              * <p><b>Implementation Requirements:</b></p>
2132              * This function must accept a reference to an existing JavaScript function.
2133              * The JavaScript function reference must be added to a list of callbacks, making it possible
2134              * to register more than one callback by invoking <code>jsf.ajax.addOnError</code>
2135              * more than once.  This function must throw an error if the <code>callback</code>
2136              * argument is not a function.
2137              *
2138              * @member jsf.ajax
2139              * @param callback a reference to a function to call on an error
2140              */
2141             addOnError: function addOnError(callback) {
2142                 if (typeof callback === 'function') {
2143                     errorListeners[errorListeners.length] = callback;
2144                 } else {
2145                     throw new Error("jsf.ajax.addOnError:  Added a callback that was not a function.");
2146                 }
2147             },
2148             /**
2149              * Register a callback for event handling.
2150              * <p><b>Usage:</b></p>
2151              * <pre><code>
2152              * jsf.ajax.addOnEvent(statusUpdate);
2153              * ...
2154              * var statusUpdate = function statusUpdate(data) {
2155              * ...
2156              * }
2157              * </pre></code>
2158              * <p><b>Implementation Requirements:</b></p>
2159              * This function must accept a reference to an existing JavaScript function.
2160              * The JavaScript function reference must be added to a list of callbacks, making it possible
2161              * to register more than one callback by invoking <code>jsf.ajax.addOnEvent</code>
2162              * more than once.  This function must throw an error if the <code>callback</code>
2163              * argument is not a function.
2164              *
2165              * @member jsf.ajax
2166              * @param callback a reference to a function to call on an event
2167              */
2168             addOnEvent: function addOnEvent(callback) {
2169                 if (typeof callback === 'function') {
2170                     eventListeners[eventListeners.length] = callback;
2171                 } else {
2172                     throw new Error("jsf.ajax.addOnEvent: Added a callback that was not a function");
2173                 }
2174             },
2175             /**
2176 
2177              * <p><span class="changed_modified_2_2">Send</span> an
2178              * asynchronous Ajax req uest to the server.
2179 
2180              * <p><b>Usage:</b></p>
2181              * <pre><code>
2182              * Example showing all optional arguments:
2183              *
2184              * <commandButton id="button1" value="submit"
2185              *     onclick="jsf.ajax.request(this,event,
2186              *       {execute:'button1',render:'status',onevent: handleEvent,onerror: handleError});return false;"/>
2187              * </commandButton/>
2188              * </pre></code>
2189              * <p><b>Implementation Requirements:</b></p>
2190              * This function must:
2191              * <ul>
2192              * <li>Be used within the context of a <code>form</code><span class="changed_added_2_3">,
2193              * else throw an error</span>.</li>
2194              * <li>Capture the element that triggered this Ajax request
2195              * (from the <code>source</code> argument, also known as the
2196              * <code>source</code> element.</li>
2197              * <li>If the <code>source</code> element is <code>null</code> or
2198              * <code>undefined</code> throw an error.</li>
2199              * <li>If the <code>source</code> argument is not a <code>string</code> or
2200              * DOM element object, throw an error.</li>
2201              * <li>If the <code>source</code> argument is a <code>string</code>, find the
2202              * DOM element for that <code>string</code> identifier.
2203              * <li>If the DOM element could not be determined, throw an error.</li>
2204              * <li class="changed_added_2_3">If the <code>javax.faces.ViewState</code> 
2205              * element could not be found, throw an error.</li>
2206              * <li class="changed_added_2_3">If the ID of the <code>javax.faces.ViewState</code> 
2207              * element has a <code><VIEW_ROOT_CONTAINER_CLIENT_ID><SEP></code>
2208              * prefix, where <SEP> is the currently configured
2209              * <code>UINamingContainer.getSeparatorChar()</code> and
2210              * <VIEW_ROOT_CONTAINER_CLIENT_ID> is the return from
2211              * <code>UIViewRoot.getContainerClientId()</code> on the
2212              * view from whence this state originated, then remember it as <i>namespace prefix</i>.
2213              * This is needed during encoding of the set of post data arguments.</li>
2214              * <li>If the <code>onerror</code> and <code>onevent</code> arguments are set,
2215              * they must be functions, or throw an error.
2216              * <li>Determine the <code>source</code> element's <code>form</code>
2217              * element.</li>
2218              * <li>Get the <code>form</code> view state by calling
2219              * {@link jsf.getViewState} passing the
2220              * <code>form</code> element as the argument.</li>
2221              * <li>Collect post data arguments for the Ajax request.
2222              * <ul>
2223              * <li>The following name/value pairs are required post data arguments:
2224              * <table border="1">
2225              * <tr>
2226              * <th>name</th>
2227              * <th>value</th>
2228              * </tr>
2229              * <tr>
2230              * <td><code>javax.faces.ViewState</code></td>
2231              * <td><code>Contents of javax.faces.ViewState hidden field.  This is included when
2232              * {@link jsf.getViewState} is used.</code></td>
2233              * </tr>
2234              * <tr>
2235              * <td><code>javax.faces.partial.ajax</code></td>
2236              * <td><code>true</code></td>
2237              * </tr>
2238              * <tr>
2239              * <td><code>javax.faces.source</code></td>
2240              * <td><code>The identifier of the element that triggered this request.</code></td>
2241              * </tr>
2242              * <tr class="changed_added_2_2">
2243              * <td><code>javax.faces.ClientWindow</code></td>
2244 
2245              * <td><code>Call jsf.getClientWindow(), passing the current
2246              * form.  If the return is non-null, it must be set as the
2247              * value of this name/value pair, otherwise, a name/value
2248              * pair for client window must not be sent.</code></td>
2249 
2250              * </tr>
2251              * </table>
2252              * </li>
2253              * </ul>
2254              * </li>
2255              * <li>Collect optional post data arguments for the Ajax request.
2256              * <ul>
2257              * <li>Determine additional arguments (if any) from the <code>options</code>
2258              * argument. If <code>options.execute</code> exists:
2259              * <ul>
2260              * <li>If the keyword <code>@none</code> is present, do not create and send
2261              * the post data argument <code>javax.faces.partial.execute</code>.</li>
2262              * <li>If the keyword <code>@all</code> is present, create the post data argument with
2263              * the name <code>javax.faces.partial.execute</code> and the value <code>@all</code>.</li>
2264              * <li>Otherwise, there are specific identifiers that need to be sent.  Create the post
2265              * data argument with the name <code>javax.faces.partial.execute</code> and the value as a
2266              * space delimited <code>string</code> of client identifiers.</li>
2267              * </ul>
2268              * </li>
2269              * <li>If <code>options.execute</code> does not exist, create the post data argument with the
2270              * name <code>javax.faces.partial.execute</code> and the value as the identifier of the
2271              * element that caused this request.</li>
2272              * <li>If <code>options.render</code> exists:
2273              * <ul>
2274              * <li>If the keyword <code>@none</code> is present, do not create and send
2275              * the post data argument <code>javax.faces.partial.render</code>.</li>
2276              * <li>If the keyword <code>@all</code> is present, create the post data argument with
2277              * the name <code>javax.faces.partial.render</code> and the value <code>@all</code>.</li>
2278              * <li>Otherwise, there are specific identifiers that need to be sent.  Create the post
2279              * data argument with the name <code>javax.faces.partial.render</code> and the value as a
2280              * space delimited <code>string</code> of client identifiers.</li>
2281              * </ul>
2282              * <li>If <code>options.render</code> does not exist do not create and send the
2283              * post data argument <code>javax.faces.partial.render</code>.</li>
2284 
2285              * <li class="changed_added_2_2">If
2286              * <code>options.delay</code> exists let it be the value
2287              * <em>delay</em>, for this discussion.  If
2288              * <code>options.delay</code> does not exist, or is the
2289              * literal string <code>'none'</code>, without the quotes,
2290              * no delay is used.  If less than <em>delay</em>
2291              * milliseconds elapses between calls to <em>request()</em>
2292              * only the most recent one is sent and all other requests
2293              * are discarded.</li>
2294 
2295 
2296              * <li class="changed_added_2_2">If
2297              * <code>options.resetValues</code> exists and its value is
2298              * <code>true</code>, ensure a post data argument with the
2299              * name <code>javax.faces.partial.resetValues</code> and the
2300              * value <code>true</code> is sent in addition to the other
2301              * post data arguments.  This will cause
2302              * <code>UIViewRoot.resetValues()</code> to be called,
2303              * passing the value of the "render" attribute.  Note: do
2304              * not use any of the <code>@</code> keywords such as
2305              * <code>@form</code> or <code>@this</code> with this option
2306              * because <code>UIViewRoot.resetValues()</code> does not
2307              * descend into the children of the listed components.</li>
2308 
2309 
2310              * <li>Determine additional arguments (if any) from the <code>event</code>
2311              * argument.  The following name/value pairs may be used from the
2312              * <code>event</code> object:
2313              * <ul>
2314              * <li><code>target</code> - the ID of the element that triggered the event.</li>
2315              * <li><code>captured</code> - the ID of the element that captured the event.</li>
2316              * <li><code>type</code> - the type of event (ex: onkeypress)</li>
2317              * <li><code>alt</code> - <code>true</code> if ALT key was pressed.</li>
2318              * <li><code>ctrl</code> - <code>true</code> if CTRL key was pressed.</li>
2319              * <li><code>shift</code> - <code>true</code> if SHIFT key was pressed. </li>
2320              * <li><code>meta</code> - <code>true</code> if META key was pressed. </li>
2321              * <li><code>right</code> - <code>true</code> if right mouse button
2322              * was pressed. </li>
2323              * <li><code>left</code> - <code>true</code> if left mouse button
2324              * was pressed. </li>
2325              * <li><code>keycode</code> - the key code.
2326              * </ul>
2327              * </li>
2328              * </ul>
2329              * </li>
2330              * <li>Encode the set of post data arguments. <span class="changed_added_2_3">
2331              * If the <code>javax.faces.ViewState</code> element has a namespace prefix, then
2332              * make sure that all post data arguments are prefixed with this namespace prefix.
2333              * </span></li>
2334              * <li>Join the encoded view state with the encoded set of post data arguments
2335              * to form the <code>query string</code> that will be sent to the server.</li>
2336              * <li>Create a request <code>context</code> object and set the properties:
2337              * <ul><li><code>source</code> (the source DOM element for this request)</li>
2338              * <li><code>onerror</code> (the error handler for this request)</li>
2339              * <li><code>onevent</code> (the event handler for this request)</li></ul>
2340              * The request context will be used during error/event handling.</li>
2341              * <li>Send a <code>begin</code> event following the procedure as outlined
2342              * in the Chapter 13 "Sending Events" section of the spec prose document <a
2343              *  href="../../javadocs/overview-summary.html#prose_document">linked in the
2344              *  overview summary</a></li>
2345              * <li>Set the request header with the name: <code>Faces-Request</code> and the
2346              * value: <code>partial/ajax</code>.</li>
2347              * <li>Determine the <code>posting URL</code> as follows: If the hidden field
2348              * <code>javax.faces.encodedURL</code> is present in the submitting form, use its
2349              * value as the <code>posting URL</code>.  Otherwise, use the <code>action</code>
2350              * property of the <code>form</code> element as the <code>URL</code>.</li>
2351 
2352              * <li> 
2353 
2354              * <p><span class="changed_modified_2_2">Determine whether
2355              * or not the submitting form is using 
2356              * <code>multipart/form-data</code> as its
2357              * <code>enctype</code> attribute.  If not, send the request
2358              * as an <code>asynchronous POST</code> using the
2359              * <code>posting URL</code> that was determined in the
2360              * previous step.</span> <span
2361              * class="changed_added_2_2">Otherwise, send the request
2362              * using a multi-part capable transport layer, such as a
2363              * hidden inline frame.  Note that using a hidden inline
2364              * frame does <strong>not</strong> use
2365              * <code>XMLHttpRequest</code>, but the request must be sent
2366              * with all the parameters that a JSF
2367              * <code>XMLHttpRequest</code> would have been sent with.
2368              * In this way, the server side processing of the request
2369              * will be identical whether or the request is multipart or
2370              * not.</span></p>
2371             
2372              * <div class="changed_added_2_2">
2373 
2374              * <p>The <code>begin</code>, <code>complete</code>, and
2375              * <code>success</code> events must be emulated when using
2376              * the multipart transport.  This allows any listeners to
2377              * behave uniformly regardless of the multipart or
2378              * <code>XMLHttpRequest</code> nature of the transport.</p>
2379 
2380              * </div></li>
2381              * </ul>
2382              * Form serialization should occur just before the request is sent to minimize 
2383              * the amount of time between the creation of the serialized form data and the 
2384              * sending of the serialized form data (in the case of long requests in the queue).
2385              * Before the request is sent it must be put into a queue to ensure requests
2386              * are sent in the same order as when they were initiated.  The request callback function
2387              * must examine the queue and determine the next request to be sent.  The behavior of the
2388              * request callback function must be as follows:
2389              * <ul>
2390              * <li>If the request completed successfully invoke {@link jsf.ajax.response}
2391              * passing the <code>request</code> object.</li>
2392              * <li>If the request did not complete successfully, notify the client.</li>
2393              * <li>Regardless of the outcome of the request (success or error) every request in the
2394              * queue must be handled.  Examine the status of each request in the queue starting from
2395              * the request that has been in the queue the longest.  If the status of the request is
2396              * <code>complete</code> (readyState 4), dequeue the request (remove it from the queue).
2397              * If the request has not been sent (readyState 0), send the request.  Requests that are
2398              * taken off the queue and sent should not be put back on the queue.</li>
2399              * </ul>
2400              *
2401              * </p>
2402              *
2403              * @param source The DOM element that triggered this Ajax request, or an id string of the
2404              * element to use as the triggering element.
2405              * @param event The DOM event that triggered this Ajax request.  The
2406              * <code>event</code> argument is optional.
2407              * @param options The set of available options that can be sent as
2408              * request parameters to control client and/or server side
2409              * request processing. Acceptable name/value pair options are:
2410              * <table border="1">
2411              * <tr>
2412              * <th>name</th>
2413              * <th>value</th>
2414              * </tr>
2415              * <tr>
2416              * <td><code>execute</code></td>
2417              * <td><code>space seperated list of client identifiers</code></td>
2418              * </tr>
2419              * <tr>
2420              * <td><code>render</code></td>
2421              * <td><code>space seperated list of client identifiers</code></td>
2422              * </tr>
2423              * <tr>
2424              * <td><code>onevent</code></td>
2425              * <td><code>function to callback for event</code></td>
2426              * </tr>
2427              * <tr>
2428              * <td><code>onerror</code></td>
2429              * <td><code>function to callback for error</code></td>
2430              * </tr>
2431              * <tr>
2432              * <td><code>params</code></td>
2433              * <td><code>object containing parameters to include in the request</code></td>
2434              * </tr>
2435 
2436              * <tr class="changed_added_2_2">
2437 
2438              * <td><code>delay</code></td>
2439 
2440              * <td>If less than <em>delay</em> milliseconds elapses
2441              * between calls to <em>request()</em> only the most recent
2442              * one is sent and all other requests are discarded. If the
2443              * value of <em>delay</em> is the literal string
2444              * <code>'none'</code> without the quotes, or no delay is
2445              * specified, no delay is used. </td>
2446 
2447              * </tr>
2448 
2449              * <tr class="changed_added_2_2">
2450 
2451              * <td><code>resetValues</code></td>
2452 
2453              * <td>If true, ensure a post data argument with the name
2454              * javax.faces.partial.resetValues and the value true is
2455              * sent in addition to the other post data arguments. This
2456              * will cause UIViewRoot.resetValues() to be called, passing
2457              * the value of the "render" attribute. Note: do not use any
2458              * of the @ keywords such as @form or @this with this option
2459              * because UIViewRoot.resetValues() does not descend into
2460              * the children of the listed components.</td>
2461 
2462              * </tr>
2463 
2464 
2465              * </table>
2466              * The <code>options</code> argument is optional.
2467              * @member jsf.ajax
2468              * @function jsf.ajax.request
2469 
2470              * @throws Error if first required argument
2471              * <code>element</code> is not specified, or if one or more
2472              * of the components in the <code>options.execute</code>
2473              * list is a file upload component, but the form's enctype
2474              * is not set to <code>multipart/form-data</code>
2475              */
2476 
2477             request: function request(source, event, options) {
2478 
2479                 var element, form, viewStateElement;   //  Element variables
2480                 var all, none;
2481                 
2482                 var context = {};
2483 
2484                 if (typeof source === 'undefined' || source === null) {
2485                     throw new Error("jsf.ajax.request: source not set");
2486                 }
2487                 if(delayHandler) {
2488                     clearTimeout(delayHandler);
2489                     delayHandler = null;
2490                 }
2491 
2492                 // set up the element based on source
2493                 if (typeof source === 'string') {
2494                     element = document.getElementById(source);
2495                 } else if (typeof source === 'object') {
2496                     element = source;
2497                 } else {
2498                     throw new Error("jsf.ajax.request: source must be object or string");
2499                 }
2500                 // attempt to handle case of name unset
2501                 // this might be true in a badly written composite component
2502                 if (!element.name) {
2503                     element.name = element.id;
2504                 }
2505                 
2506                 context.element = element;
2507 
2508                 if (typeof(options) === 'undefined' || options === null) {
2509                     options = {};
2510                 }
2511 
2512                 // Error handler for this request
2513                 var onerror = false;
2514 
2515                 if (options.onerror && typeof options.onerror === 'function') {
2516                     onerror = options.onerror;
2517                 } else if (options.onerror && typeof options.onerror !== 'function') {
2518                     throw new Error("jsf.ajax.request: Added an onerror callback that was not a function");
2519                 }
2520 
2521                 // Event handler for this request
2522                 var onevent = false;
2523 
2524                 if (options.onevent && typeof options.onevent === 'function') {
2525                     onevent = options.onevent;
2526                 } else if (options.onevent && typeof options.onevent !== 'function') {
2527                     throw new Error("jsf.ajax.request: Added an onevent callback that was not a function");
2528                 }
2529 
2530                 form = getForm(element);
2531                 if (!form) {
2532                     throw new Error("jsf.ajax.request: Method must be called within a form");
2533                 }
2534 
2535                 viewStateElement = getHiddenStateField(form, "javax.faces.ViewState");
2536                 if (!viewStateElement) {
2537                     throw new Error("jsf.ajax.request: Form has no view state element");
2538                 }
2539                 
2540                 context.form = form;
2541                 context.formId = form.id;
2542                 
2543                 var viewState = jsf.getViewState(form);
2544 
2545                 // Set up additional arguments to be used in the request..
2546                 // Make sure "javax.faces.source" is set up.
2547                 // If there were "execute" ids specified, make sure we
2548                 // include the identifier of the source element in the
2549                 // "execute" list.  If there were no "execute" ids
2550                 // specified, determine the default.
2551 
2552                 var args = {};
2553 
2554                 var namingContainerPrefix = viewStateElement.name.substring(0, viewStateElement.name.indexOf("javax.faces.ViewState"));
2555 
2556                 args[namingContainerPrefix + "javax.faces.source"] = element.id;
2557 
2558                 if (event && !!event.type) {
2559                     args[namingContainerPrefix + "javax.faces.partial.event"] = event.type;
2560                 }
2561 
2562                 if ("resetValues" in options) {
2563                     args[namingContainerPrefix + "javax.faces.partial.resetValues"] = options.resetValues;
2564                 }
2565 
2566                 // If we have 'execute' identifiers:
2567                 // Handle any keywords that may be present.
2568                 // If @none present anywhere, do not send the
2569                 // "javax.faces.partial.execute" parameter.
2570                 // The 'execute' and 'render' lists must be space
2571                 // delimited.
2572 
2573                 if (options.execute) {
2574                     none = options.execute.indexOf("@none");
2575                     if (none < 0) {
2576                         all = options.execute.indexOf("@all");
2577                         if (all < 0) {
2578                             options.execute = options.execute.replace("@this", element.id);
2579                             options.execute = options.execute.replace("@form", form.id);
2580                             var temp = options.execute.split(' ');
2581                             if (!isInArray(temp, element.name)) {
2582                                 options.execute = element.name + " " + options.execute;
2583                             }
2584                             if (namingContainerPrefix) {
2585                                 options.execute = namespaceParametersIfNecessary(options.execute, element.name, namingContainerPrefix);
2586                             }
2587                         } else {
2588                             options.execute = "@all";
2589                         }
2590                         args[namingContainerPrefix + "javax.faces.partial.execute"] = options.execute;
2591                     }
2592                 } else {
2593                     options.execute = element.name + " " + element.id;
2594                     args[namingContainerPrefix + "javax.faces.partial.execute"] = options.execute;
2595                 }
2596 
2597                 if (options.render) {
2598                     none = options.render.indexOf("@none");
2599                     if (none < 0) {
2600                         all = options.render.indexOf("@all");
2601                         if (all < 0) {
2602                             options.render = options.render.replace("@this", element.id);
2603                             options.render = options.render.replace("@form", form.id);
2604                             if (namingContainerPrefix) {
2605                                 options.render = namespaceParametersIfNecessary(options.render, element.name, namingContainerPrefix);
2606                             }
2607                         } else {
2608                             options.render = "@all";
2609                         }
2610                         args[namingContainerPrefix + "javax.faces.partial.render"] = options.render;
2611                     }
2612                 }
2613                 var explicitlyDoNotDelay = ((typeof options.delay == 'undefined') || (typeof options.delay == 'string') &&
2614                                             (options.delay.toLowerCase() == 'none'));
2615                 var delayValue;
2616                 if (typeof options.delay == 'number') {
2617                     delayValue = options.delay;
2618                 } else  {
2619                     var converted = parseInt(options.delay);
2620                     
2621                     if (!explicitlyDoNotDelay && isNaN(converted)) {
2622                         throw new Error('invalid value for delay option: ' + options.delay);
2623                     }
2624                     delayValue = converted;
2625                 }
2626 
2627                 var checkForTypeFile
2628 
2629                 // check the execute ids to see if any include an input of type "file"
2630                 context.includesInputFile = false;
2631                 var ids = options.execute.split(" ");
2632                 if (ids == "@all") { ids = [ form.id ]; }
2633                 if (ids) {
2634                     for (i = 0; i < ids.length; i++) {
2635                         var elem = document.getElementById(ids[i]);
2636                         if (elem) {
2637                             var nodeType = elem.nodeType;
2638                             if (nodeType == Node.ELEMENT_NODE) {
2639                                 var elemAttributeDetector = detectAttributes(elem);
2640                                 if (elemAttributeDetector("type")) {
2641                                     if (elem.getAttribute("type") === "file") {
2642                                         context.includesInputFile = true;
2643                                         break;
2644                                     }
2645                                 } else {
2646                                     if (hasInputFileControl(elem)) {
2647                                         context.includesInputFile = true;
2648                                         break;
2649                                     }
2650                                 }
2651                             }
2652                         }
2653                     }
2654                 }
2655 
2656                 // copy all params to args
2657                 var params = options.params || {};
2658                 for (var property in params) {
2659                     if (params.hasOwnProperty(property)) {
2660                         args[namingContainerPrefix + property] = params[property];
2661                     }
2662                 }
2663 
2664                 // remove non-passthrough options
2665                 delete options.execute;
2666                 delete options.render;
2667                 delete options.onerror;
2668                 delete options.onevent;
2669                 delete options.delay;
2670                 delete options.resetValues;
2671                 delete options.params;
2672 
2673                 // copy all other options to args (for backwards compatibility on issue 4115)
2674                 for (var property in options) {
2675                     if (options.hasOwnProperty(property)) {
2676                         args[namingContainerPrefix + property] = options[property];
2677                     }
2678                 }
2679 
2680                 args[namingContainerPrefix + "javax.faces.partial.ajax"] = "true";
2681                 args["method"] = "POST";
2682 
2683                 // Determine the posting url
2684 
2685                 var encodedUrlField = getEncodedUrlElement(form);
2686                 if (typeof encodedUrlField == 'undefined') {
2687                     args["url"] = form.action;
2688                 } else {
2689                     args["url"] = encodedUrlField.value;
2690                 }
2691                 var sendRequest = function() {
2692                     var ajaxEngine = new AjaxEngine(context);
2693                     ajaxEngine.setupArguments(args);
2694                     ajaxEngine.queryString = viewState;
2695                     ajaxEngine.context.onevent = onevent;
2696                     ajaxEngine.context.onerror = onerror;
2697                     ajaxEngine.context.sourceid = element.id;
2698                     ajaxEngine.context.render = args[namingContainerPrefix + "javax.faces.partial.render"] || "";
2699                     ajaxEngine.context.namingContainerPrefix = namingContainerPrefix;
2700                     ajaxEngine.sendRequest();
2701 
2702                     // null out element variables to protect against IE memory leak
2703                     element = null;
2704                     form = null;
2705                     sendRequest = null;
2706                     context = null;
2707                 };
2708 
2709                 if (explicitlyDoNotDelay) {
2710                     sendRequest();
2711                 } else {
2712                     delayHandler = setTimeout(sendRequest, delayValue);
2713                 }
2714 
2715             },
2716             /**
2717              * <p><span class="changed_modified_2_2">Receive</span> an Ajax response 
2718              * from the server.
2719              * <p><b>Usage:</b></p>
2720              * <pre><code>
2721              * jsf.ajax.response(request, context);
2722              * </pre></code>
2723              * <p><b>Implementation Requirements:</b></p>
2724              * This function must evaluate the markup returned in the
2725              * <code>request.responseXML</code> object and perform the following action:
2726              * <ul>
2727              * <p>If there is no XML response returned, signal an <code>emptyResponse</code>
2728              * error. If the XML response does not follow the format as outlined
2729              * in Appendix A of the spec prose document <a
2730              *  href="../../javadocs/overview-summary.html#prose_document">linked in the
2731              *  overview summary</a> signal a <code>malformedError</code> error.  Refer to
2732              * section "Signaling Errors" in Chapter 13 of the spec prose document <a
2733              *  href="../../javadocs/overview-summary.html#prose_document">linked in the
2734              *  overview summary</a>.</p>
2735              * <p>If the response was successfully processed, send a <code>success</code>
2736              * event as outlined in Chapter 13 "Sending Events" section of the spec prose
2737              * document <a
2738              * href="../../javadocs/overview-summary.html#prose_document">linked in the
2739              * overview summary</a>.</p>
2740              * <p><i>Update Element Processing</i></p>
2741              * The <code>update</code> element is used to update a single DOM element.  The
2742              * "id" attribute of the <code>update</code> element refers to the DOM element that
2743              * will be updated.  The contents of the <code>CDATA</code> section is the data that 
2744              * will be used when updating the contents of the DOM element as specified by the
2745              * <code><update></code> element identifier.
2746              * <li>If an <code><update></code> element is found in the response
2747              * with the identifier <code>javax.faces.ViewRoot</code>:
2748              * <pre><code><update id="javax.faces.ViewRoot">
2749              *    <![CDATA[...]]>
2750              * </update></code></pre>
2751              * Update the entire DOM replacing the appropriate <code>head</code> and/or
2752              * <code>body</code> sections with the content from the response.</li>
2753 
2754              * <li class="changed_modified_2_2">If an
2755              * <code><update></code> element is found in the 
2756              * response with an identifier containing
2757              * <code>javax.faces.ViewState</code>:
2758 
2759              * <pre><code><update id="<VIEW_ROOT_CONTAINER_CLIENT_ID><SEP>javax.faces.ViewState<SEP><UNIQUE_PER_VIEW_NUMBER>">
2760              *    <![CDATA[...]]>
2761              * </update></code></pre>
2762 
2763              * locate and update the submitting form's
2764              * <code>javax.faces.ViewState</code> value with the
2765              * <code>CDATA</code> contents from the response.
2766              * <SEP> is the currently configured
2767              * <code>UINamingContainer.getSeparatorChar()</code>.
2768              * <VIEW_ROOT_CONTAINER_CLIENT_ID> is the return from
2769              * <code>UIViewRoot.getContainerClientId()</code> on the
2770              * view from whence this state originated.
2771              * <UNIQUE_PER_VIEW_NUMBER> is a number that must be
2772              * unique within this view, but must not be included in the
2773              * view state.  This requirement is simply to satisfy XML
2774              * correctness in parity with what is done in the
2775              * corresponding non-partial JSF view.  Locate and update
2776              * the <code>javax.faces.ViewState</code> value for all
2777              * JSF forms covered in the <code>render</code> target
2778              * list whose ID starts with the same 
2779              * <VIEW_ROOT_CONTAINER_CLIENT_ID> value.</li>
2780 
2781              * <li class="changed_added_2_2">If an
2782              * <code>update</code> element is found in the response with
2783              * an identifier containing
2784              * <code>javax.faces.ClientWindow</code>:
2785 
2786              * <pre><code><update id="<VIEW_ROOT_CONTAINER_CLIENT_ID><SEP>javax.faces.ClientWindow<SEP><UNIQUE_PER_VIEW_NUMBER>">
2787              *    <![CDATA[...]]>
2788              * </update></code></pre>
2789 
2790              * locate and update the submitting form's
2791              * <code>javax.faces.ClientWindow</code> value with the
2792              * <code>CDATA</code> contents from the response.
2793              * <SEP> is the currently configured
2794              * <code>UINamingContainer.getSeparatorChar()</code>.
2795              * <VIEW_ROOT_CONTAINER_CLIENT_ID> is the return from
2796              * <code>UIViewRoot.getContainerClientId()</code> on the
2797              * view from whence this state originated.             
2798              * <UNIQUE_PER_VIEW_NUMBER> is a number that must be
2799              * unique within this view, but must not be included in the
2800              * view state.  This requirement is simply to satisfy XML
2801              * correctness in parity with what is done in the
2802              * corresponding non-partial JSF view.  Locate and update
2803              * the <code>javax.faces.ClientWindow</code> value for all
2804              * JSF forms covered in the <code>render</code> target
2805              * list whose ID starts with the same 
2806              * <VIEW_ROOT_CONTAINER_CLIENT_ID> value.</li>
2807 
2808              * <li class="changed_added_2_3">If an <code>update</code> element is found in the response with the
2809              * identifier <code>javax.faces.Resource</code>:
2810              * <pre><code><update id="javax.faces.Resource">
2811              *    <![CDATA[...]]>
2812              * </update></code></pre>
2813              * append any element found in the <code>CDATA</code> contents which is absent in the document to the
2814              * document's <code>head</code> section.
2815              * </li>
2816 
2817              * <li>If an <code>update</code> element is found in the response with the identifier
2818              * <code>javax.faces.ViewHead</code>:
2819              * <pre><code><update id="javax.faces.ViewHead">
2820              *    <![CDATA[...]]>
2821              * </update></code></pre>
2822              * update the document's <code>head</code> section with the <code>CDATA</code>
2823              * contents from the response.</li>
2824              * <li>If an <code>update</code> element is found in the response with the identifier
2825              * <code>javax.faces.ViewBody</code>:
2826              * <pre><code><update id="javax.faces.ViewBody">
2827              *    <![CDATA[...]]>
2828              * </update></code></pre>
2829              * update the document's <code>body</code> section with the <code>CDATA</code>
2830              * contents from the response.</li>
2831              * <li>For any other <code><update></code> element:
2832              * <pre><code><update id="update id">
2833              *    <![CDATA[...]]>
2834              * </update></code></pre>
2835              * Find the DOM element with the identifier that matches the
2836              * <code><update></code> element identifier, and replace its contents with
2837              * the <code><update></code> element's <code>CDATA</code> contents.</li>
2838              * </li>
2839              * <p><i>Insert Element Processing</i></p>
2840     
2841              * <li>If an <code><insert></code> element is found in
2842              * the response with a nested <code><before></code>
2843              * element:
2844             
2845              * <pre><code><insert>
2846              *     <before id="before id">
2847              *        <![CDATA[...]]>
2848              *     </before>
2849              * </insert></code></pre>
2850              * 
2851              * <ul>
2852              * <li>Extract this <code><before></code> element's <code>CDATA</code> contents
2853              * from the response.</li>
2854              * <li>Find the DOM element whose identifier matches <code>before id</code> and insert
2855              * the <code><before></code> element's <code>CDATA</code> content before
2856              * the DOM element in the document.</li>
2857              * </ul>
2858              * </li>
2859              * 
2860              * <li>If an <code><insert></code> element is found in 
2861              * the response with a nested <code><after></code>
2862              * element:
2863              * 
2864              * <pre><code><insert>
2865              *     <after id="after id">
2866              *        <![CDATA[...]]>
2867              *     </after>
2868              * </insert></code></pre>
2869              * 
2870              * <ul>
2871              * <li>Extract this <code><after></code> element's <code>CDATA</code> contents
2872              * from the response.</li>
2873              * <li>Find the DOM element whose identifier matches <code>after id</code> and insert
2874              * the <code><after></code> element's <code>CDATA</code> content after
2875              * the DOM element in the document.</li>
2876              * </ul>
2877              * </li>
2878              * <p><i>Delete Element Processing</i></p>
2879              * <li>If a <code><delete></code> element is found in the response:
2880              * <pre><code><delete id="delete id"/></code></pre>
2881              * Find the DOM element whose identifier matches <code>delete id</code> and remove it
2882              * from the DOM.</li>
2883              * <p><i>Element Attribute Update Processing</i></p>
2884              * <li>If an <code><attributes></code> element is found in the response:
2885              * <pre><code><attributes id="id of element with attribute">
2886              *    <attribute name="attribute name" value="attribute value">
2887              *    ...
2888              * </attributes></code></pre>
2889              * <ul>
2890              * <li>Find the DOM element that matches the <code><attributes></code> identifier.</li>
2891              * <li>For each nested <code><attribute></code> element in <code><attribute></code>,
2892              * update the DOM element attribute value (whose name matches <code>attribute name</code>),
2893              * with <code>attribute value</code>.</li>
2894              * </ul>
2895              * </li>
2896              * <p><i>JavaScript Processing</i></p>
2897              * <li>If an <code><eval></code> element is found in the response:
2898              * <pre><code><eval>
2899              *    <![CDATA[...JavaScript...]]>
2900              * </eval></code></pre>
2901              * <ul>
2902              * <li>Extract this <code><eval></code> element's <code>CDATA</code> contents
2903              * from the response and execute it as if it were JavaScript code.</li>
2904              * </ul>
2905              * </li>
2906              * <p><i>Redirect Processing</i></p>
2907              * <li>If a <code><redirect></code> element is found in the response:
2908              * <pre><code><redirect url="redirect url"/></code></pre>
2909              * Cause a redirect to the url <code>redirect url</code>.</li>
2910              * <p><i>Error Processing</i></p>
2911              * <li>If an <code><error></code> element is found in the response:
2912              * <pre><code><error>
2913              *    <error-name>..fully qualified class name string...<error-name>
2914              *    <error-message><![CDATA[...]]><error-message>
2915              * </error></code></pre>
2916              * Extract this <code><error></code> element's <code>error-name</code> contents
2917              * and the <code>error-message</code> contents. Signal a <code>serverError</code> passing
2918              * the <code>errorName</code> and <code>errorMessage</code>.  Refer to
2919              * section "Signaling Errors" in Chapter 13 of the spec prose document <a
2920              *  href="../../javadocs/overview-summary.html#prose_document">linked in the
2921              *  overview summary</a>.</li>
2922              * <p><i>Extensions</i></p>
2923              * <li>The <code><extensions></code> element provides a way for framework
2924              * implementations to provide their own information.</li>
2925              * <p><li>The implementation must check if <script> elements in the response can
2926              * be automatically run, as some browsers support this feature and some do not.  
2927              * If they can not be run, then scripts should be extracted from the response and
2928              * run separately.</li></p> 
2929              * </ul>
2930              *
2931              * </p>
2932              *
2933              * @param request The <code>XMLHttpRequest</code> instance that
2934              * contains the status code and response message from the server.
2935              *
2936              * @param context An object containing the request context, including the following properties:
2937              * the source element, per call onerror callback function, and per call onevent callback function.
2938              *
2939              * @throws  Error if request contains no data
2940              *
2941              * @function jsf.ajax.response
2942              */
2943             response: function response(request, context) {
2944                 if (!request) {
2945                     throw new Error("jsf.ajax.response: Request parameter is unset");
2946                 }
2947 
2948                 // ensure context source is the dom element and not the ID
2949                 // per 14.4.1 of the 2.0 specification.  We're doing it here
2950                 // *before* any errors or events are propagated becasue the
2951                 // DOM element may be removed after the update has been processed.
2952                 if (typeof context.sourceid === 'string') {
2953                     context.sourceid = document.getElementById(context.sourceid);
2954                 }
2955 
2956                 var xml = request.responseXML;
2957                 if (xml === null) {
2958                     sendError(request, context, "emptyResponse");
2959                     return;
2960                 }
2961 
2962                 if (getParseErrorText(xml) !== PARSED_OK) {
2963                     sendError(request, context, "malformedXML");
2964                     return;
2965                 }
2966 
2967                 var partialResponse = xml.getElementsByTagName("partial-response")[0];
2968                 var namingContainerId = partialResponse.getAttribute("id");
2969                 var namingContainerPrefix = namingContainerId ? (namingContainerId + jsf.separatorchar) : "";
2970                 var responseType = partialResponse.firstChild;
2971                 
2972                 context.namingContainerId = namingContainerId;
2973                 context.namingContainerPrefix = namingContainerPrefix;
2974 
2975                 for (var i = 0; i < partialResponse.childNodes.length; i++) {
2976                     if (partialResponse.childNodes[i].nodeName === "error") {
2977                         responseType = partialResponse.childNodes[i];
2978                         break;
2979                     }
2980                 }
2981 
2982                 if (responseType.nodeName === "error") { // it's an error
2983                     var errorName = "";
2984                     var errorMessage = "";
2985                     
2986                     var element = responseType.firstChild;
2987                     if (element.nodeName === "error-name") {
2988                         if (null != element.firstChild) {
2989                             errorName = element.firstChild.nodeValue;
2990                         }
2991                     }
2992                     
2993                     element = responseType.firstChild.nextSibling;
2994                     if (element.nodeName === "error-message") {
2995                         if (null != element.firstChild) {
2996                             errorMessage = element.firstChild.nodeValue;
2997                         }
2998                     }
2999                     sendError(request, context, "serverError", null, errorName, errorMessage);
3000                     sendEvent(request, context, "success");
3001                     return;
3002                 }
3003 
3004 
3005                 if (responseType.nodeName === "redirect") {
3006                     window.location = responseType.getAttribute("url");
3007                     return;
3008                 }
3009 
3010 
3011                 if (responseType.nodeName !== "changes") {
3012                     sendError(request, context, "malformedXML", "Top level node must be one of: changes, redirect, error, received: " + responseType.nodeName + " instead.");
3013                     return;
3014                 }
3015 
3016 
3017                 var changes = responseType.childNodes;
3018 
3019                 try {
3020                     for (var i = 0; i < changes.length; i++) {
3021                         switch (changes[i].nodeName) {
3022                             case "update":
3023                                 doUpdate(changes[i], context);
3024                                 break;
3025                             case "delete":
3026                                 doDelete(changes[i]);
3027                                 break;
3028                             case "insert":
3029                                 doInsert(changes[i]);
3030                                 break;
3031                             case "attributes":
3032                                 doAttributes(changes[i]);
3033                                 break;
3034                             case "eval":
3035                                 doEval(changes[i]);
3036                                 break;
3037                             case "extension":
3038                                 // no action
3039                                 break;
3040                             default:
3041                                 sendError(request, context, "malformedXML", "Changes allowed are: update, delete, insert, attributes, eval, extension.  Received " + changes[i].nodeName + " instead.");
3042                                 return;
3043                         }
3044                     }
3045                 } catch (ex) {
3046                     sendError(request, context, "malformedXML", ex.message);
3047                     return;
3048                 }
3049                 sendEvent(request, context, "success");
3050 
3051             }
3052         };
3053     }();
3054 
3055     /**
3056      *
3057      * <p>Return the value of <code>Application.getProjectStage()</code> for
3058      * the currently running application instance.  Calling this method must
3059      * not cause any network transaction to happen to the server.</p>
3060      * <p><b>Usage:</b></p>
3061      * <pre><code>
3062      * var stage = jsf.getProjectStage();
3063      * if (stage === ProjectStage.Development) {
3064      *  ...
3065      * } else if stage === ProjectStage.Production) {
3066      *  ...
3067      * }
3068      * </code></pre>
3069      *
3070      * @returns String <code>String</code> representing the current state of the
3071      * running application in a typical product development lifecycle.  Refer
3072      * to <code>javax.faces.application.Application.getProjectStage</code> and
3073      * <code>javax.faces.application.ProjectStage</code>.
3074      * @function jsf.getProjectStage
3075      */
3076     jsf.getProjectStage = function() {
3077         // First, return cached value if available
3078         if (typeof mojarra !== 'undefined' && typeof mojarra.projectStageCache !== 'undefined') {
3079             return mojarra.projectStageCache;
3080         }
3081         var scripts = document.getElementsByTagName("script"); // nodelist of scripts
3082         var script; // jsf.js script
3083         var s = 0; // incremental variable for for loop
3084         var stage; // temp value for stage
3085         var match; // temp value for match
3086         while (s < scripts.length) {
3087             if (typeof scripts[s].src === 'string' && scripts[s].src.match('\/javax\.faces\.resource\/jsf\.js\?.*ln=javax\.faces')) {
3088                 script = scripts[s].src;
3089                 break;
3090             }
3091             s++;
3092         }
3093         if (typeof script == "string") {
3094             match = script.match("stage=(.*)");
3095             if (match) {
3096                 stage = match[1];
3097             }
3098         }
3099         if (typeof stage === 'undefined' || !stage) {
3100             stage = "Production";
3101         }
3102 
3103         mojarra = mojarra || {};
3104         mojarra.projectStageCache = stage;
3105 
3106         return mojarra.projectStageCache;
3107     };
3108 
3109 
3110     /**
3111      * <p>Collect and encode state for input controls associated
3112      * with the specified <code>form</code> element.  This will include
3113      * all input controls of type <code>hidden</code>.</p>
3114      * <p><b>Usage:</b></p>
3115      * <pre><code>
3116      * var state = jsf.getViewState(form);
3117      * </pre></code>
3118      *
3119      * @param form The <code>form</code> element whose contained
3120      * <code>input</code> controls will be collected and encoded.
3121      * Only successful controls will be collected and encoded in
3122      * accordance with: <a href="http://www.w3.org/TR/html401/interact/forms.html#h-17.13.2">
3123      * Section 17.13.2 of the HTML Specification</a>.
3124      *
3125      * @returns String The encoded state for the specified form's input controls.
3126      * @function jsf.getViewState
3127      */
3128     jsf.getViewState = function(form) {
3129         if (!form) {
3130             throw new Error("jsf.getViewState:  form must be set");
3131         }
3132         var els = form.elements;
3133         var len = els.length;
3134         // create an array which we'll use to hold all the intermediate strings
3135         // this bypasses a problem in IE when repeatedly concatenating very
3136         // large strings - we'll perform the concatenation once at the end
3137         var qString = [];
3138         var addField = function(name, value) {
3139             var tmpStr = "";
3140             if (qString.length > 0) {
3141                 tmpStr = "&";
3142             }
3143             tmpStr += encodeURIComponent(name) + "=" + encodeURIComponent(value);
3144             qString.push(tmpStr);
3145         };
3146         for (var i = 0; i < len; i++) {
3147             var el = els[i];
3148             if (el.name === "") {
3149                 continue;
3150             }
3151             if (!el.disabled) {
3152                 switch (el.type) {
3153                     case 'submit':
3154                     case 'reset':
3155                     case 'image':
3156                     case 'file':
3157                         break;
3158                     case 'select-one':
3159                         if (el.selectedIndex >= 0) {
3160                             addField(el.name, el.options[el.selectedIndex].value);
3161                         }
3162                         break;
3163                     case 'select-multiple':
3164                         for (var j = 0; j < el.options.length; j++) {
3165                             if (el.options[j].selected) {
3166                                 addField(el.name, el.options[j].value);
3167                             }
3168                         }
3169                         break;
3170                     case 'checkbox':
3171                     case 'radio':
3172                         if (el.checked) {
3173                             addField(el.name, el.value || 'on');
3174                         }
3175                         break;
3176                     default:
3177                         // this is for any input incl.  text', 'password', 'hidden', 'textarea'
3178                         var nodeName = el.nodeName.toLowerCase();
3179                         if (nodeName === "input" || nodeName === "select" ||
3180                             nodeName === "button" || nodeName === "object" ||
3181                             nodeName === "textarea") {                                 
3182                             addField(el.name, el.value);
3183                         }
3184                         break;
3185                 }
3186             }
3187         }
3188         // concatenate the array
3189         return qString.join("");
3190     };
3191 
3192     /**
3193      * <p class="changed_added_2_2">Return the windowId of the window
3194      * in which the argument form is rendered.</p>
3195 
3196      * @param {optional String|DomNode} node. Determine the nature of
3197      * the argument.  If not present, search for the windowId within
3198      * <code>document.forms</code>.  If present and the value is a
3199      * string, assume the string is a DOM id and get the element with
3200      * that id and start the search from there.  If present and the
3201      * value is a DOM element, start the search from there.
3202 
3203      * @returns String The windowId of the current window, or null 
3204      *  if the windowId cannot be determined.
3205 
3206      * @throws an error if more than one unique WindowId is found.
3207 
3208      * @function jsf.getClientWindow
3209      */
3210     jsf.getClientWindow = function(node) {
3211         var FORM = "form";
3212         var WIN_ID = "javax.faces.ClientWindow";
3213 
3214         /**
3215          * Find javax.faces.ClientWindow field for a given form.
3216          * @param form
3217          * @ignore
3218          */
3219         var getWindowIdElement = function getWindowIdElement(form) {
3220             var windowIdElement = form[WIN_ID];
3221 
3222             if (windowIdElement) {
3223                 return windowIdElement;
3224             } else {
3225                 var formElements = form.elements;
3226                 for (var i = 0, length = formElements.length; i < length; i++) {
3227                     var formElement = formElements[i];
3228                     if (formElement.name && (formElement.name.indexOf(WIN_ID) >= 0)) {
3229                         return formElement;
3230                     }
3231                 }
3232             }
3233 
3234             return undefined;
3235         };
3236 
3237         var fetchWindowIdFromForms = function (forms) {
3238             var result_idx = {};
3239             var result;
3240             var foundCnt = 0;
3241             for (var cnt = forms.length - 1; cnt >= 0; cnt--) {
3242                 var UDEF = 'undefined';
3243                 var currentForm = forms[cnt];
3244                 var windowIdElement = getWindowIdElement(currentForm);
3245                 var windowId = windowIdElement && windowIdElement.value;
3246                 if (UDEF != typeof windowId) {
3247                     if (foundCnt > 0 && UDEF == typeof result_idx[windowId]) throw Error("Multiple different windowIds found in document");
3248                     result = windowId;
3249                     result_idx[windowId] = true;
3250                     foundCnt++;
3251                 }
3252             }
3253             return result;
3254         }
3255 
3256         /**
3257          * @ignore
3258          */
3259         var getChildForms = function (currentElement) {
3260             //Special condition no element we return document forms
3261             //as search parameter, ideal would be to
3262             //have the viewroot here but the frameworks
3263             //can deal with that themselves by using
3264             //the viewroot as currentElement
3265             if (!currentElement) {
3266                 return document.forms;
3267             }
3268             
3269             var targetArr = [];
3270             if (!currentElement.tagName) return [];
3271             else if (currentElement.tagName.toLowerCase() == FORM) {
3272                 targetArr.push(currentElement);
3273                 return targetArr;
3274             }
3275             
3276             //if query selectors are supported we can take
3277             //a non recursive shortcut
3278             if (currentElement.querySelectorAll) {
3279                 return currentElement.querySelectorAll(FORM);
3280             }
3281             
3282             //old recursive way, due to flakeyness of querySelectorAll
3283             for (var cnt = currentElement.childNodes.length - 1; cnt >= 0; cnt--) {
3284                 var currentChild = currentElement.childNodes[cnt];
3285                 targetArr = targetArr.concat(getChildForms(currentChild, FORM));
3286             }
3287             return targetArr;
3288         }
3289         
3290         /**
3291          * @ignore
3292          */
3293         var fetchWindowIdFromURL = function () {
3294             var href = window.location.href;
3295             var windowId = "windowId";
3296             var regex = new RegExp("[\\?&]" + windowId + "=([^&#\\;]*)");
3297             var results = regex.exec(href);
3298             //initial trial over the url and a regexp
3299             if (results != null) return results[1];
3300             return null;
3301         }
3302         
3303         //byId ($)
3304         var finalNode = (node && (typeof node == "string" || node instanceof String)) ?
3305             document.getElementById(node) : (node || null);
3306         
3307         var forms = getChildForms(finalNode);
3308         var result = fetchWindowIdFromForms(forms);
3309         return (null != result) ? result : fetchWindowIdFromURL();
3310         
3311 
3312     };
3313 
3314     /**
3315      * <p class="changed_added_2_3">
3316      * The Push functionality.
3317      * </p>
3318      * @name jsf.push
3319      * @namespace
3320      * @exec
3321      */
3322     jsf.push = function() {
3323 
3324         // "Constant" fields ----------------------------------------------------------------------------------------------
3325 
3326         var RECONNECT_INTERVAL = 500;
3327         var MAX_RECONNECT_ATTEMPTS = 25;
3328         var REASON_EXPIRED = "Expired";
3329 
3330         // Private static fields ------------------------------------------------------------------------------------------
3331 
3332         var sockets = {};
3333 
3334         // Private constructor functions ----------------------------------------------------------------------------------
3335 
3336         /**
3337          * Creates a reconnecting websocket. When the websocket successfully connects on first attempt, then it will
3338          * automatically reconnect on timeout with cumulative intervals of 500ms with a maximum of 25 attempts (~3 minutes).
3339          * The <code>onclose</code> function will be called with the error code of the last attempt.
3340          * @constructor
3341          * @param {string} url The URL of the websocket.
3342          * @param {string} channel The channel name of the websocket.
3343          * @param {function} onopen The function to be invoked when the websocket is opened.
3344          * @param {function} onmessage The function to be invoked when a message is received.
3345          * @param {function} onclose The function to be invoked when the websocket is closed.
3346          * @param {Object} behaviors Client behavior functions to be invoked when specific message is received.
3347          * @ignore
3348          */
3349         function ReconnectingWebsocket(url, channel, onopen, onmessage, onclose, behaviors) {
3350 
3351             // Private fields -----------------------------------------------------------------------------------------
3352 
3353             var socket;
3354             var reconnectAttempts;
3355             var self = this;
3356 
3357             // Public functions ---------------------------------------------------------------------------------------
3358 
3359             /**
3360              * Opens the reconnecting websocket.
3361              */
3362             self.open = function() {
3363                 if (socket && socket.readyState == 1) {
3364                     return;
3365                 }
3366 
3367                 socket = new WebSocket(url);
3368 
3369                 socket.onopen = function(event) {
3370                     if (reconnectAttempts == null) {
3371                         onopen(channel);
3372                     }
3373 
3374                     reconnectAttempts = 0;
3375                 }
3376 
3377                 socket.onmessage = function(event) {
3378                     var message = JSON.parse(event.data).data;
3379                     onmessage(message, channel, event);
3380                     var functions = behaviors[message];
3381 
3382                     if (functions && functions.length) {
3383                         for (var i = 0; i < functions.length; i++) {
3384                             functions[i]();
3385                         }
3386                     }
3387                 }
3388 
3389                 socket.onclose = function(event) {
3390                     if (!socket
3391                             || (event.code == 1000 && event.reason == REASON_EXPIRED)
3392                             || (event.code == 1008)
3393                             || (reconnectAttempts == null)
3394                             || (reconnectAttempts >= MAX_RECONNECT_ATTEMPTS))
3395                     {
3396                         onclose(event.code, channel, event);
3397                     }
3398                     else {
3399                         setTimeout(self.open, RECONNECT_INTERVAL * reconnectAttempts++);
3400                     }
3401                 }
3402             }
3403 
3404             /**
3405              * Closes the reconnecting websocket.
3406              */
3407             self.close = function() {
3408                 if (socket) {
3409                     var s = socket;
3410                     socket = null;
3411                     reconnectAttempts == null;
3412                     s.close();
3413                 }
3414             }
3415 
3416         }
3417 
3418 
3419         // Private static functions ---------------------------------------------------------------------------------------
3420 
3421         /**
3422          * If given function is actually not a function, then try to interpret it as name of a global function.
3423          * If it still doesn't resolve to anything, then return a NOOP function.
3424          * @param {Object} fn Can be function, or string representing function name, or undefined.
3425          * @return {function} The intented function, or a NOOP function when undefined.
3426          * @ignore
3427          */
3428         function resolveFunction(fn) {
3429             return (typeof fn !== "function") && (fn = window[fn] || function(){}), fn;
3430         }
3431 
3432         /**
3433          * Get socket associated with given client identifier.
3434          * @param {string} clientId The client identifier of the websocket.
3435          * @return {Socket} Socket associated with given client identifier.
3436          * @throws {Error} When client identifier is unknown. You may need to initialize it first via <code>init()</code> function.
3437          * @ignore
3438          */
3439         function getSocket(clientId) {
3440             var socket = sockets[clientId];
3441 
3442             if (socket) {
3443                 return socket;
3444             }
3445             else {
3446                 throw new Error("Unknown clientId: " + clientId);
3447             }
3448         }
3449 
3450 
3451         // Public static functions ----------------------------------------------------------------------------------------
3452 
3453         return {
3454 
3455             /**
3456              * Initialize a websocket on the given client identifier. When connected, it will stay open and reconnect as
3457              * long as URL is valid and <code>jsf.push.close()</code> hasn't explicitly been called on the same client
3458              * identifier.
3459              * @param {string} clientId The client identifier of the websocket.
3460              * @param {string} url The URL of the websocket. All open websockets on the same URL will receive the
3461              * same push notification from the server.
3462              * @param {string} channel The channel name of the websocket.
3463              * @param {function} onopen The JavaScript event handler function that is invoked when the websocket is opened.
3464              * The function will be invoked with one argument: the client identifier.
3465              * @param {function} onmessage The JavaScript event handler function that is invoked when a message is received from
3466              * the server. The function will be invoked with three arguments: the push message, the client identifier and
3467              * the raw <code>MessageEvent</code> itself.
3468              * @param {function} onclose The JavaScript event handler function that is invoked when the websocket is closed.
3469              * The function will be invoked with three arguments: the close reason code, the client identifier and the raw
3470              * <code>CloseEvent</code> itself. Note that this will also be invoked on errors and that you can inspect the
3471              * close reason code if an error occurred and which one (i.e. when the code is not 1000). See also
3472              * <a href="http://tools.ietf.org/html/rfc6455#section-7.4.1">RFC 6455 section 7.4.1</a> and
3473              * <a href="http://docs.oracle.com/javaee/7/api/javax/websocket/CloseReason.CloseCodes.html">CloseCodes</a> API
3474              * for an elaborate list.
3475              * @param {Object} behaviors Client behavior functions to be invoked when specific message is received.
3476              * @param {boolean} autoconnect Whether or not to automatically connect the socket. Defaults to <code>false</code>.
3477              * @member jsf.push
3478              * @function jsf.push.init
3479              */
3480             init: function(clientId, url, channel, onopen, onmessage, onclose, behaviors, autoconnect) {
3481                 onclose = resolveFunction(onclose);
3482     
3483                 if (!window.WebSocket) { // IE6-9.
3484                     onclose(-1, clientId);
3485                     return;
3486                 }
3487     
3488                 if (!sockets[clientId]) {
3489                     sockets[clientId] = new ReconnectingWebsocket(url, channel, resolveFunction(onopen), resolveFunction(onmessage), onclose, behaviors);
3490                 }
3491     
3492                 if (autoconnect) {
3493                 	getSocket(clientId).open();
3494                 }
3495             },
3496 
3497             /**
3498              * Open the websocket on the given client identifier.
3499              * @param {string} clientId The client identifier of the websocket.
3500              * @throws {Error} When client identifier is unknown. You may need to initialize it first via <code>init()</code> function.
3501              * @member jsf.push
3502              * @function jsf.push.open
3503              */
3504             open: function(clientId) {
3505                 getSocket(clientId).open();
3506             },
3507 
3508             /**
3509              * Close the websocket on the given client identifier.
3510              * @param {string} clientId The client identifier of the websocket.
3511              * @throws {Error} When client identifier is unknown. You may need to initialize it first via <code>init()</code> function.
3512              * @member jsf.push
3513              * @function jsf.push.close
3514              */
3515             close: function(clientId) {
3516                 getSocket(clientId).close();
3517             }
3518         }
3519     }();
3520 
3521 
3522     /**
3523      * The namespace for JavaServer Faces JavaScript utilities.
3524      * @name jsf.util
3525      * @namespace
3526      */
3527     jsf.util = {};
3528 
3529     /**
3530      * <p>A varargs function that invokes an arbitrary number of scripts.
3531      * If any script in the chain returns false, the chain is short-circuited
3532      * and subsequent scripts are not invoked.  Any number of scripts may
3533      * specified after the <code>event</code> argument.</p>
3534      *
3535      * @param source The DOM element that triggered this Ajax request, or an
3536      * id string of the element to use as the triggering element.
3537      * @param event The DOM event that triggered this Ajax request.  The
3538      * <code>event</code> argument is optional.
3539      *
3540      * @returns boolean <code>false</code> if any scripts in the chain return <code>false</code>,
3541      *  otherwise returns <code>true</code>
3542      * 
3543      * @function jsf.util.chain
3544      */
3545     jsf.util.chain = function(source, event) {
3546 
3547         if (arguments.length < 3) {
3548             return true;
3549         }
3550 
3551         // RELEASE_PENDING rogerk - shouldn't this be getElementById instead of null
3552         var thisArg = (typeof source === 'object') ? source : null;
3553 
3554         // Call back any scripts that were passed in
3555         for (var i = 2; i < arguments.length; i++) {
3556 
3557             var f = new Function("event", arguments[i]);
3558             var returnValue = f.call(thisArg, event);
3559 
3560             if (returnValue === false) {
3561                 return false;
3562             }
3563         }
3564         return true;
3565         
3566     };
3567 
3568     /**
3569      * <p class="changed_added_2_2">The result of calling
3570      * <code>UINamingContainer.getNamingContainerSeparatorChar().</code></p>
3571      */
3572     jsf.separatorchar = '#{facesContext.namingContainerSeparatorChar}';
3573 
3574     /**
3575      * <p>An integer specifying the specification version that this file implements.
3576      * Its format is: rightmost two digits, bug release number, next two digits,
3577      * minor release number, leftmost digits, major release number.
3578      * This number may only be incremented by a new release of the specification.</p>
3579      */
3580     jsf.specversion = 23000;
3581 
3582     /**
3583      * <p>An integer specifying the implementation version that this file implements.
3584      * It's a monotonically increasing number, reset with every increment of
3585      * <code>jsf.specversion</code>
3586      * This number is implementation dependent.</p>
3587      */
3588     jsf.implversion = 3;
3589 
3590 
3591 } //end if version detection block
3592