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