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