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