PageRenderTime 60ms CodeModel.GetById 16ms RepoModel.GetById 0ms app.codeStats 0ms

/js/src/metrics/jint/v8/raytrace.js

http://github.com/zpao/v8monkey
JavaScript | 3418 lines | 2898 code | 418 blank | 102 comment | 442 complexity | 0f810b31b03b524a557516351b02ad43 MD5 | raw file
Possible License(s): MPL-2.0-no-copyleft-exception, LGPL-3.0, AGPL-1.0, LGPL-2.1, BSD-3-Clause, GPL-2.0, JSON, Apache-2.0, 0BSD

Large files files are truncated, but you can click here to view the full file

  1. // The ray tracer code in this file is written by Adam Burmister. It
  2. // is available in its original form from:
  3. //
  4. // http://labs.flog.nz.co/raytracer/
  5. //
  6. // It has been modified slightly by Google to work as a standalone
  7. // benchmark, but the all the computational code remains
  8. // untouched. This file also contains a copy of the Prototype
  9. // JavaScript framework which is used by the ray tracer.
  10. var RayTrace = new BenchmarkSuite('RayTrace', 932666, [
  11. new Benchmark('RayTrace', renderScene)
  12. ]);
  13. // Create dummy objects if we're not running in a browser.
  14. if (typeof document == 'undefined') {
  15. document = { };
  16. window = { opera: null };
  17. navigator = { userAgent: null, appVersion: "" };
  18. }
  19. // ------------------------------------------------------------------------
  20. // ------------------------------------------------------------------------
  21. /* Prototype JavaScript framework, version 1.5.0
  22. * (c) 2005-2007 Sam Stephenson
  23. *
  24. * Prototype is freely distributable under the terms of an MIT-style license.
  25. * For details, see the Prototype web site: http://prototype.conio.net/
  26. *
  27. /*--------------------------------------------------------------------------*/
  28. //--------------------
  29. var Prototype = {
  30. Version: '1.5.0',
  31. BrowserFeatures: {
  32. XPath: !!document.evaluate
  33. },
  34. ScriptFragment: '(?:<script.*?>)((\n|\r|.)*?)(?:<\/script>)',
  35. emptyFunction: function() {},
  36. K: function(x) { return x }
  37. }
  38. var Class = {
  39. create: function() {
  40. return function() {
  41. this.initialize.apply(this, arguments);
  42. }
  43. }
  44. }
  45. var Abstract = new Object();
  46. Object.extend = function(destination, source) {
  47. for (var property in source) {
  48. destination[property] = source[property];
  49. }
  50. return destination;
  51. }
  52. Object.extend(Object, {
  53. inspect: function(object) {
  54. try {
  55. if (object === undefined) return 'undefined';
  56. if (object === null) return 'null';
  57. return object.inspect ? object.inspect() : object.toString();
  58. } catch (e) {
  59. if (e instanceof RangeError) return '...';
  60. throw e;
  61. }
  62. },
  63. keys: function(object) {
  64. var keys = [];
  65. for (var property in object)
  66. keys.push(property);
  67. return keys;
  68. },
  69. values: function(object) {
  70. var values = [];
  71. for (var property in object)
  72. values.push(object[property]);
  73. return values;
  74. },
  75. clone: function(object) {
  76. return Object.extend({}, object);
  77. }
  78. });
  79. Function.prototype.bind = function() {
  80. var __method = this, args = $A(arguments), object = args.shift();
  81. return function() {
  82. return __method.apply(object, args.concat($A(arguments)));
  83. }
  84. }
  85. Function.prototype.bindAsEventListener = function(object) {
  86. var __method = this, args = $A(arguments), object = args.shift();
  87. return function(event) {
  88. return __method.apply(object, [( event || window.event)].concat(args).concat($A(arguments)));
  89. }
  90. }
  91. Object.extend(Number.prototype, {
  92. toColorPart: function() {
  93. var digits = this.toString(16);
  94. if (this < 16) return '0' + digits;
  95. return digits;
  96. },
  97. succ: function() {
  98. return this + 1;
  99. },
  100. times: function(iterator) {
  101. $R(0, this, true).each(iterator);
  102. return this;
  103. }
  104. });
  105. var Try = {
  106. these: function() {
  107. var returnValue;
  108. for (var i = 0, length = arguments.length; i < length; i++) {
  109. var lambda = arguments[i];
  110. try {
  111. returnValue = lambda();
  112. break;
  113. } catch (e) {}
  114. }
  115. return returnValue;
  116. }
  117. }
  118. /*--------------------------------------------------------------------------*/
  119. var PeriodicalExecuter = Class.create();
  120. PeriodicalExecuter.prototype = {
  121. initialize: function(callback, frequency) {
  122. this.callback = callback;
  123. this.frequency = frequency;
  124. this.currentlyExecuting = false;
  125. this.registerCallback();
  126. },
  127. registerCallback: function() {
  128. this.timer = setInterval(this.onTimerEvent.bind(this), this.frequency * 1000);
  129. },
  130. stop: function() {
  131. if (!this.timer) return;
  132. clearInterval(this.timer);
  133. this.timer = null;
  134. },
  135. onTimerEvent: function() {
  136. if (!this.currentlyExecuting) {
  137. try {
  138. this.currentlyExecuting = true;
  139. this.callback(this);
  140. } finally {
  141. this.currentlyExecuting = false;
  142. }
  143. }
  144. }
  145. }
  146. String.interpret = function(value){
  147. return value == null ? '' : String(value);
  148. }
  149. Object.extend(String.prototype, {
  150. gsub: function(pattern, replacement) {
  151. var result = '', source = this, match;
  152. replacement = arguments.callee.prepareReplacement(replacement);
  153. while (source.length > 0) {
  154. if (match = source.match(pattern)) {
  155. result += source.slice(0, match.index);
  156. result += String.interpret(replacement(match));
  157. source = source.slice(match.index + match[0].length);
  158. } else {
  159. result += source, source = '';
  160. }
  161. }
  162. return result;
  163. },
  164. sub: function(pattern, replacement, count) {
  165. replacement = this.gsub.prepareReplacement(replacement);
  166. count = count === undefined ? 1 : count;
  167. return this.gsub(pattern, function(match) {
  168. if (--count < 0) return match[0];
  169. return replacement(match);
  170. });
  171. },
  172. scan: function(pattern, iterator) {
  173. this.gsub(pattern, iterator);
  174. return this;
  175. },
  176. truncate: function(length, truncation) {
  177. length = length || 30;
  178. truncation = truncation === undefined ? '...' : truncation;
  179. return this.length > length ?
  180. this.slice(0, length - truncation.length) + truncation : this;
  181. },
  182. strip: function() {
  183. return this.replace(/^\s+/, '').replace(/\s+$/, '');
  184. },
  185. stripTags: function() {
  186. return this.replace(/<\/?[^>]+>/gi, '');
  187. },
  188. stripScripts: function() {
  189. return this.replace(new RegExp(Prototype.ScriptFragment, 'img'), '');
  190. },
  191. extractScripts: function() {
  192. var matchAll = new RegExp(Prototype.ScriptFragment, 'img');
  193. var matchOne = new RegExp(Prototype.ScriptFragment, 'im');
  194. return (this.match(matchAll) || []).map(function(scriptTag) {
  195. return (scriptTag.match(matchOne) || ['', ''])[1];
  196. });
  197. },
  198. evalScripts: function() {
  199. return this.extractScripts().map(function(script) { return eval(script) });
  200. },
  201. escapeHTML: function() {
  202. var div = document.createElement('div');
  203. var text = document.createTextNode(this);
  204. div.appendChild(text);
  205. return div.innerHTML;
  206. },
  207. unescapeHTML: function() {
  208. var div = document.createElement('div');
  209. div.innerHTML = this.stripTags();
  210. return div.childNodes[0] ? (div.childNodes.length > 1 ?
  211. $A(div.childNodes).inject('',function(memo,node){ return memo+node.nodeValue }) :
  212. div.childNodes[0].nodeValue) : '';
  213. },
  214. toQueryParams: function(separator) {
  215. var match = this.strip().match(/([^?#]*)(#.*)?$/);
  216. if (!match) return {};
  217. return match[1].split(separator || '&').inject({}, function(hash, pair) {
  218. if ((pair = pair.split('='))[0]) {
  219. var name = decodeURIComponent(pair[0]);
  220. var value = pair[1] ? decodeURIComponent(pair[1]) : undefined;
  221. if (hash[name] !== undefined) {
  222. if (hash[name].constructor != Array)
  223. hash[name] = [hash[name]];
  224. if (value) hash[name].push(value);
  225. }
  226. else hash[name] = value;
  227. }
  228. return hash;
  229. });
  230. },
  231. toArray: function() {
  232. return this.split('');
  233. },
  234. succ: function() {
  235. return this.slice(0, this.length - 1) +
  236. String.fromCharCode(this.charCodeAt(this.length - 1) + 1);
  237. },
  238. camelize: function() {
  239. var parts = this.split('-'), len = parts.length;
  240. if (len == 1) return parts[0];
  241. var camelized = this.charAt(0) == '-'
  242. ? parts[0].charAt(0).toUpperCase() + parts[0].substring(1)
  243. : parts[0];
  244. for (var i = 1; i < len; i++)
  245. camelized += parts[i].charAt(0).toUpperCase() + parts[i].substring(1);
  246. return camelized;
  247. },
  248. capitalize: function(){
  249. return this.charAt(0).toUpperCase() + this.substring(1).toLowerCase();
  250. },
  251. underscore: function() {
  252. return this.gsub(/::/, '/').gsub(/([A-Z]+)([A-Z][a-z])/,'#{1}_#{2}').gsub(/([a-z\d])([A-Z])/,'#{1}_#{2}').gsub(/-/,'_').toLowerCase();
  253. },
  254. dasherize: function() {
  255. return this.gsub(/_/,'-');
  256. },
  257. inspect: function(useDoubleQuotes) {
  258. var escapedString = this.replace(/\\/g, '\\\\');
  259. if (useDoubleQuotes)
  260. return '"' + escapedString.replace(/"/g, '\\"') + '"';
  261. else
  262. return "'" + escapedString.replace(/'/g, '\\\'') + "'";
  263. }
  264. });
  265. String.prototype.gsub.prepareReplacement = function(replacement) {
  266. if (typeof replacement == 'function') return replacement;
  267. var template = new Template(replacement);
  268. return function(match) { return template.evaluate(match) };
  269. }
  270. String.prototype.parseQuery = String.prototype.toQueryParams;
  271. var Template = Class.create();
  272. Template.Pattern = /(^|.|\r|\n)(#\{(.*?)\})/;
  273. Template.prototype = {
  274. initialize: function(template, pattern) {
  275. this.template = template.toString();
  276. this.pattern = pattern || Template.Pattern;
  277. },
  278. evaluate: function(object) {
  279. return this.template.gsub(this.pattern, function(match) {
  280. var before = match[1];
  281. if (before == '\\') return match[2];
  282. return before + String.interpret(object[match[3]]);
  283. });
  284. }
  285. }
  286. var $break = new Object();
  287. var $continue = new Object();
  288. var Enumerable = {
  289. each: function(iterator) {
  290. var index = 0;
  291. try {
  292. this._each(function(value) {
  293. try {
  294. iterator(value, index++);
  295. } catch (e) {
  296. if (e != $continue) throw e;
  297. }
  298. });
  299. } catch (e) {
  300. if (e != $break) throw e;
  301. }
  302. return this;
  303. },
  304. eachSlice: function(number, iterator) {
  305. var index = -number, slices = [], array = this.toArray();
  306. while ((index += number) < array.length)
  307. slices.push(array.slice(index, index+number));
  308. return slices.map(iterator);
  309. },
  310. all: function(iterator) {
  311. var result = true;
  312. this.each(function(value, index) {
  313. result = result && !!(iterator || Prototype.K)(value, index);
  314. if (!result) throw $break;
  315. });
  316. return result;
  317. },
  318. any: function(iterator) {
  319. var result = false;
  320. this.each(function(value, index) {
  321. if (result = !!(iterator || Prototype.K)(value, index))
  322. throw $break;
  323. });
  324. return result;
  325. },
  326. collect: function(iterator) {
  327. var results = [];
  328. this.each(function(value, index) {
  329. results.push((iterator || Prototype.K)(value, index));
  330. });
  331. return results;
  332. },
  333. detect: function(iterator) {
  334. var result;
  335. this.each(function(value, index) {
  336. if (iterator(value, index)) {
  337. result = value;
  338. throw $break;
  339. }
  340. });
  341. return result;
  342. },
  343. findAll: function(iterator) {
  344. var results = [];
  345. this.each(function(value, index) {
  346. if (iterator(value, index))
  347. results.push(value);
  348. });
  349. return results;
  350. },
  351. grep: function(pattern, iterator) {
  352. var results = [];
  353. this.each(function(value, index) {
  354. var stringValue = value.toString();
  355. if (stringValue.match(pattern))
  356. results.push((iterator || Prototype.K)(value, index));
  357. })
  358. return results;
  359. },
  360. include: function(object) {
  361. var found = false;
  362. this.each(function(value) {
  363. if (value == object) {
  364. found = true;
  365. throw $break;
  366. }
  367. });
  368. return found;
  369. },
  370. inGroupsOf: function(number, fillWith) {
  371. fillWith = fillWith === undefined ? null : fillWith;
  372. return this.eachSlice(number, function(slice) {
  373. while(slice.length < number) slice.push(fillWith);
  374. return slice;
  375. });
  376. },
  377. inject: function(memo, iterator) {
  378. this.each(function(value, index) {
  379. memo = iterator(memo, value, index);
  380. });
  381. return memo;
  382. },
  383. invoke: function(method) {
  384. var args = $A(arguments).slice(1);
  385. return this.map(function(value) {
  386. return value[method].apply(value, args);
  387. });
  388. },
  389. max: function(iterator) {
  390. var result;
  391. this.each(function(value, index) {
  392. value = (iterator || Prototype.K)(value, index);
  393. if (result == undefined || value >= result)
  394. result = value;
  395. });
  396. return result;
  397. },
  398. min: function(iterator) {
  399. var result;
  400. this.each(function(value, index) {
  401. value = (iterator || Prototype.K)(value, index);
  402. if (result == undefined || value < result)
  403. result = value;
  404. });
  405. return result;
  406. },
  407. partition: function(iterator) {
  408. var trues = [], falses = [];
  409. this.each(function(value, index) {
  410. ((iterator || Prototype.K)(value, index) ?
  411. trues : falses).push(value);
  412. });
  413. return [trues, falses];
  414. },
  415. pluck: function(property) {
  416. var results = [];
  417. this.each(function(value, index) {
  418. results.push(value[property]);
  419. });
  420. return results;
  421. },
  422. reject: function(iterator) {
  423. var results = [];
  424. this.each(function(value, index) {
  425. if (!iterator(value, index))
  426. results.push(value);
  427. });
  428. return results;
  429. },
  430. sortBy: function(iterator) {
  431. return this.map(function(value, index) {
  432. return {value: value, criteria: iterator(value, index)};
  433. }).sort(function(left, right) {
  434. var a = left.criteria, b = right.criteria;
  435. return a < b ? -1 : a > b ? 1 : 0;
  436. }).pluck('value');
  437. },
  438. toArray: function() {
  439. return this.map();
  440. },
  441. zip: function() {
  442. var iterator = Prototype.K, args = $A(arguments);
  443. if (typeof args.last() == 'function')
  444. iterator = args.pop();
  445. var collections = [this].concat(args).map($A);
  446. return this.map(function(value, index) {
  447. return iterator(collections.pluck(index));
  448. });
  449. },
  450. size: function() {
  451. return this.toArray().length;
  452. },
  453. inspect: function() {
  454. return '#<Enumerable:' + this.toArray().inspect() + '>';
  455. }
  456. }
  457. Object.extend(Enumerable, {
  458. map: Enumerable.collect,
  459. find: Enumerable.detect,
  460. select: Enumerable.findAll,
  461. member: Enumerable.include,
  462. entries: Enumerable.toArray
  463. });
  464. var $A = Array.from = function(iterable) {
  465. if (!iterable) return [];
  466. if (iterable.toArray) {
  467. return iterable.toArray();
  468. } else {
  469. var results = [];
  470. for (var i = 0, length = iterable.length; i < length; i++)
  471. results.push(iterable[i]);
  472. return results;
  473. }
  474. }
  475. Object.extend(Array.prototype, Enumerable);
  476. if (!Array.prototype._reverse)
  477. Array.prototype._reverse = Array.prototype.reverse;
  478. Object.extend(Array.prototype, {
  479. _each: function(iterator) {
  480. for (var i = 0, length = this.length; i < length; i++)
  481. iterator(this[i]);
  482. },
  483. clear: function() {
  484. this.length = 0;
  485. return this;
  486. },
  487. first: function() {
  488. return this[0];
  489. },
  490. last: function() {
  491. return this[this.length - 1];
  492. },
  493. compact: function() {
  494. return this.select(function(value) {
  495. return value != null;
  496. });
  497. },
  498. flatten: function() {
  499. return this.inject([], function(array, value) {
  500. return array.concat(value && value.constructor == Array ?
  501. value.flatten() : [value]);
  502. });
  503. },
  504. without: function() {
  505. var values = $A(arguments);
  506. return this.select(function(value) {
  507. return !values.include(value);
  508. });
  509. },
  510. indexOf: function(object) {
  511. for (var i = 0, length = this.length; i < length; i++)
  512. if (this[i] == object) return i;
  513. return -1;
  514. },
  515. reverse: function(inline) {
  516. return (inline !== false ? this : this.toArray())._reverse();
  517. },
  518. reduce: function() {
  519. return this.length > 1 ? this : this[0];
  520. },
  521. uniq: function() {
  522. return this.inject([], function(array, value) {
  523. return array.include(value) ? array : array.concat([value]);
  524. });
  525. },
  526. clone: function() {
  527. return [].concat(this);
  528. },
  529. size: function() {
  530. return this.length;
  531. },
  532. inspect: function() {
  533. return '[' + this.map(Object.inspect).join(', ') + ']';
  534. }
  535. });
  536. Array.prototype.toArray = Array.prototype.clone;
  537. function $w(string){
  538. string = string.strip();
  539. return string ? string.split(/\s+/) : [];
  540. }
  541. if(window.opera){
  542. Array.prototype.concat = function(){
  543. var array = [];
  544. for(var i = 0, length = this.length; i < length; i++) array.push(this[i]);
  545. for(var i = 0, length = arguments.length; i < length; i++) {
  546. if(arguments[i].constructor == Array) {
  547. for(var j = 0, arrayLength = arguments[i].length; j < arrayLength; j++)
  548. array.push(arguments[i][j]);
  549. } else {
  550. array.push(arguments[i]);
  551. }
  552. }
  553. return array;
  554. }
  555. }
  556. var Hash = function(obj) {
  557. Object.extend(this, obj || {});
  558. };
  559. Object.extend(Hash, {
  560. toQueryString: function(obj) {
  561. var parts = [];
  562. this.prototype._each.call(obj, function(pair) {
  563. if (!pair.key) return;
  564. if (pair.value && pair.value.constructor == Array) {
  565. var values = pair.value.compact();
  566. if (values.length < 2) pair.value = values.reduce();
  567. else {
  568. key = encodeURIComponent(pair.key);
  569. values.each(function(value) {
  570. value = value != undefined ? encodeURIComponent(value) : '';
  571. parts.push(key + '=' + encodeURIComponent(value));
  572. });
  573. return;
  574. }
  575. }
  576. if (pair.value == undefined) pair[1] = '';
  577. parts.push(pair.map(encodeURIComponent).join('='));
  578. });
  579. return parts.join('&');
  580. }
  581. });
  582. Object.extend(Hash.prototype, Enumerable);
  583. Object.extend(Hash.prototype, {
  584. _each: function(iterator) {
  585. for (var key in this) {
  586. var value = this[key];
  587. if (value && value == Hash.prototype[key]) continue;
  588. var pair = [key, value];
  589. pair.key = key;
  590. pair.value = value;
  591. iterator(pair);
  592. }
  593. },
  594. keys: function() {
  595. return this.pluck('key');
  596. },
  597. values: function() {
  598. return this.pluck('value');
  599. },
  600. merge: function(hash) {
  601. return $H(hash).inject(this, function(mergedHash, pair) {
  602. mergedHash[pair.key] = pair.value;
  603. return mergedHash;
  604. });
  605. },
  606. remove: function() {
  607. var result;
  608. for(var i = 0, length = arguments.length; i < length; i++) {
  609. var value = this[arguments[i]];
  610. if (value !== undefined){
  611. if (result === undefined) result = value;
  612. else {
  613. if (result.constructor != Array) result = [result];
  614. result.push(value)
  615. }
  616. }
  617. delete this[arguments[i]];
  618. }
  619. return result;
  620. },
  621. toQueryString: function() {
  622. return Hash.toQueryString(this);
  623. },
  624. inspect: function() {
  625. return '#<Hash:{' + this.map(function(pair) {
  626. return pair.map(Object.inspect).join(': ');
  627. }).join(', ') + '}>';
  628. }
  629. });
  630. function $H(object) {
  631. if (object && object.constructor == Hash) return object;
  632. return new Hash(object);
  633. };
  634. ObjectRange = Class.create();
  635. Object.extend(ObjectRange.prototype, Enumerable);
  636. Object.extend(ObjectRange.prototype, {
  637. initialize: function(start, end, exclusive) {
  638. this.start = start;
  639. this.end = end;
  640. this.exclusive = exclusive;
  641. },
  642. _each: function(iterator) {
  643. var value = this.start;
  644. while (this.include(value)) {
  645. iterator(value);
  646. value = value.succ();
  647. }
  648. },
  649. include: function(value) {
  650. if (value < this.start)
  651. return false;
  652. if (this.exclusive)
  653. return value < this.end;
  654. return value <= this.end;
  655. }
  656. });
  657. var $R = function(start, end, exclusive) {
  658. return new ObjectRange(start, end, exclusive);
  659. }
  660. var Ajax = {
  661. getTransport: function() {
  662. return Try.these(
  663. function() {return new XMLHttpRequest()},
  664. function() {return new ActiveXObject('Msxml2.XMLHTTP')},
  665. function() {return new ActiveXObject('Microsoft.XMLHTTP')}
  666. ) || false;
  667. },
  668. activeRequestCount: 0
  669. }
  670. Ajax.Responders = {
  671. responders: [],
  672. _each: function(iterator) {
  673. this.responders._each(iterator);
  674. },
  675. register: function(responder) {
  676. if (!this.include(responder))
  677. this.responders.push(responder);
  678. },
  679. unregister: function(responder) {
  680. this.responders = this.responders.without(responder);
  681. },
  682. dispatch: function(callback, request, transport, json) {
  683. this.each(function(responder) {
  684. if (typeof responder[callback] == 'function') {
  685. try {
  686. responder[callback].apply(responder, [request, transport, json]);
  687. } catch (e) {}
  688. }
  689. });
  690. }
  691. };
  692. Object.extend(Ajax.Responders, Enumerable);
  693. Ajax.Responders.register({
  694. onCreate: function() {
  695. Ajax.activeRequestCount++;
  696. },
  697. onComplete: function() {
  698. Ajax.activeRequestCount--;
  699. }
  700. });
  701. Ajax.Base = function() {};
  702. Ajax.Base.prototype = {
  703. setOptions: function(options) {
  704. this.options = {
  705. method: 'post',
  706. asynchronous: true,
  707. contentType: 'application/x-www-form-urlencoded',
  708. encoding: 'UTF-8',
  709. parameters: ''
  710. }
  711. Object.extend(this.options, options || {});
  712. this.options.method = this.options.method.toLowerCase();
  713. if (typeof this.options.parameters == 'string')
  714. this.options.parameters = this.options.parameters.toQueryParams();
  715. }
  716. }
  717. Ajax.Request = Class.create();
  718. Ajax.Request.Events =
  719. ['Uninitialized', 'Loading', 'Loaded', 'Interactive', 'Complete'];
  720. Ajax.Request.prototype = Object.extend(new Ajax.Base(), {
  721. _complete: false,
  722. initialize: function(url, options) {
  723. this.transport = Ajax.getTransport();
  724. this.setOptions(options);
  725. this.request(url);
  726. },
  727. request: function(url) {
  728. this.url = url;
  729. this.method = this.options.method;
  730. var params = this.options.parameters;
  731. if (!['get', 'post'].include(this.method)) {
  732. // simulate other verbs over post
  733. params['_method'] = this.method;
  734. this.method = 'post';
  735. }
  736. params = Hash.toQueryString(params);
  737. if (params && /Konqueror|Safari|KHTML/.test(navigator.userAgent)) params += '&_='
  738. // when GET, append parameters to URL
  739. if (this.method == 'get' && params)
  740. this.url += (this.url.indexOf('?') > -1 ? '&' : '?') + params;
  741. try {
  742. Ajax.Responders.dispatch('onCreate', this, this.transport);
  743. this.transport.open(this.method.toUpperCase(), this.url,
  744. this.options.asynchronous);
  745. if (this.options.asynchronous)
  746. setTimeout(function() { this.respondToReadyState(1) }.bind(this), 10);
  747. this.transport.onreadystatechange = this.onStateChange.bind(this);
  748. this.setRequestHeaders();
  749. var body = this.method == 'post' ? (this.options.postBody || params) : null;
  750. this.transport.send(body);
  751. /* Force Firefox to handle ready state 4 for synchronous requests */
  752. if (!this.options.asynchronous && this.transport.overrideMimeType)
  753. this.onStateChange();
  754. }
  755. catch (e) {
  756. this.dispatchException(e);
  757. }
  758. },
  759. onStateChange: function() {
  760. var readyState = this.transport.readyState;
  761. if (readyState > 1 && !((readyState == 4) && this._complete))
  762. this.respondToReadyState(this.transport.readyState);
  763. },
  764. setRequestHeaders: function() {
  765. var headers = {
  766. 'X-Requested-With': 'XMLHttpRequest',
  767. 'X-Prototype-Version': Prototype.Version,
  768. 'Accept': 'text/javascript, text/html, application/xml, text/xml, */*'
  769. };
  770. if (this.method == 'post') {
  771. headers['Content-type'] = this.options.contentType +
  772. (this.options.encoding ? '; charset=' + this.options.encoding : '');
  773. /* Force "Connection: close" for older Mozilla browsers to work
  774. * around a bug where XMLHttpRequest sends an incorrect
  775. * Content-length header. See Mozilla Bugzilla #246651.
  776. */
  777. if (this.transport.overrideMimeType &&
  778. (navigator.userAgent.match(/Gecko\/(\d{4})/) || [0,2005])[1] < 2005)
  779. headers['Connection'] = 'close';
  780. }
  781. // user-defined headers
  782. if (typeof this.options.requestHeaders == 'object') {
  783. var extras = this.options.requestHeaders;
  784. if (typeof extras.push == 'function')
  785. for (var i = 0, length = extras.length; i < length; i += 2)
  786. headers[extras[i]] = extras[i+1];
  787. else
  788. $H(extras).each(function(pair) { headers[pair.key] = pair.value });
  789. }
  790. for (var name in headers)
  791. this.transport.setRequestHeader(name, headers[name]);
  792. },
  793. success: function() {
  794. return !this.transport.status
  795. || (this.transport.status >= 200 && this.transport.status < 300);
  796. },
  797. respondToReadyState: function(readyState) {
  798. var state = Ajax.Request.Events[readyState];
  799. var transport = this.transport, json = this.evalJSON();
  800. if (state == 'Complete') {
  801. try {
  802. this._complete = true;
  803. (this.options['on' + this.transport.status]
  804. || this.options['on' + (this.success() ? 'Success' : 'Failure')]
  805. || Prototype.emptyFunction)(transport, json);
  806. } catch (e) {
  807. this.dispatchException(e);
  808. }
  809. if ((this.getHeader('Content-type') || 'text/javascript').strip().
  810. match(/^(text|application)\/(x-)?(java|ecma)script(;.*)?$/i))
  811. this.evalResponse();
  812. }
  813. try {
  814. (this.options['on' + state] || Prototype.emptyFunction)(transport, json);
  815. Ajax.Responders.dispatch('on' + state, this, transport, json);
  816. } catch (e) {
  817. this.dispatchException(e);
  818. }
  819. if (state == 'Complete') {
  820. // avoid memory leak in MSIE: clean up
  821. this.transport.onreadystatechange = Prototype.emptyFunction;
  822. }
  823. },
  824. getHeader: function(name) {
  825. try {
  826. return this.transport.getResponseHeader(name);
  827. } catch (e) { return null }
  828. },
  829. evalJSON: function() {
  830. try {
  831. var json = this.getHeader('X-JSON');
  832. return json ? eval('(' + json + ')') : null;
  833. } catch (e) { return null }
  834. },
  835. evalResponse: function() {
  836. try {
  837. return eval(this.transport.responseText);
  838. } catch (e) {
  839. this.dispatchException(e);
  840. }
  841. },
  842. dispatchException: function(exception) {
  843. (this.options.onException || Prototype.emptyFunction)(this, exception);
  844. Ajax.Responders.dispatch('onException', this, exception);
  845. }
  846. });
  847. Ajax.Updater = Class.create();
  848. Object.extend(Object.extend(Ajax.Updater.prototype, Ajax.Request.prototype), {
  849. initialize: function(container, url, options) {
  850. this.container = {
  851. success: (container.success || container),
  852. failure: (container.failure || (container.success ? null : container))
  853. }
  854. this.transport = Ajax.getTransport();
  855. this.setOptions(options);
  856. var onComplete = this.options.onComplete || Prototype.emptyFunction;
  857. this.options.onComplete = (function(transport, param) {
  858. this.updateContent();
  859. onComplete(transport, param);
  860. }).bind(this);
  861. this.request(url);
  862. },
  863. updateContent: function() {
  864. var receiver = this.container[this.success() ? 'success' : 'failure'];
  865. var response = this.transport.responseText;
  866. if (!this.options.evalScripts) response = response.stripScripts();
  867. if (receiver = $(receiver)) {
  868. if (this.options.insertion)
  869. new this.options.insertion(receiver, response);
  870. else
  871. receiver.update(response);
  872. }
  873. if (this.success()) {
  874. if (this.onComplete)
  875. setTimeout(this.onComplete.bind(this), 10);
  876. }
  877. }
  878. });
  879. Ajax.PeriodicalUpdater = Class.create();
  880. Ajax.PeriodicalUpdater.prototype = Object.extend(new Ajax.Base(), {
  881. initialize: function(container, url, options) {
  882. this.setOptions(options);
  883. this.onComplete = this.options.onComplete;
  884. this.frequency = (this.options.frequency || 2);
  885. this.decay = (this.options.decay || 1);
  886. this.updater = {};
  887. this.container = container;
  888. this.url = url;
  889. this.start();
  890. },
  891. start: function() {
  892. this.options.onComplete = this.updateComplete.bind(this);
  893. this.onTimerEvent();
  894. },
  895. stop: function() {
  896. this.updater.options.onComplete = undefined;
  897. clearTimeout(this.timer);
  898. (this.onComplete || Prototype.emptyFunction).apply(this, arguments);
  899. },
  900. updateComplete: function(request) {
  901. if (this.options.decay) {
  902. this.decay = (request.responseText == this.lastText ?
  903. this.decay * this.options.decay : 1);
  904. this.lastText = request.responseText;
  905. }
  906. this.timer = setTimeout(this.onTimerEvent.bind(this),
  907. this.decay * this.frequency * 1000);
  908. },
  909. onTimerEvent: function() {
  910. this.updater = new Ajax.Updater(this.container, this.url, this.options);
  911. }
  912. });
  913. function $(element) {
  914. if (arguments.length > 1) {
  915. for (var i = 0, elements = [], length = arguments.length; i < length; i++)
  916. elements.push($(arguments[i]));
  917. return elements;
  918. }
  919. if (typeof element == 'string')
  920. element = document.getElementById(element);
  921. return Element.extend(element);
  922. }
  923. if (Prototype.BrowserFeatures.XPath) {
  924. document._getElementsByXPath = function(expression, parentElement) {
  925. var results = [];
  926. var query = document.evaluate(expression, $(parentElement) || document,
  927. null, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);
  928. for (var i = 0, length = query.snapshotLength; i < length; i++)
  929. results.push(query.snapshotItem(i));
  930. return results;
  931. };
  932. }
  933. document.getElementsByClassName = function(className, parentElement) {
  934. if (Prototype.BrowserFeatures.XPath) {
  935. var q = ".//*[contains(concat(' ', @class, ' '), ' " + className + " ')]";
  936. return document._getElementsByXPath(q, parentElement);
  937. } else {
  938. var children = ($(parentElement) || document.body).getElementsByTagName('*');
  939. var elements = [], child;
  940. for (var i = 0, length = children.length; i < length; i++) {
  941. child = children[i];
  942. if (Element.hasClassName(child, className))
  943. elements.push(Element.extend(child));
  944. }
  945. return elements;
  946. }
  947. };
  948. /*--------------------------------------------------------------------------*/
  949. if (!window.Element)
  950. var Element = new Object();
  951. Element.extend = function(element) {
  952. if (!element || _nativeExtensions || element.nodeType == 3) return element;
  953. if (!element._extended && element.tagName && element != window) {
  954. var methods = Object.clone(Element.Methods), cache = Element.extend.cache;
  955. if (element.tagName == 'FORM')
  956. Object.extend(methods, Form.Methods);
  957. if (['INPUT', 'TEXTAREA', 'SELECT'].include(element.tagName))
  958. Object.extend(methods, Form.Element.Methods);
  959. Object.extend(methods, Element.Methods.Simulated);
  960. for (var property in methods) {
  961. var value = methods[property];
  962. if (typeof value == 'function' && !(property in element))
  963. element[property] = cache.findOrStore(value);
  964. }
  965. }
  966. element._extended = true;
  967. return element;
  968. };
  969. Element.extend.cache = {
  970. findOrStore: function(value) {
  971. return this[value] = this[value] || function() {
  972. return value.apply(null, [this].concat($A(arguments)));
  973. }
  974. }
  975. };
  976. Element.Methods = {
  977. visible: function(element) {
  978. return $(element).style.display != 'none';
  979. },
  980. toggle: function(element) {
  981. element = $(element);
  982. Element[Element.visible(element) ? 'hide' : 'show'](element);
  983. return element;
  984. },
  985. hide: function(element) {
  986. $(element).style.display = 'none';
  987. return element;
  988. },
  989. show: function(element) {
  990. $(element).style.display = '';
  991. return element;
  992. },
  993. remove: function(element) {
  994. element = $(element);
  995. element.parentNode.removeChild(element);
  996. return element;
  997. },
  998. update: function(element, html) {
  999. html = typeof html == 'undefined' ? '' : html.toString();
  1000. $(element).innerHTML = html.stripScripts();
  1001. setTimeout(function() {html.evalScripts()}, 10);
  1002. return element;
  1003. },
  1004. replace: function(element, html) {
  1005. element = $(element);
  1006. html = typeof html == 'undefined' ? '' : html.toString();
  1007. if (element.outerHTML) {
  1008. element.outerHTML = html.stripScripts();
  1009. } else {
  1010. var range = element.ownerDocument.createRange();
  1011. range.selectNodeContents(element);
  1012. element.parentNode.replaceChild(
  1013. range.createContextualFragment(html.stripScripts()), element);
  1014. }
  1015. setTimeout(function() {html.evalScripts()}, 10);
  1016. return element;
  1017. },
  1018. inspect: function(element) {
  1019. element = $(element);
  1020. var result = '<' + element.tagName.toLowerCase();
  1021. $H({'id': 'id', 'className': 'class'}).each(function(pair) {
  1022. var property = pair.first(), attribute = pair.last();
  1023. var value = (element[property] || '').toString();
  1024. if (value) result += ' ' + attribute + '=' + value.inspect(true);
  1025. });
  1026. return result + '>';
  1027. },
  1028. recursivelyCollect: function(element, property) {
  1029. element = $(element);
  1030. var elements = [];
  1031. while (element = element[property])
  1032. if (element.nodeType == 1)
  1033. elements.push(Element.extend(element));
  1034. return elements;
  1035. },
  1036. ancestors: function(element) {
  1037. return $(element).recursivelyCollect('parentNode');
  1038. },
  1039. descendants: function(element) {
  1040. return $A($(element).getElementsByTagName('*'));
  1041. },
  1042. immediateDescendants: function(element) {
  1043. if (!(element = $(element).firstChild)) return [];
  1044. while (element && element.nodeType != 1) element = element.nextSibling;
  1045. if (element) return [element].concat($(element).nextSiblings());
  1046. return [];
  1047. },
  1048. previousSiblings: function(element) {
  1049. return $(element).recursivelyCollect('previousSibling');
  1050. },
  1051. nextSiblings: function(element) {
  1052. return $(element).recursivelyCollect('nextSibling');
  1053. },
  1054. siblings: function(element) {
  1055. element = $(element);
  1056. return element.previousSiblings().reverse().concat(element.nextSiblings());
  1057. },
  1058. match: function(element, selector) {
  1059. if (typeof selector == 'string')
  1060. selector = new Selector(selector);
  1061. return selector.match($(element));
  1062. },
  1063. up: function(element, expression, index) {
  1064. return Selector.findElement($(element).ancestors(), expression, index);
  1065. },
  1066. down: function(element, expression, index) {
  1067. return Selector.findElement($(element).descendants(), expression, index);
  1068. },
  1069. previous: function(element, expression, index) {
  1070. return Selector.findElement($(element).previousSiblings(), expression, index);
  1071. },
  1072. next: function(element, expression, index) {
  1073. return Selector.findElement($(element).nextSiblings(), expression, index);
  1074. },
  1075. getElementsBySelector: function() {
  1076. var args = $A(arguments), element = $(args.shift());
  1077. return Selector.findChildElements(element, args);
  1078. },
  1079. getElementsByClassName: function(element, className) {
  1080. return document.getElementsByClassName(className, element);
  1081. },
  1082. readAttribute: function(element, name) {
  1083. element = $(element);
  1084. if (document.all && !window.opera) {
  1085. var t = Element._attributeTranslations;
  1086. if (t.values[name]) return t.values[name](element, name);
  1087. if (t.names[name]) name = t.names[name];
  1088. var attribute = element.attributes[name];
  1089. if(attribute) return attribute.nodeValue;
  1090. }
  1091. return element.getAttribute(name);
  1092. },
  1093. getHeight: function(element) {
  1094. return $(element).getDimensions().height;
  1095. },
  1096. getWidth: function(element) {
  1097. return $(element).getDimensions().width;
  1098. },
  1099. classNames: function(element) {
  1100. return new Element.ClassNames(element);
  1101. },
  1102. hasClassName: function(element, className) {
  1103. if (!(element = $(element))) return;
  1104. var elementClassName = element.className;
  1105. if (elementClassName.length == 0) return false;
  1106. if (elementClassName == className ||
  1107. elementClassName.match(new RegExp("(^|\\s)" + className + "(\\s|$)")))
  1108. return true;
  1109. return false;
  1110. },
  1111. addClassName: function(element, className) {
  1112. if (!(element = $(element))) return;
  1113. Element.classNames(element).add(className);
  1114. return element;
  1115. },
  1116. removeClassName: function(element, className) {
  1117. if (!(element = $(element))) return;
  1118. Element.classNames(element).remove(className);
  1119. return element;
  1120. },
  1121. toggleClassName: function(element, className) {
  1122. if (!(element = $(element))) return;
  1123. Element.classNames(element)[element.hasClassName(className) ? 'remove' : 'add'](className);
  1124. return element;
  1125. },
  1126. observe: function() {
  1127. Event.observe.apply(Event, arguments);
  1128. return $A(arguments).first();
  1129. },
  1130. stopObserving: function() {
  1131. Event.stopObserving.apply(Event, arguments);
  1132. return $A(arguments).first();
  1133. },
  1134. // removes whitespace-only text node children
  1135. cleanWhitespace: function(element) {
  1136. element = $(element);
  1137. var node = element.firstChild;
  1138. while (node) {
  1139. var nextNode = node.nextSibling;
  1140. if (node.nodeType == 3 && !/\S/.test(node.nodeValue))
  1141. element.removeChild(node);
  1142. node = nextNode;
  1143. }
  1144. return element;
  1145. },
  1146. empty: function(element) {
  1147. return $(element).innerHTML.match(/^\s*$/);
  1148. },
  1149. descendantOf: function(element, ancestor) {
  1150. element = $(element), ancestor = $(ancestor);
  1151. while (element = element.parentNode)
  1152. if (element == ancestor) return true;
  1153. return false;
  1154. },
  1155. scrollTo: function(element) {
  1156. element = $(element);
  1157. var pos = Position.cumulativeOffset(element);
  1158. window.scrollTo(pos[0], pos[1]);
  1159. return element;
  1160. },
  1161. getStyle: function(element, style) {
  1162. element = $(element);
  1163. if (['float','cssFloat'].include(style))
  1164. style = (typeof element.style.styleFloat != 'undefined' ? 'styleFloat' : 'cssFloat');
  1165. style = style.camelize();
  1166. var value = element.style[style];
  1167. if (!value) {
  1168. if (document.defaultView && document.defaultView.getComputedStyle) {
  1169. var css = document.defaultView.getComputedStyle(element, null);
  1170. value = css ? css[style] : null;
  1171. } else if (element.currentStyle) {
  1172. value = element.currentStyle[style];
  1173. }
  1174. }
  1175. if((value == 'auto') && ['width','height'].include(style) && (element.getStyle('display') != 'none'))
  1176. value = element['offset'+style.capitalize()] + 'px';
  1177. if (window.opera && ['left', 'top', 'right', 'bottom'].include(style))
  1178. if (Element.getStyle(element, 'position') == 'static') value = 'auto';
  1179. if(style == 'opacity') {
  1180. if(value) return parseFloat(value);
  1181. if(value = (element.getStyle('filter') || '').match(/alpha\(opacity=(.*)\)/))
  1182. if(value[1]) return parseFloat(value[1]) / 100;
  1183. return 1.0;
  1184. }
  1185. return value == 'auto' ? null : value;
  1186. },
  1187. setStyle: function(element, style) {
  1188. element = $(element);
  1189. for (var name in style) {
  1190. var value = style[name];
  1191. if(name == 'opacity') {
  1192. if (value == 1) {
  1193. value = (/Gecko/.test(navigator.userAgent) &&
  1194. !/Konqueror|Safari|KHTML/.test(navigator.userAgent)) ? 0.999999 : 1.0;
  1195. if(/MSIE/.test(navigator.userAgent) && !window.opera)
  1196. element.style.filter = element.getStyle('filter').replace(/alpha\([^\)]*\)/gi,'');
  1197. } else if(value == '') {
  1198. if(/MSIE/.test(navigator.userAgent) && !window.opera)
  1199. element.style.filter = element.getStyle('filter').replace(/alpha\([^\)]*\)/gi,'');
  1200. } else {
  1201. if(value < 0.00001) value = 0;
  1202. if(/MSIE/.test(navigator.userAgent) && !window.opera)
  1203. element.style.filter = element.getStyle('filter').replace(/alpha\([^\)]*\)/gi,'') +
  1204. 'alpha(opacity='+value*100+')';
  1205. }
  1206. } else if(['float','cssFloat'].include(name)) name = (typeof element.style.styleFloat != 'undefined') ? 'styleFloat' : 'cssFloat';
  1207. element.style[name.camelize()] = value;
  1208. }
  1209. return element;
  1210. },
  1211. getDimensions: function(element) {
  1212. element = $(element);
  1213. var display = $(element).getStyle('display');
  1214. if (display != 'none' && display != null) // Safari bug
  1215. return {width: element.offsetWidth, height: element.offsetHeight};
  1216. // All *Width and *Height properties give 0 on elements with display none,
  1217. // so enable the element temporarily
  1218. var els = element.style;
  1219. var originalVisibility = els.visibility;
  1220. var originalPosition = els.position;
  1221. var originalDisplay = els.display;
  1222. els.visibility = 'hidden';
  1223. els.position = 'absolute';
  1224. els.display = 'block';
  1225. var originalWidth = element.clientWidth;
  1226. var originalHeight = element.clientHeight;
  1227. els.display = originalDisplay;
  1228. els.position = originalPosition;
  1229. els.visibility = originalVisibility;
  1230. return {width: originalWidth, height: originalHeight};
  1231. },
  1232. makePositioned: function(element) {
  1233. element = $(element);
  1234. var pos = Element.getStyle(element, 'position');
  1235. if (pos == 'static' || !pos) {
  1236. element._madePositioned = true;
  1237. element.style.position = 'relative';
  1238. // Opera returns the offset relative to the positioning context, when an
  1239. // element is position relative but top and left have not been defined
  1240. if (window.opera) {
  1241. element.style.top = 0;
  1242. element.style.left = 0;
  1243. }
  1244. }
  1245. return element;
  1246. },
  1247. undoPositioned: function(element) {
  1248. element = $(element);
  1249. if (element._madePositioned) {
  1250. element._madePositioned = undefined;
  1251. element.style.position =
  1252. element.style.top =
  1253. element.style.left =
  1254. element.style.bottom =
  1255. element.style.right = '';
  1256. }
  1257. return element;
  1258. },
  1259. makeClipping: function(element) {
  1260. element = $(element);
  1261. if (element._overflow) return element;
  1262. element._overflow = element.style.overflow || 'auto';
  1263. if ((Element.getStyle(element, 'overflow') || 'visible') != 'hidden')
  1264. element.style.overflow = 'hidden';
  1265. return element;
  1266. },
  1267. undoClipping: function(element) {
  1268. element = $(element);
  1269. if (!element._overflow) return element;
  1270. element.style.overflow = element._overflow == 'auto' ? '' : element._overflow;
  1271. element._overflow = null;
  1272. return element;
  1273. }
  1274. };
  1275. Object.extend(Element.Methods, {childOf: Element.Methods.descendantOf});
  1276. Element._attributeTranslations = {};
  1277. Element._attributeTranslations.names = {
  1278. colspan: "colSpan",
  1279. rowspan: "rowSpan",
  1280. valign: "vAlign",
  1281. datetime: "dateTime",
  1282. accesskey: "accessKey",
  1283. tabindex: "tabIndex",
  1284. enctype: "encType",
  1285. maxlength: "maxLength",
  1286. readonly: "readOnly",
  1287. longdesc: "longDesc"
  1288. };
  1289. Element._attributeTranslations.values = {
  1290. _getAttr: function(element, attribute) {
  1291. return element.getAttribute(attribute, 2);
  1292. },
  1293. _flag: function(element, attribute) {
  1294. return $(element).hasAttribute(attribute) ? attribute : null;
  1295. },
  1296. style: function(element) {
  1297. return element.style.cssText.toLowerCase();
  1298. },
  1299. title: function(element) {
  1300. var node = element.getAttributeNode('title');
  1301. return node.specified ? node.nodeValue : null;
  1302. }
  1303. };
  1304. Object.extend(Element._attributeTranslations.values, {
  1305. href: Element._attributeTranslations.values._getAttr,
  1306. src: Element._attributeTranslations.values._getAttr,
  1307. disabled: Element._attributeTranslations.values._flag,
  1308. checked: Element._attributeTranslations.values._flag,
  1309. readonly: Element._attributeTranslations.values._flag,
  1310. multiple: Element._attributeTranslations.values._flag
  1311. });
  1312. Element.Methods.Simulated = {
  1313. hasAttribute: function(element, attribute) {
  1314. var t = Element._attributeTranslations;
  1315. attribute = t.names[attribute] || attribute;
  1316. return $(element).getAttributeNode(attribute).specified;
  1317. }
  1318. };
  1319. // IE is missing .innerHTML support for TABLE-related elements
  1320. if (document.all && !window.opera){
  1321. Element.Methods.update = function(element, html) {
  1322. element = $(element);
  1323. html = typeof html == 'undefined' ? '' : html.toString();
  1324. var tagName = element.tagName.toUpperCase();
  1325. if (['THEAD','TBODY','TR','TD'].include(tagName)) {
  1326. var div = document.createElement('div');
  1327. switch (tagName) {
  1328. case 'THEAD':
  1329. case 'TBODY':
  1330. div.innerHTML = '<table><tbody>' + html.stripScripts() + '</tbody></table>';
  1331. depth = 2;
  1332. break;
  1333. case 'TR':
  1334. div.innerHTML = '<table><tbody><tr>' + html.stripScripts() + '</tr></tbody></table>';
  1335. depth = 3;
  1336. break;
  1337. case 'TD':
  1338. div.innerHTML = '<table><tbody><tr><td>' + html.stripScripts() + '</td></tr></tbody></table>';
  1339. depth = 4;
  1340. }
  1341. $A(element.childNodes).each(function(node){
  1342. element.removeChild(node)
  1343. });
  1344. depth.times(function(){ div = div.firstChild });
  1345. $A(div.childNodes).each(
  1346. function(node){ element.appendChild(node) });
  1347. } else {
  1348. element.innerHTML = html.stripScripts();
  1349. }
  1350. setTimeout(function() {html.evalScripts()}, 10);
  1351. return element;
  1352. }
  1353. };
  1354. Object.extend(Element, Element.Methods);
  1355. var _nativeExtensions = false;
  1356. if(/Konqueror|Safari|KHTML/.test(navigator.userAgent))
  1357. ['', 'Form', 'Input', 'TextArea', 'Select'].each(function(tag) {
  1358. var className = 'HTML' + tag + 'Element';
  1359. if(window[className]) return;
  1360. var klass = window[className] = {};
  1361. klass.prototype = document.createElement(tag ? tag.toLowerCase() : 'div').__proto__;
  1362. });
  1363. Element.addMethods = function(methods) {
  1364. Object.extend(Element.Methods, methods || {});
  1365. function copy(methods, destination, onlyIfAbsent) {
  1366. onlyIfAbsent = onlyIfAbsent || false;
  1367. var cache = Element.extend.cache;
  1368. for (var property in methods) {
  1369. var value = methods[property];
  1370. if (!onlyIfAbsent || !(property in destination))
  1371. destination[property] = cache.findOrStore(value);
  1372. }
  1373. }
  1374. if (typeof HTMLElement != 'undefined') {
  1375. copy(Element.Methods, HTMLElement.prototype);
  1376. copy(Element.Methods.Simulated, HTMLElement.prototype, true);
  1377. copy(Form.Methods, HTMLFormElement.prototype);
  1378. [HTMLInputElement, HTMLTextAreaElement, HTMLSelectElement].each(function(klass) {
  1379. copy(Form.Element.Methods, klass.prototype);
  1380. });
  1381. _nativeExtensions = true;
  1382. }
  1383. }
  1384. var Toggle = new Object();
  1385. Toggle.display = Element.toggle;
  1386. /*--------------------------------------------------------------------------*/
  1387. Abstract.Insertion = function(adjacency) {
  1388. this.adjacency = adjacency;
  1389. }
  1390. Abstract.Insertion.prototype = {
  1391. initialize: function(element, content) {
  1392. this.element = $(element);
  1393. this.content = content.stripScripts();
  1394. if (this.adjacency && this.element.insertAdjacentHTML) {
  1395. try {
  1396. this.element.insertAdjacentHTML(this.adjacency, this.content);
  1397. } catch (e) {
  1398. var tagName = this.element.tagName.toUpperCase();
  1399. if (['TBODY', 'TR'].include(tagName)) {
  1400. this.insertContent(this.contentFromAnonymousTable());
  1401. } else {
  1402. throw e;
  1403. }
  1404. }
  1405. } else {
  1406. this.range = this.element.ownerDocument.createRange();
  1407. if (this.initializeRange) this.initializeRange();
  1408. this.insertContent([this.range.createContextualFragment(this.content)]);
  1409. }
  1410. setTimeout(function() {content.evalScripts()}, 10);
  1411. },
  1412. contentFromAnonymousTable: function() {
  1413. var div = document.createElement('div');
  1414. div.innerHTML = '<table><tbody>' + this.content + '</tbody></table>';
  1415. return $A(div.childNodes[0].childNodes[0].childNodes);
  1416. }
  1417. }
  1418. var Insertion = new Object();
  1419. Insertion.Before = Class.create();
  1420. Insertion.Before.prototype = Object.extend(new Abstract.Insertion('beforeBegin'), {
  1421. initializeRange: function() {
  1422. this.range.setStartBefore(this.element);
  1423. },
  1424. insertContent: function(fragments) {
  1425. fragments.each((function(fragment) {
  1426. this.element.parentNode.insertBefore(fragment, this.element);
  1427. }).bind(this));
  1428. }
  1429. });
  1430. Insertion.Top = Class.create();
  1431. Insertion.Top.prototype = Object.extend(new Abstract.Insertion('afterBegin'), {
  1432. initializeRange: function() {
  1433. this.range.selectNodeContents(this.element);
  1434. this.range.collapse(true);
  1435. },
  1436. insertContent: function(fragments) {
  1437. fragments.reverse(false).each((function(fragment) {
  1438. this.element.insertBefore(fragment, this.element.firstChild);
  1439. }).bind(this));
  1440. }
  1441. });
  1442. Insertion.Bottom = Class.create();
  1443. Insertion.Bottom.prototype = Object.extend(new Abstract.Insertion('beforeEnd'), {
  1444. initializeRange: function() {
  1445. this.range.selectNodeContents(this.element);
  1446. this.range.collapse(this.element);
  1447. },
  1448. insertContent: function(fragments) {
  1449. fragments.each((function(fragment) {
  1450. this.element.appendChild(fragment);
  1451. }).bind(this));
  1452. }
  1453. });
  1454. Insertion.After = Class.create();
  1455. Insertion.After.prototype = Object.extend(new Abstract.Insertion('afterEnd'), {
  1456. initializeRange: function() {
  1457. this.range.setStartAfter(this.element);
  1458. },
  1459. insertContent: function(fragments) {
  1460. fragments.each((function(fragment) {
  1461. this.element.parentNode.insertBefore(fragment,
  1462. this.element.nextSibling);
  1463. }).bind(this));
  1464. }
  1465. });
  1466. /*--------------------------------------------------------------------------*/
  1467. Element.ClassNames = Class.create();
  1468. Element.ClassNames.prototype = {
  1469. initialize: function(element) {
  1470. this.element = $(element);
  1471. },
  1472. _each: function(iterator) {
  1473. this.element.className.split(/\s+/).select(function(name) {
  1474. return name.length > 0;
  1475. })._each(iterator);
  1476. },
  1477. set: function(className) {
  1478. this.element.className = className;
  1479. },
  1480. add: function(classNameToAdd) {
  1481. if (this.include(classNameToAdd)) return;
  1482. this.set($A(this).concat(classNameToAdd).join(' '));
  1483. },
  1484. remove: function(classNameToRemove) {
  1485. if (!this.include(classNameToRemove)) return;
  1486. this.set($A(this).without(classNameToRemove).join(' '));
  1487. },
  1488. toString: function() {
  1489. return $A(this).join(' ');
  1490. }
  1491. };
  1492. Object.extend(Element.ClassNames.prototype, Enumerable);
  1493. var Selector = Class.create();
  1494. Selector.prototype = {
  1495. initialize: function(expression) {
  1496. this.params = {classNames: []};
  1497. this.expression = expression.toString().strip();
  1498. this.parseExpression();
  1499. this.compileMatcher();
  1500. },
  1501. parseExpression: function() {
  1502. function abort(message) { throw 'Parse error in selector: ' + message; }
  1503. if (this.expression == '') abort('empty expression');
  1504. var params = this.params, expr = this.expression, match, modifier, clause, rest;
  1505. while (match = expr.match(/^(.*)\[([a-z0-9_:-]+?)(?:([~\|!]?=)(?:"([^"]*)"|([^\]\s]*)))?\]$/i)) {
  1506. params.attributes = params.attributes || [];
  1507. params.attributes.push({name: match[2], operator

Large files files are truncated, but you can click here to view the full file