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