PageRenderTime 84ms CodeModel.GetById 23ms RepoModel.GetById 1ms app.codeStats 0ms

/dom/tests/mochitest/ajax/prototype/dist/prototype.js

http://github.com/zpao/v8monkey
JavaScript | 4681 lines | 4594 code | 78 blank | 9 comment | 83 complexity | a288125ff0fb9c7f273efaebf448cc51 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
  1. /* Prototype JavaScript framework, version 1.6.0.2
  2. * (c) 2005-2007 Sam Stephenson
  3. *
  4. * Prototype is freely distributable under the terms of an MIT-style license.
  5. * For details, see the Prototype web site: http://www.prototypejs.org/
  6. *
  7. *--------------------------------------------------------------------------*/
  8. var Prototype = {
  9. Version: '1.6.0.2',
  10. Browser: {
  11. IE: !!(window.attachEvent && !window.opera),
  12. Opera: !!window.opera,
  13. WebKit: navigator.userAgent.indexOf('AppleWebKit/') > -1,
  14. Gecko: navigator.userAgent.indexOf('Gecko') > -1 && navigator.userAgent.indexOf('KHTML') == -1,
  15. MobileSafari: !!navigator.userAgent.match(/Apple.*Mobile.*Safari/)
  16. },
  17. BrowserFeatures: {
  18. XPath: !!document.evaluate,
  19. SelectorsAPI: !!document.querySelector,
  20. ElementExtensions: !!window.HTMLElement,
  21. SpecificElementExtensions:
  22. document.createElement('div')['__proto__'] &&
  23. document.createElement('div')['__proto__'] !==
  24. document.createElement('form')['__proto__']
  25. },
  26. ScriptFragment: '<script[^>]*>([^\\x00]*?)<\/script>',
  27. JSONFilter: /^\/\*-secure-([\s\S]*)\*\/\s*$/,
  28. emptyFunction: function() { },
  29. K: function(x) { return x }
  30. };
  31. if (Prototype.Browser.MobileSafari)
  32. Prototype.BrowserFeatures.SpecificElementExtensions = false;
  33. /* Based on Alex Arnell's inheritance implementation. */
  34. var Class = {
  35. create: function() {
  36. var parent = null, properties = $A(arguments);
  37. if (Object.isFunction(properties[0]))
  38. parent = properties.shift();
  39. function klass() {
  40. this.initialize.apply(this, arguments);
  41. }
  42. Object.extend(klass, Class.Methods);
  43. klass.superclass = parent;
  44. klass.subclasses = [];
  45. if (parent) {
  46. var subclass = function() { };
  47. subclass.prototype = parent.prototype;
  48. klass.prototype = new subclass;
  49. parent.subclasses.push(klass);
  50. }
  51. for (var i = 0; i < properties.length; i++)
  52. klass.addMethods(properties[i]);
  53. if (!klass.prototype.initialize)
  54. klass.prototype.initialize = Prototype.emptyFunction;
  55. klass.prototype.constructor = klass;
  56. return klass;
  57. }
  58. };
  59. Class.Methods = {
  60. addMethods: function(source) {
  61. var ancestor = this.superclass && this.superclass.prototype;
  62. var properties = Object.keys(source);
  63. if (!Object.keys({ toString: true }).length)
  64. properties.push("toString", "valueOf");
  65. for (var i = 0, length = properties.length; i < length; i++) {
  66. var property = properties[i], value = source[property];
  67. if (ancestor && Object.isFunction(value) &&
  68. value.argumentNames().first() == "$super") {
  69. var method = value, value = (function(m) {
  70. return function() { return ancestor[m].apply(this, arguments) };
  71. })(property).wrap(method);
  72. value.valueOf = method.valueOf.bind(method);
  73. value.toString = method.toString.bind(method);
  74. }
  75. this.prototype[property] = value;
  76. }
  77. return this;
  78. }
  79. };
  80. var Abstract = { };
  81. Object.extend = function(destination, source) {
  82. for (var property in source)
  83. destination[property] = source[property];
  84. return destination;
  85. };
  86. Object.extend(Object, {
  87. inspect: function(object) {
  88. try {
  89. if (Object.isUndefined(object)) return 'undefined';
  90. if (object === null) return 'null';
  91. return object.inspect ? object.inspect() : String(object);
  92. } catch (e) {
  93. if (e instanceof RangeError) return '...';
  94. throw e;
  95. }
  96. },
  97. toJSON: function(object) {
  98. var type = typeof object;
  99. switch (type) {
  100. case 'undefined':
  101. case 'function':
  102. case 'unknown': return;
  103. case 'boolean': return object.toString();
  104. }
  105. if (object === null) return 'null';
  106. if (object.toJSON) return object.toJSON();
  107. if (Object.isElement(object)) return;
  108. var results = [];
  109. for (var property in object) {
  110. var value = Object.toJSON(object[property]);
  111. if (!Object.isUndefined(value))
  112. results.push(property.toJSON() + ': ' + value);
  113. }
  114. return '{' + results.join(', ') + '}';
  115. },
  116. toQueryString: function(object) {
  117. return $H(object).toQueryString();
  118. },
  119. toHTML: function(object) {
  120. return object && object.toHTML ? object.toHTML() : String.interpret(object);
  121. },
  122. keys: function(object) {
  123. var keys = [];
  124. for (var property in object)
  125. keys.push(property);
  126. return keys;
  127. },
  128. values: function(object) {
  129. var values = [];
  130. for (var property in object)
  131. values.push(object[property]);
  132. return values;
  133. },
  134. clone: function(object) {
  135. return Object.extend({ }, object);
  136. },
  137. isElement: function(object) {
  138. return !!(object && object.nodeType == 1);
  139. },
  140. isArray: function(object) {
  141. return object != null && typeof object == "object" &&
  142. 'splice' in object && 'join' in object;
  143. },
  144. isHash: function(object) {
  145. return object && object instanceof Hash;
  146. },
  147. isFunction: function(object) {
  148. return typeof object == "function" && typeof object.call == "function";
  149. },
  150. isString: function(object) {
  151. return typeof object == "string";
  152. },
  153. isNumber: function(object) {
  154. return typeof object == "number";
  155. },
  156. isUndefined: function(object) {
  157. return typeof object == "undefined";
  158. }
  159. });
  160. Object.extend(Function.prototype, {
  161. argumentNames: function() {
  162. var names = this.toString().match(/^[\s\(]*function[^(]*\(([^\)]*)\)/)[1]
  163. .replace(/\s+/g, '').split(',');
  164. return names.length == 1 && !names[0] ? [] : names;
  165. },
  166. bind: function() {
  167. if (arguments.length < 2 && Object.isUndefined(arguments[0])) return this;
  168. var __method = this, args = $A(arguments), object = args.shift();
  169. return function() {
  170. return __method.apply(object, args.concat($A(arguments)));
  171. }
  172. },
  173. bindAsEventListener: function() {
  174. var __method = this, args = $A(arguments), object = args.shift();
  175. return function(event) {
  176. return __method.apply(object, [event || window.event].concat(args));
  177. }
  178. },
  179. curry: function() {
  180. if (!arguments.length) return this;
  181. var __method = this, args = $A(arguments);
  182. return function() {
  183. return __method.apply(this, args.concat($A(arguments)));
  184. }
  185. },
  186. delay: function() {
  187. var __method = this, args = $A(arguments), timeout = args.shift() * 1000;
  188. return window.setTimeout(function() {
  189. return __method.apply(__method, args);
  190. }, timeout);
  191. },
  192. defer: function() {
  193. var args = [0.01].concat($A(arguments));
  194. return this.delay.apply(this, args);
  195. },
  196. wrap: function(wrapper) {
  197. var __method = this;
  198. return function() {
  199. return wrapper.apply(this, [__method.bind(this)].concat($A(arguments)));
  200. }
  201. },
  202. methodize: function() {
  203. if (this._methodized) return this._methodized;
  204. var __method = this;
  205. return this._methodized = function() {
  206. return __method.apply(null, [this].concat($A(arguments)));
  207. };
  208. }
  209. });
  210. Date.prototype.toJSON = function() {
  211. return '"' + this.getUTCFullYear() + '-' +
  212. (this.getUTCMonth() + 1).toPaddedString(2) + '-' +
  213. this.getUTCDate().toPaddedString(2) + 'T' +
  214. this.getUTCHours().toPaddedString(2) + ':' +
  215. this.getUTCMinutes().toPaddedString(2) + ':' +
  216. this.getUTCSeconds().toPaddedString(2) + 'Z"';
  217. };
  218. var Try = {
  219. these: function() {
  220. var returnValue;
  221. for (var i = 0, length = arguments.length; i < length; i++) {
  222. var lambda = arguments[i];
  223. try {
  224. returnValue = lambda();
  225. break;
  226. } catch (e) { }
  227. }
  228. return returnValue;
  229. }
  230. };
  231. RegExp.prototype.match = RegExp.prototype.test;
  232. RegExp.escape = function(str) {
  233. return String(str).replace(/([.*+?^=!:${}()|[\]\/\\])/g, '\\$1');
  234. };
  235. /*--------------------------------------------------------------------------*/
  236. var PeriodicalExecuter = Class.create({
  237. initialize: function(callback, frequency) {
  238. this.callback = callback;
  239. this.frequency = frequency;
  240. this.currentlyExecuting = false;
  241. this.registerCallback();
  242. },
  243. registerCallback: function() {
  244. this.timer = setInterval(this.onTimerEvent.bind(this), this.frequency * 1000);
  245. },
  246. execute: function() {
  247. this.callback(this);
  248. },
  249. stop: function() {
  250. if (!this.timer) return;
  251. clearInterval(this.timer);
  252. this.timer = null;
  253. },
  254. onTimerEvent: function() {
  255. if (!this.currentlyExecuting) {
  256. try {
  257. this.currentlyExecuting = true;
  258. this.execute();
  259. } finally {
  260. this.currentlyExecuting = false;
  261. }
  262. }
  263. }
  264. });
  265. Object.extend(String, {
  266. interpret: function(value) {
  267. return value == null ? '' : String(value);
  268. },
  269. specialChar: {
  270. '\b': '\\b',
  271. '\t': '\\t',
  272. '\n': '\\n',
  273. '\f': '\\f',
  274. '\r': '\\r',
  275. '\\': '\\\\'
  276. }
  277. });
  278. Object.extend(String.prototype, {
  279. gsub: function(pattern, replacement) {
  280. var result = '', source = this, match;
  281. replacement = arguments.callee.prepareReplacement(replacement);
  282. while (source.length > 0) {
  283. if (match = source.match(pattern)) {
  284. result += source.slice(0, match.index);
  285. result += String.interpret(replacement(match));
  286. source = source.slice(match.index + match[0].length);
  287. } else {
  288. result += source, source = '';
  289. }
  290. }
  291. return result;
  292. },
  293. sub: function(pattern, replacement, count) {
  294. replacement = this.gsub.prepareReplacement(replacement);
  295. count = Object.isUndefined(count) ? 1 : count;
  296. return this.gsub(pattern, function(match) {
  297. if (--count < 0) return match[0];
  298. return replacement(match);
  299. });
  300. },
  301. scan: function(pattern, iterator) {
  302. this.gsub(pattern, iterator);
  303. return String(this);
  304. },
  305. truncate: function(length, truncation) {
  306. length = length || 30;
  307. truncation = Object.isUndefined(truncation) ? '...' : truncation;
  308. return this.length > length ?
  309. this.slice(0, length - truncation.length) + truncation : String(this);
  310. },
  311. strip: function() {
  312. return this.replace(/^\s+/, '').replace(/\s+$/, '');
  313. },
  314. stripTags: function() {
  315. return this.replace(/<\/?[^>]+>/gi, '');
  316. },
  317. stripScripts: function() {
  318. return this.replace(new RegExp(Prototype.ScriptFragment, 'img'), '');
  319. },
  320. extractScripts: (function() {
  321. var matchAll = new RegExp(Prototype.ScriptFragment, 'ig');
  322. var matchOne = new RegExp(Prototype.ScriptFragment, 'i');
  323. var matchComments = new RegExp('<!--\\s*' + Prototype.ScriptFragment + '\\s*-->', 'i');
  324. return function() {
  325. if (this.indexOf('<script') == -1) return [];
  326. return (this.replace(matchComments, '').match(matchAll) || []).map(function(scriptTag) {
  327. return (scriptTag.match(matchOne) || ['', ''])[1];
  328. });
  329. }
  330. })(),
  331. evalScripts: function() {
  332. return this.extractScripts().map(function(script) { return eval(script) });
  333. },
  334. escapeHTML: function() {
  335. var self = arguments.callee;
  336. self.text.data = this;
  337. return self.container.innerHTML.replace(/"/g, '&quot;');
  338. },
  339. unescapeHTML: function() {
  340. var div = new Element('div');
  341. // Safari requires the text nested inside another element to render correctly
  342. div.innerHTML = '<pre>' + this.stripTags() + '</pre>';
  343. div = div.firstChild;
  344. return div.childNodes[0] ? (div.childNodes.length > 1 ?
  345. $A(div.childNodes).inject('', function(memo, node) { return memo + node.nodeValue }) :
  346. div.childNodes[0].nodeValue) : '';
  347. },
  348. toQueryParams: function(separator) {
  349. var match = this.strip().match(/([^?#]*)(#.*)?$/);
  350. if (!match) return { };
  351. return match[1].split(separator || '&').inject({ }, function(hash, pair) {
  352. if ((pair = pair.split('='))[0]) {
  353. var key = decodeURIComponent(pair.shift());
  354. var value = pair.length > 1 ? pair.join('=') : pair[0];
  355. if (value != undefined) value = decodeURIComponent(value);
  356. if (key in hash) {
  357. if (!Object.isArray(hash[key])) hash[key] = [hash[key]];
  358. hash[key].push(value);
  359. }
  360. else hash[key] = value;
  361. }
  362. return hash;
  363. });
  364. },
  365. toArray: function() {
  366. return this.split('');
  367. },
  368. succ: function() {
  369. return this.slice(0, this.length - 1) +
  370. String.fromCharCode(this.charCodeAt(this.length - 1) + 1);
  371. },
  372. times: function(count) {
  373. return count < 1 ? '' : new Array(count + 1).join(this);
  374. },
  375. camelize: function() {
  376. var parts = this.split('-'), len = parts.length;
  377. if (len == 1) return parts[0];
  378. var camelized = this.charAt(0) == '-'
  379. ? parts[0].charAt(0).toUpperCase() + parts[0].substring(1)
  380. : parts[0];
  381. for (var i = 1; i < len; i++)
  382. camelized += parts[i].charAt(0).toUpperCase() + parts[i].substring(1);
  383. return camelized;
  384. },
  385. capitalize: function() {
  386. return this.charAt(0).toUpperCase() + this.substring(1).toLowerCase();
  387. },
  388. underscore: function() {
  389. return this.gsub(/::/, '/').gsub(/([A-Z]+)([A-Z][a-z])/,'#{1}_#{2}').gsub(/([a-z\d])([A-Z])/,'#{1}_#{2}').gsub(/-/,'_').toLowerCase();
  390. },
  391. dasherize: function() {
  392. return this.gsub(/_/,'-');
  393. },
  394. inspect: function(useDoubleQuotes) {
  395. var escapedString = this.gsub(/[\x00-\x1f\\]/, function(match) {
  396. var character = String.specialChar[match[0]];
  397. return character ? character : '\\u00' + match[0].charCodeAt().toPaddedString(2, 16);
  398. });
  399. if (useDoubleQuotes) return '"' + escapedString.replace(/"/g, '\\"') + '"';
  400. return "'" + escapedString.replace(/'/g, '\\\'') + "'";
  401. },
  402. toJSON: function() {
  403. return this.inspect(true);
  404. },
  405. unfilterJSON: function(filter) {
  406. return this.sub(filter || Prototype.JSONFilter, '#{1}');
  407. },
  408. isJSON: function() {
  409. var str = this;
  410. if (str.blank()) return false;
  411. str = this.replace(/\\./g, '@').replace(/"[^"\\\n\r]*"/g, '');
  412. return (/^[,:{}\[\]0-9.\-+Eaeflnr-u \n\r\t]*$/).test(str);
  413. },
  414. evalJSON: function(sanitize) {
  415. var json = this.unfilterJSON();
  416. try {
  417. if (!sanitize || json.isJSON()) return eval('(' + json + ')');
  418. } catch (e) { }
  419. throw new SyntaxError('Badly formed JSON string: ' + this.inspect());
  420. },
  421. include: function(pattern) {
  422. return this.indexOf(pattern) > -1;
  423. },
  424. startsWith: function(pattern) {
  425. return this.indexOf(pattern) === 0;
  426. },
  427. endsWith: function(pattern) {
  428. var d = this.length - pattern.length;
  429. return d >= 0 && this.lastIndexOf(pattern) === d;
  430. },
  431. empty: function() {
  432. return this == '';
  433. },
  434. blank: function() {
  435. return /^\s*$/.test(this);
  436. },
  437. interpolate: function(object, pattern) {
  438. return new Template(this, pattern).evaluate(object);
  439. }
  440. });
  441. String.prototype.gsub.prepareReplacement = function(replacement) {
  442. if (Object.isFunction(replacement)) return replacement;
  443. var template = new Template(replacement);
  444. return function(match) { return template.evaluate(match) };
  445. };
  446. String.prototype.parseQuery = String.prototype.toQueryParams;
  447. Object.extend(String.prototype.escapeHTML, {
  448. container: document.createElement('pre'),
  449. text: document.createTextNode('')
  450. });
  451. String.prototype.escapeHTML.container.appendChild(String.prototype.escapeHTML.text);
  452. if (Prototype.Browser.IE) {
  453. // IE converts all newlines to carriage returns so we swap them back
  454. String.prototype.unescapeHTML = String.prototype.unescapeHTML.wrap(function(proceed) {
  455. return proceed().replace(/\r/g, '\n')
  456. });
  457. }
  458. if ('>'.escapeHTML() !== '&gt;') {
  459. // Safari 3.x has issues with escaping the ">" character
  460. (function() {
  461. var escapeHTML = String.prototype.escapeHTML;
  462. Object.extend(
  463. String.prototype.escapeHTML = escapeHTML.wrap(function(proceed) {
  464. return proceed().replace(/>/g, "&gt;")
  465. }), {
  466. container: escapeHTML.container,
  467. text: escapeHTML.text
  468. })
  469. })();
  470. }
  471. if ('&'.escapeHTML() !== '&amp;') {
  472. // Safari 2.x has issues with escaping html inside a "pre" element so we use the deprecated "xmp" element instead
  473. Object.extend(String.prototype.escapeHTML, {
  474. container: document.createElement('xmp'),
  475. text: document.createTextNode('')
  476. });
  477. String.prototype.escapeHTML.container.appendChild(String.prototype.escapeHTML.text);
  478. }
  479. var Template = Class.create({
  480. initialize: function(template, pattern) {
  481. this.template = template.toString();
  482. this.pattern = pattern || Template.Pattern;
  483. },
  484. evaluate: function(object) {
  485. if (Object.isFunction(object.toTemplateReplacements))
  486. object = object.toTemplateReplacements();
  487. return this.template.gsub(this.pattern, function(match) {
  488. if (object == null) return '';
  489. var before = match[1] || '';
  490. if (before == '\\') return match[2];
  491. var ctx = object, expr = match[3];
  492. var pattern = /^([^.[]+|\[((?:.*?[^\\])?)\])(\.|\[|$)/;
  493. match = pattern.exec(expr);
  494. if (match == null) return before;
  495. while (match != null) {
  496. var comp = match[1].startsWith('[') ? match[2].gsub('\\\\]', ']') : match[1];
  497. ctx = ctx[comp];
  498. if (null == ctx || '' == match[3]) break;
  499. expr = expr.substring('[' == match[3] ? match[1].length : match[0].length);
  500. match = pattern.exec(expr);
  501. }
  502. return before + String.interpret(ctx);
  503. });
  504. }
  505. });
  506. Template.Pattern = /(^|.|\r|\n)(#\{(.*?)\})/;
  507. var $break = { };
  508. var Enumerable = {
  509. each: function(iterator, context) {
  510. var index = 0;
  511. try {
  512. this._each(function(value) {
  513. iterator.call(context, value, index++);
  514. });
  515. } catch (e) {
  516. if (e != $break) throw e;
  517. }
  518. return this;
  519. },
  520. eachSlice: function(number, iterator, context) {
  521. var index = -number, slices = [], array = this.toArray();
  522. if (number < 1) return array;
  523. while ((index += number) < array.length)
  524. slices.push(array.slice(index, index+number));
  525. return slices.collect(iterator, context);
  526. },
  527. all: function(iterator, context) {
  528. iterator = iterator || Prototype.K;
  529. var result = true;
  530. this.each(function(value, index) {
  531. result = result && !!iterator.call(context, value, index);
  532. if (!result) throw $break;
  533. });
  534. return result;
  535. },
  536. any: function(iterator, context) {
  537. iterator = iterator || Prototype.K;
  538. var result = false;
  539. this.each(function(value, index) {
  540. if (result = !!iterator.call(context, value, index))
  541. throw $break;
  542. });
  543. return result;
  544. },
  545. collect: function(iterator, context) {
  546. iterator = iterator || Prototype.K;
  547. var results = [];
  548. this.each(function(value, index) {
  549. results.push(iterator.call(context, value, index));
  550. });
  551. return results;
  552. },
  553. detect: function(iterator, context) {
  554. var result;
  555. this.each(function(value, index) {
  556. if (iterator.call(context, value, index)) {
  557. result = value;
  558. throw $break;
  559. }
  560. });
  561. return result;
  562. },
  563. findAll: function(iterator, context) {
  564. var results = [];
  565. this.each(function(value, index) {
  566. if (iterator.call(context, value, index))
  567. results.push(value);
  568. });
  569. return results;
  570. },
  571. grep: function(filter, iterator, context) {
  572. iterator = iterator || Prototype.K;
  573. var results = [];
  574. if (Object.isString(filter))
  575. filter = new RegExp(filter);
  576. this.each(function(value, index) {
  577. if (filter.match(value))
  578. results.push(iterator.call(context, value, index));
  579. });
  580. return results;
  581. },
  582. include: function(object) {
  583. if (Object.isFunction(this.indexOf))
  584. if (this.indexOf(object) != -1) return true;
  585. var found = false;
  586. this.each(function(value) {
  587. if (value == object) {
  588. found = true;
  589. throw $break;
  590. }
  591. });
  592. return found;
  593. },
  594. inGroupsOf: function(number, fillWith) {
  595. fillWith = Object.isUndefined(fillWith) ? null : fillWith;
  596. return this.eachSlice(number, function(slice) {
  597. while (slice.length < number) slice.push(fillWith);
  598. return slice;
  599. });
  600. },
  601. inject: function(memo, iterator, context) {
  602. this.each(function(value, index) {
  603. memo = iterator.call(context, memo, value, index);
  604. });
  605. return memo;
  606. },
  607. invoke: function(method) {
  608. var args = $A(arguments).slice(1);
  609. return this.map(function(value) {
  610. return value[method].apply(value, args);
  611. });
  612. },
  613. max: function(iterator, context) {
  614. iterator = iterator || Prototype.K;
  615. var result;
  616. this.each(function(value, index) {
  617. value = iterator.call(context, value, index);
  618. if (result == null || value >= result)
  619. result = value;
  620. });
  621. return result;
  622. },
  623. min: function(iterator, context) {
  624. iterator = iterator || Prototype.K;
  625. var result;
  626. this.each(function(value, index) {
  627. value = iterator.call(context, value, index);
  628. if (result == null || value < result)
  629. result = value;
  630. });
  631. return result;
  632. },
  633. partition: function(iterator, context) {
  634. iterator = iterator || Prototype.K;
  635. var trues = [], falses = [];
  636. this.each(function(value, index) {
  637. (iterator.call(context, value, index) ?
  638. trues : falses).push(value);
  639. });
  640. return [trues, falses];
  641. },
  642. pluck: function(property) {
  643. var results = [];
  644. this.each(function(value) {
  645. results.push(value[property]);
  646. });
  647. return results;
  648. },
  649. reject: function(iterator, context) {
  650. var results = [];
  651. this.each(function(value, index) {
  652. if (!iterator.call(context, value, index))
  653. results.push(value);
  654. });
  655. return results;
  656. },
  657. sortBy: function(iterator, context) {
  658. return this.map(function(value, index) {
  659. return {
  660. value: value,
  661. criteria: iterator.call(context, value, index)
  662. };
  663. }).sort(function(left, right) {
  664. var a = left.criteria, b = right.criteria;
  665. return a < b ? -1 : a > b ? 1 : 0;
  666. }).pluck('value');
  667. },
  668. toArray: function() {
  669. return this.map();
  670. },
  671. zip: function() {
  672. var iterator = Prototype.K, args = $A(arguments);
  673. if (Object.isFunction(args.last()))
  674. iterator = args.pop();
  675. var collections = [this].concat(args).map($A);
  676. return this.map(function(value, index) {
  677. return iterator(collections.pluck(index));
  678. });
  679. },
  680. size: function() {
  681. return this.toArray().length;
  682. },
  683. inspect: function() {
  684. return '#<Enumerable:' + this.toArray().inspect() + '>';
  685. }
  686. };
  687. Object.extend(Enumerable, {
  688. map: Enumerable.collect,
  689. find: Enumerable.detect,
  690. select: Enumerable.findAll,
  691. filter: Enumerable.findAll,
  692. member: Enumerable.include,
  693. entries: Enumerable.toArray,
  694. every: Enumerable.all,
  695. some: Enumerable.any
  696. });
  697. function $A(iterable) {
  698. if (!iterable) return [];
  699. if (iterable.toArray) return iterable.toArray();
  700. var length = iterable.length || 0, results = new Array(length);
  701. while (length--) results[length] = iterable[length];
  702. return results;
  703. }
  704. if (Prototype.Browser.WebKit) {
  705. $A = function(iterable) {
  706. if (!iterable) return [];
  707. if (!(Object.isFunction(iterable) && iterable == '[object NodeList]') &&
  708. iterable.toArray) return iterable.toArray();
  709. var length = iterable.length || 0, results = new Array(length);
  710. while (length--) results[length] = iterable[length];
  711. return results;
  712. };
  713. }
  714. Array.from = $A;
  715. Object.extend(Array.prototype, Enumerable);
  716. if (!Array.prototype._reverse) Array.prototype._reverse = Array.prototype.reverse;
  717. Object.extend(Array.prototype, {
  718. _each: function(iterator) {
  719. for (var i = 0, length = this.length; i < length; i++)
  720. iterator(this[i]);
  721. },
  722. clear: function() {
  723. this.length = 0;
  724. return this;
  725. },
  726. first: function() {
  727. return this[0];
  728. },
  729. last: function() {
  730. return this[this.length - 1];
  731. },
  732. compact: function() {
  733. return this.select(function(value) {
  734. return value != null;
  735. });
  736. },
  737. flatten: function() {
  738. return this.inject([], function(array, value) {
  739. return array.concat(Object.isArray(value) ?
  740. value.flatten() : [value]);
  741. });
  742. },
  743. without: function() {
  744. var values = $A(arguments);
  745. return this.select(function(value) {
  746. return !values.include(value);
  747. });
  748. },
  749. reverse: function(inline) {
  750. return (inline !== false ? this : this.toArray())._reverse();
  751. },
  752. reduce: function() {
  753. return this.length > 1 ? this : this[0];
  754. },
  755. uniq: function(sorted) {
  756. return this.inject([], function(array, value, index) {
  757. if (0 == index || (sorted ? array.last() != value : !array.include(value)))
  758. array.push(value);
  759. return array;
  760. });
  761. },
  762. intersect: function(array) {
  763. var length = array.length, i;
  764. return this.uniq().findAll(function(item) {
  765. i = length;
  766. while (i--) if (item === array[i]) return true;
  767. return false;
  768. });
  769. },
  770. clone: function() {
  771. return [].concat(this);
  772. },
  773. size: function() {
  774. return this.length;
  775. },
  776. inspect: function() {
  777. return '[' + this.map(Object.inspect).join(', ') + ']';
  778. },
  779. toJSON: function() {
  780. var results = [];
  781. this.each(function(object) {
  782. var value = Object.toJSON(object);
  783. if (!Object.isUndefined(value)) results.push(value);
  784. });
  785. return '[' + results.join(', ') + ']';
  786. }
  787. });
  788. // use native browser JS 1.6 implementation if available
  789. if (Object.isFunction(Array.prototype.forEach))
  790. Array.prototype._each = Array.prototype.forEach;
  791. if (!Array.prototype.indexOf) Array.prototype.indexOf = function(item, i) {
  792. i || (i = 0);
  793. var length = this.length;
  794. if (i < 0) i = length + i;
  795. for (; i < length; i++)
  796. if (this[i] === item) return i;
  797. return -1;
  798. };
  799. if (!Array.prototype.lastIndexOf) Array.prototype.lastIndexOf = function(item, i) {
  800. i = isNaN(i) ? this.length : (i < 0 ? this.length + i : i) + 1;
  801. var n = this.slice(0, i).reverse().indexOf(item);
  802. return (n < 0) ? n : i - n - 1;
  803. };
  804. Array.prototype.toArray = Array.prototype.clone;
  805. function $w(string) {
  806. if (!Object.isString(string)) return [];
  807. string = string.strip();
  808. return string ? string.split(/\s+/) : [];
  809. }
  810. if (Prototype.Browser.Opera){
  811. Array.prototype.concat = function() {
  812. var array = [];
  813. for (var i = 0, length = this.length; i < length; i++) array.push(this[i]);
  814. for (var i = 0, length = arguments.length; i < length; i++) {
  815. if (Object.isArray(arguments[i])) {
  816. for (var j = 0, arrayLength = arguments[i].length; j < arrayLength; j++)
  817. array.push(arguments[i][j]);
  818. } else {
  819. array.push(arguments[i]);
  820. }
  821. }
  822. return array;
  823. };
  824. }
  825. Object.extend(Number.prototype, {
  826. toColorPart: function() {
  827. return this.toPaddedString(2, 16);
  828. },
  829. succ: function() {
  830. return this + 1;
  831. },
  832. times: function(iterator, context) {
  833. $R(0, this, true).each(iterator, context);
  834. return this;
  835. },
  836. toPaddedString: function(length, radix) {
  837. var string = this.toString(radix || 10);
  838. return '0'.times(length - string.length) + string;
  839. },
  840. toJSON: function() {
  841. return isFinite(this) ? this.toString() : 'null';
  842. }
  843. });
  844. $w('abs round ceil floor').each(function(method){
  845. Number.prototype[method] = Math[method].methodize();
  846. });
  847. function $H(object) {
  848. return new Hash(object);
  849. };
  850. var Hash = Class.create(Enumerable, (function() {
  851. function toQueryPair(key, value) {
  852. if (Object.isUndefined(value)) return key;
  853. return key + '=' + encodeURIComponent(String.interpret(value));
  854. }
  855. return {
  856. initialize: function(object) {
  857. this._object = Object.isHash(object) ? object.toObject() : Object.clone(object);
  858. },
  859. _each: function(iterator) {
  860. for (var key in this._object) {
  861. var value = this._object[key], pair = [key, value];
  862. pair.key = key;
  863. pair.value = value;
  864. iterator(pair);
  865. }
  866. },
  867. set: function(key, value) {
  868. return this._object[key] = value;
  869. },
  870. get: function(key) {
  871. // simulating poorly supported hasOwnProperty
  872. if (this._object[key] !== Object.prototype[key])
  873. return this._object[key];
  874. },
  875. unset: function(key) {
  876. var value = this._object[key];
  877. delete this._object[key];
  878. return value;
  879. },
  880. toObject: function() {
  881. return Object.clone(this._object);
  882. },
  883. keys: function() {
  884. return this.pluck('key');
  885. },
  886. values: function() {
  887. return this.pluck('value');
  888. },
  889. index: function(value) {
  890. var match = this.detect(function(pair) {
  891. return pair.value === value;
  892. });
  893. return match && match.key;
  894. },
  895. merge: function(object) {
  896. return this.clone().update(object);
  897. },
  898. update: function(object) {
  899. return new Hash(object).inject(this, function(result, pair) {
  900. result.set(pair.key, pair.value);
  901. return result;
  902. });
  903. },
  904. toQueryString: function() {
  905. return this.inject([], function(results, pair) {
  906. var key = encodeURIComponent(pair.key), values = pair.value;
  907. if (values && typeof values == 'object') {
  908. if (Object.isArray(values))
  909. return results.concat(values.map(toQueryPair.curry(key)));
  910. } else results.push(toQueryPair(key, values));
  911. return results;
  912. }).join('&');
  913. },
  914. inspect: function() {
  915. return '#<Hash:{' + this.map(function(pair) {
  916. return pair.map(Object.inspect).join(': ');
  917. }).join(', ') + '}>';
  918. },
  919. toJSON: function() {
  920. return Object.toJSON(this.toObject());
  921. },
  922. clone: function() {
  923. return new Hash(this);
  924. }
  925. }
  926. })());
  927. Hash.prototype.toTemplateReplacements = Hash.prototype.toObject;
  928. Hash.from = $H;
  929. var ObjectRange = Class.create(Enumerable, {
  930. initialize: function(start, end, exclusive) {
  931. this.start = start;
  932. this.end = end;
  933. this.exclusive = exclusive;
  934. },
  935. _each: function(iterator) {
  936. var value = this.start;
  937. while (this.include(value)) {
  938. iterator(value);
  939. value = value.succ();
  940. }
  941. },
  942. include: function(value) {
  943. if (value < this.start)
  944. return false;
  945. if (this.exclusive)
  946. return value < this.end;
  947. return value <= this.end;
  948. }
  949. });
  950. var $R = function(start, end, exclusive) {
  951. return new ObjectRange(start, end, exclusive);
  952. };
  953. var Ajax = {
  954. getTransport: function() {
  955. var transport = false;
  956. Ajax.getTransport = Try.these(
  957. function() {
  958. /* fallback on activex xmlhttp to avoid IE7 local file-system read error */
  959. if (Prototype.Browser.IE && window.location.href.indexOf('file://') == 0) throw 'skip';
  960. transport = new XMLHttpRequest();
  961. return function(){ return new XMLHttpRequest()}
  962. },
  963. function() {
  964. transport = new ActiveXObject('Msxml2.XMLHTTP');
  965. return function(){ return new ActiveXObject('Msxml2.XMLHTTP')}
  966. },
  967. function() {
  968. transport = new ActiveXObject('Microsoft.XMLHTTP');
  969. return function(){ return new ActiveXObject('Microsoft.XMLHTTP')}
  970. }
  971. ) || false;
  972. return transport;
  973. },
  974. activeRequestCount: 0
  975. };
  976. Ajax.Responders = {
  977. responders: [],
  978. _each: function(iterator) {
  979. this.responders._each(iterator);
  980. },
  981. register: function(responder) {
  982. if (!this.include(responder))
  983. this.responders.push(responder);
  984. },
  985. unregister: function(responder) {
  986. this.responders = this.responders.without(responder);
  987. },
  988. dispatch: function(callback, request, transport, json) {
  989. this.each(function(responder) {
  990. if (Object.isFunction(responder[callback])) {
  991. try {
  992. responder[callback].apply(responder, [request, transport, json]);
  993. } catch (e) { }
  994. }
  995. });
  996. }
  997. };
  998. Object.extend(Ajax.Responders, Enumerable);
  999. Ajax.Responders.register({
  1000. onCreate: function() { Ajax.activeRequestCount++ },
  1001. onComplete: function() { Ajax.activeRequestCount-- }
  1002. });
  1003. Ajax.Base = Class.create({
  1004. initialize: function(options) {
  1005. this.allowStatusZero = false;
  1006. this.options = {
  1007. method: 'post',
  1008. asynchronous: true,
  1009. contentType: 'application/x-www-form-urlencoded',
  1010. encoding: 'UTF-8',
  1011. parameters: '',
  1012. evalJSON: true,
  1013. evalJS: true
  1014. };
  1015. Object.extend(this.options, options || { });
  1016. this.options.method = this.options.method.toLowerCase();
  1017. if (Object.isString(this.options.parameters))
  1018. this.options.parameters = this.options.parameters.toQueryParams();
  1019. else if (Object.isHash(this.options.parameters))
  1020. this.options.parameters = this.options.parameters.toObject();
  1021. }
  1022. });
  1023. Ajax.Request = Class.create(Ajax.Base, {
  1024. _complete: false,
  1025. _allowStatusZero: false,
  1026. initialize: function($super, url, options) {
  1027. $super(options);
  1028. this.transport = Ajax.getTransport();
  1029. this.request(url);
  1030. },
  1031. request: (function() {
  1032. var absoluteExp = /^[a-z]{3,5}:/, fileExp = /^(file|ftp):/;
  1033. function isRelative(url) {
  1034. return !absoluteExp.test(url);
  1035. }
  1036. function isFileProtocol(url) {
  1037. return fileExp.test(url);
  1038. }
  1039. return function(url) {
  1040. var base;
  1041. if (Prototype.Browser.Opera && opera.version() < 9.5 &&
  1042. isRelative(url) && (base = $(document.documentElement).down('base')))
  1043. url = base.readAttribute('href') + url;
  1044. this.url = url;
  1045. this.method = this.options.method;
  1046. var params = Object.clone(this.options.parameters);
  1047. this._allowStatusZero = isFileProtocol(this.url) ||
  1048. (isRelative(url) && isFileProtocol(window.location.protocol));
  1049. if (!['get', 'post'].include(this.method)) {
  1050. // simulate other verbs over post
  1051. params['_method'] = this.method;
  1052. this.method = 'post';
  1053. }
  1054. this.parameters = params;
  1055. if (params = Object.toQueryString(params)) {
  1056. this.url += (this.url.include('?') ? '&' : '?') + params;
  1057. if (this.method == 'post' &&
  1058. /Konqueror|Safari|KHTML/.test(navigator.userAgent))
  1059. params += '&_=';
  1060. }
  1061. try {
  1062. var response = new Ajax.Response(this);
  1063. if (this.options.onCreate) this.options.onCreate(response);
  1064. Ajax.Responders.dispatch('onCreate', this, response);
  1065. this.transport.open(this.method.toUpperCase(), this.url,
  1066. this.options.asynchronous);
  1067. if (this.options.asynchronous) this.respondToReadyState.bind(this).defer(1);
  1068. this.transport.onreadystatechange = this.onStateChange.bind(this);
  1069. this.setRequestHeaders();
  1070. this.body = this.method == 'post' ? (this.options.postBody || params) : null;
  1071. this.transport.send(this.body);
  1072. /* Force Firefox to handle ready state 4 for synchronous requests */
  1073. if (!this.options.asynchronous && this.transport.overrideMimeType)
  1074. this.onStateChange();
  1075. }
  1076. catch (e) {
  1077. this.dispatchException(e);
  1078. }
  1079. }
  1080. })(),
  1081. onStateChange: function() {
  1082. var readyState = this.transport.readyState;
  1083. if (readyState > 1 && !((readyState == 4) && this._complete))
  1084. this.respondToReadyState(this.transport.readyState);
  1085. },
  1086. setRequestHeaders: function() {
  1087. var headers = {
  1088. 'X-Requested-With': 'XMLHttpRequest',
  1089. 'X-Prototype-Version': Prototype.Version,
  1090. 'Accept': 'text/javascript, text/html, application/xml, text/xml, */*'
  1091. };
  1092. if (this.method == 'post') {
  1093. headers['Content-type'] = this.options.contentType +
  1094. (this.options.encoding ? '; charset=' + this.options.encoding : '');
  1095. /* Force "Connection: close" for older Mozilla browsers to work
  1096. * around a bug where XMLHttpRequest sends an incorrect
  1097. * Content-length header. See Mozilla Bugzilla #246651.
  1098. */
  1099. if (this.transport.overrideMimeType &&
  1100. (navigator.userAgent.match(/Gecko\/(\d{4})/) || [0,2005])[1] < 2005)
  1101. headers['Connection'] = 'close';
  1102. }
  1103. // user-defined headers
  1104. if (typeof this.options.requestHeaders == 'object') {
  1105. var extras = this.options.requestHeaders;
  1106. if (Object.isFunction(extras.push))
  1107. for (var i = 0, length = extras.length; i < length; i += 2)
  1108. headers[extras[i]] = extras[i+1];
  1109. else
  1110. $H(extras).each(function(pair) { headers[pair.key] = pair.value });
  1111. }
  1112. for (var name in headers)
  1113. this.transport.setRequestHeader(name, headers[name]);
  1114. },
  1115. success: function() {
  1116. var status = this.getStatus();
  1117. return (!status && this._allowStatusZero) || (status >= 200 && status < 300);
  1118. },
  1119. getStatus: function() {
  1120. try {
  1121. return this.transport.status || 0;
  1122. } catch (e) { return 0 }
  1123. },
  1124. respondToReadyState: function(readyState) {
  1125. var state = Ajax.Request.Events[readyState], response = new Ajax.Response(this);
  1126. if (state == 'Complete') {
  1127. try {
  1128. this._complete = true;
  1129. (this.options['on' + response.status]
  1130. || this.options['on' + (this.success() ? 'Success' : 'Failure')]
  1131. || Prototype.emptyFunction)(response, response.headerJSON);
  1132. } catch (e) {
  1133. this.dispatchException(e);
  1134. }
  1135. var contentType = response.getHeader('Content-type');
  1136. if (this.options.evalJS == 'force'
  1137. || (this.options.evalJS && this.isSameOrigin() && contentType
  1138. && contentType.match(/^\s*(text|application)\/(x-)?(java|ecma)script(;.*)?\s*$/i)))
  1139. this.evalResponse();
  1140. }
  1141. try {
  1142. (this.options['on' + state] || Prototype.emptyFunction)(response, response.headerJSON);
  1143. Ajax.Responders.dispatch('on' + state, this, response, response.headerJSON);
  1144. } catch (e) {
  1145. this.dispatchException(e);
  1146. }
  1147. if (state == 'Complete') {
  1148. // avoid memory leak in MSIE: clean up
  1149. this.transport.onreadystatechange = Prototype.emptyFunction;
  1150. }
  1151. },
  1152. isSameOrigin: function() {
  1153. var m = this.url.match(/^\s*https?:\/\/[^\/]*/);
  1154. return !m || (m[0] == '#{protocol}//#{domain}#{port}'.interpolate({
  1155. protocol: location.protocol,
  1156. domain: document.domain,
  1157. port: location.port ? ':' + location.port : ''
  1158. }));
  1159. },
  1160. getHeader: function(name) {
  1161. try {
  1162. return this.transport.getResponseHeader(name) || null;
  1163. } catch (e) { return null }
  1164. },
  1165. evalResponse: function() {
  1166. try {
  1167. return eval((this.transport.responseText || '').unfilterJSON());
  1168. } catch (e) {
  1169. this.dispatchException(e);
  1170. }
  1171. },
  1172. dispatchException: function(exception) {
  1173. (this.options.onException || Prototype.emptyFunction)(this, exception);
  1174. Ajax.Responders.dispatch('onException', this, exception);
  1175. }
  1176. });
  1177. Ajax.Request.Events =
  1178. ['Uninitialized', 'Loading', 'Loaded', 'Interactive', 'Complete'];
  1179. Ajax.Response = Class.create({
  1180. initialize: function(request){
  1181. this.request = request;
  1182. var transport = this.transport = request.transport,
  1183. readyState = this.readyState = transport.readyState;
  1184. if ((readyState > 2 && !Prototype.Browser.IE) || readyState == 4) {
  1185. this.status = this.getStatus();
  1186. this.statusText = this.getStatusText();
  1187. this.responseText = String.interpret(transport.responseText);
  1188. this.headerJSON = this._getHeaderJSON();
  1189. }
  1190. if (readyState == 4) {
  1191. var xml = transport.responseXML;
  1192. this.responseXML = Object.isUndefined(xml) ? null : xml;
  1193. this.responseJSON = this._getResponseJSON();
  1194. }
  1195. },
  1196. status: 0,
  1197. statusText: '',
  1198. getStatus: Ajax.Request.prototype.getStatus,
  1199. getStatusText: function() {
  1200. try {
  1201. return this.transport.statusText || '';
  1202. } catch (e) { return '' }
  1203. },
  1204. getHeader: Ajax.Request.prototype.getHeader,
  1205. getAllHeaders: function() {
  1206. try {
  1207. return this.getAllResponseHeaders();
  1208. } catch (e) { return null }
  1209. },
  1210. getResponseHeader: function(name) {
  1211. return this.transport.getResponseHeader(name);
  1212. },
  1213. getAllResponseHeaders: function() {
  1214. return this.transport.getAllResponseHeaders();
  1215. },
  1216. _getHeaderJSON: function() {
  1217. var json = this.getHeader('X-JSON');
  1218. if (!json) return null;
  1219. json = decodeURIComponent(escape(json));
  1220. try {
  1221. return json.evalJSON(this.request.options.sanitizeJSON ||
  1222. !this.request.isSameOrigin());
  1223. } catch (e) {
  1224. this.request.dispatchException(e);
  1225. }
  1226. },
  1227. _getResponseJSON: function() {
  1228. var options = this.request.options;
  1229. if (!options.evalJSON || (options.evalJSON != 'force' &&
  1230. !(this.getHeader('Content-type') || '').include('application/json')) ||
  1231. this.responseText.blank())
  1232. return null;
  1233. try {
  1234. return this.responseText.evalJSON(options.sanitizeJSON ||
  1235. !this.request.isSameOrigin());
  1236. } catch (e) {
  1237. this.request.dispatchException(e);
  1238. }
  1239. }
  1240. });
  1241. Ajax.Updater = Class.create(Ajax.Request, {
  1242. initialize: function($super, container, url, options) {
  1243. this.container = {
  1244. success: (container.success || container),
  1245. failure: (container.failure || (container.success ? null : container))
  1246. };
  1247. options = Object.clone(options);
  1248. var onComplete = options.onComplete;
  1249. options.onComplete = (function(response, json) {
  1250. this.updateContent(response.responseText);
  1251. if (Object.isFunction(onComplete)) onComplete(response, json);
  1252. }).bind(this);
  1253. $super(url, options);
  1254. },
  1255. updateContent: function(responseText) {
  1256. var receiver = this.container[this.success() ? 'success' : 'failure'],
  1257. options = this.options;
  1258. if (!options.evalScripts) responseText = responseText.stripScripts();
  1259. if (receiver = $(receiver)) {
  1260. if (options.insertion) {
  1261. if (Object.isString(options.insertion)) {
  1262. var insertion = { }; insertion[options.insertion] = responseText;
  1263. receiver.insert(insertion);
  1264. }
  1265. else options.insertion(receiver, responseText);
  1266. }
  1267. else receiver.update(responseText);
  1268. }
  1269. }
  1270. });
  1271. Ajax.PeriodicalUpdater = Class.create(Ajax.Base, {
  1272. initialize: function($super, container, url, options) {
  1273. $super(options);
  1274. this.onComplete = this.options.onComplete;
  1275. this.frequency = (this.options.frequency || 2);
  1276. this.decay = (this.options.decay || 1);
  1277. this.updater = { };
  1278. this.container = container;
  1279. this.url = url;
  1280. this.start();
  1281. },
  1282. start: function() {
  1283. this.options.onComplete = this.updateComplete.bind(this);
  1284. this.onTimerEvent();
  1285. },
  1286. stop: function() {
  1287. this.updater.options.onComplete = undefined;
  1288. clearTimeout(this.timer);
  1289. (this.onComplete || Prototype.emptyFunction).apply(this, arguments);
  1290. },
  1291. updateComplete: function(response) {
  1292. if (this.options.decay) {
  1293. this.decay = (response.responseText == this.lastText ?
  1294. this.decay * this.options.decay : 1);
  1295. this.lastText = response.responseText;
  1296. }
  1297. this.timer = this.onTimerEvent.bind(this).delay(this.decay * this.frequency);
  1298. },
  1299. onTimerEvent: function() {
  1300. this.updater = new Ajax.Updater(this.container, this.url, this.options);
  1301. }
  1302. });
  1303. function $(element) {
  1304. if (arguments.length > 1) {
  1305. for (var i = 0, elements = [], length = arguments.length; i < length; i++)
  1306. elements.push($(arguments[i]));
  1307. return elements;
  1308. }
  1309. if (Object.isString(element))
  1310. element = document.getElementById(element);
  1311. return Element.extend(element);
  1312. }
  1313. if (Prototype.BrowserFeatures.XPath) {
  1314. document._getElementsByXPath = function(expression, parentElement) {
  1315. var results = [];
  1316. var query = document.evaluate(expression, $(parentElement) || document,
  1317. null, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);
  1318. for (var i = 0, length = query.snapshotLength; i < length; i++)
  1319. results.push(Element.extend(query.snapshotItem(i)));
  1320. return results;
  1321. };
  1322. }
  1323. /*--------------------------------------------------------------------------*/
  1324. if (!window.Node) var Node = { };
  1325. if (!Node.ELEMENT_NODE) {
  1326. // DOM level 2 ECMAScript Language Binding
  1327. Object.extend(Node, {
  1328. ELEMENT_NODE: 1,
  1329. ATTRIBUTE_NODE: 2,
  1330. TEXT_NODE: 3,
  1331. CDATA_SECTION_NODE: 4,
  1332. ENTITY_REFERENCE_NODE: 5,
  1333. ENTITY_NODE: 6,
  1334. PROCESSING_INSTRUCTION_NODE: 7,
  1335. COMMENT_NODE: 8,
  1336. DOCUMENT_NODE: 9,
  1337. DOCUMENT_TYPE_NODE: 10,
  1338. DOCUMENT_FRAGMENT_NODE: 11,
  1339. NOTATION_NODE: 12
  1340. });
  1341. }
  1342. (function() {
  1343. var element = this.Element;
  1344. this.Element = function(tagName, attributes) {
  1345. attributes = attributes || { };
  1346. tagName = tagName.toLowerCase();
  1347. var cache = Element.cache;
  1348. if (Prototype.Browser.IE && (attributes.name || attributes.type)) {
  1349. tagName = '<' + tagName +
  1350. (attributes.name ? ' name="' + attributes.name + '"' : '') +
  1351. (attributes.type ? ' type="' + attributes.type + '"' : '') + '>';
  1352. delete attributes.name; delete attributes.type;
  1353. return Element.writeAttribute(document.createElement(tagName), attributes);
  1354. }
  1355. if (!cache[tagName]) cache[tagName] = Element.extend(document.createElement(tagName));
  1356. return Element.writeAttribute(cache[tagName].cloneNode(false), attributes);
  1357. };
  1358. Object.extend(this.Element, element || { });
  1359. if (element) this.Element.prototype = element.prototype;
  1360. }).call(window);
  1361. Element.cache = { };
  1362. Element.Methods = {
  1363. visible: function(element) {
  1364. return $(element).style.display != 'none';
  1365. },
  1366. toggle: function(element) {
  1367. element = $(element);
  1368. Element[Element.visible(element) ? 'hide' : 'show'](element);
  1369. return element;
  1370. },
  1371. hide: function(element) {
  1372. element = $(element);
  1373. var originalDisplay = element.style.display;
  1374. if (originalDisplay && originalDisplay != 'none')
  1375. element._originalDisplay = originalDisplay;
  1376. element.style.display = 'none';
  1377. return element;
  1378. },
  1379. show: function(element) {
  1380. element = $(element);
  1381. if (element._originalDisplay) {
  1382. element.style.display = element._originalDisplay;
  1383. element._originalDisplay = null;
  1384. } else element.style.display = '';
  1385. return element;
  1386. },
  1387. remove: function(element) {
  1388. element = $(element);
  1389. element.parentNode.removeChild(element);
  1390. return element;
  1391. },
  1392. update: function(element, content) {
  1393. element = $(element);
  1394. if (content && content.toElement) content = content.toElement();
  1395. if (Object.isElement(content)) return element.update().insert(content);
  1396. content = Object.toHTML(content);
  1397. element.innerHTML = content.stripScripts();
  1398. content.evalScripts.bind(content).defer();
  1399. return element;
  1400. },
  1401. replace: function(element, content) {
  1402. element = $(element);
  1403. if (content && content.toElement) content = content.toElement();
  1404. else if (!Object.isElement(content)) {
  1405. content = Object.toHTML(content);
  1406. var range = element.ownerDocument.createRange();
  1407. range.selectNode(element);
  1408. content.evalScripts.bind(content).defer();
  1409. content = range.createContextualFragment(content.stripScripts());
  1410. }
  1411. element.parentNode.replaceChild(content, element);
  1412. return element;
  1413. },
  1414. insert: function(element, insertions) {
  1415. element = $(element);
  1416. if (Object.isString(insertions) || Object.isNumber(insertions) ||
  1417. Object.isElement(insertions) || (insertions && (insertions.toElement || insertions.toHTML)))
  1418. insertions = {bottom:insertions};
  1419. var content, insert, tagName, childNodes;
  1420. for (var position in insertions) {
  1421. content = insertions[position];
  1422. position = position.toLowerCase();
  1423. insert = Element._insertionTranslations[position];
  1424. if (content && content.toElement) content = content.toElement();
  1425. if (Object.isElement(content)) {
  1426. insert(element, content);
  1427. continue;
  1428. }
  1429. content = Object.toHTML(content);
  1430. tagName = ((position == 'before' || position == 'after')
  1431. ? element.parentNode : element).tagName.toUpperCase();
  1432. childNodes = Element._getContentFromAnonymousElement(tagName, content.stripScripts());
  1433. if (position == 'top' || position == 'after') childNodes.reverse();
  1434. childNodes.each(insert.curry(element));
  1435. content.evalScripts.bind(content).defer();
  1436. }
  1437. return element;
  1438. },
  1439. wrap: function(element, wrapper, attributes) {
  1440. element = $(element);
  1441. if (Object.isElement(wrapper))
  1442. $(wrapper).writeAttribute(attributes || { });
  1443. else if (Object.isString(wrapper)) wrapper = new Element(wrapper, attributes);
  1444. else wrapper = new Element('div', wrapper);
  1445. if (element.parentNode)
  1446. element.parentNode.replaceChild(wrapper, element);
  1447. wrapper.appendChild(element);
  1448. return wrapper;
  1449. },
  1450. inspect: function(element) {
  1451. element = $(element);
  1452. var result = '<' + element.tagName.toLowerCase();
  1453. $H({'id': 'id', 'className': 'class'}).each(function(pair) {
  1454. var property = pair.first(), attribute = pair.last();
  1455. var value = (element[property] || '').toString();
  1456. if (value) result += ' ' + attribute + '=' + value.inspect(true);
  1457. });
  1458. return result + '>';
  1459. },
  1460. recursivelyCollect: function(element, property) {
  1461. element = $(element);
  1462. var elements = [];
  1463. while (element = element[property])
  1464. if (element.nodeType == 1)
  1465. elements.push(Element.extend(element));
  1466. return elements;
  1467. },
  1468. ancestors: function(element) {
  1469. return $(element).recursivelyCollect('parentNode');
  1470. },
  1471. descendants: function(element) {
  1472. return $(element).select("*");
  1473. },
  1474. firstDescendant: function(element) {
  1475. element = $(element).firstChild;
  1476. while (element && element.nodeType != 1) element = element.nextSibling;
  1477. return $(element);
  1478. },
  1479. immediateDescendants: function(element) {
  1480. if (!(element = $(element).firstChild)) return [];
  1481. while (element && element.nodeType != 1) element = element.nextSibling;
  1482. if (element) return [element].concat($(element).nextSiblings());
  1483. return [];
  1484. },
  1485. previousSiblings: function(element) {
  1486. return $(element).recursivelyCollect('previousSibling');
  1487. },
  1488. nextSiblings: function(element) {
  1489. return $(element).recursivelyCollect('nextSibling');
  1490. },
  1491. siblings: function(element) {
  1492. element = $(element);
  1493. return element.previousSiblings().reverse().concat(element.nextSiblings());
  1494. },
  1495. match: function(element, selector) {
  1496. if (Object.isString(selector))
  1497. selector = new Selector(selector);
  1498. return selector.match($(element));
  1499. },
  1500. up: function(element, expression, index) {
  1501. element = $(element);
  1502. if (arguments.length == 1) return $(element.parentNode);
  1503. var ancestors = element.ancestors();
  1504. return Object.isNumber(expression) ? ancestors[expression] :
  1505. Selector.findElement(ancestors, expression, index);
  1506. },
  1507. down: function(element, expression, index) {
  1508. element = $(element);
  1509. if (arguments.length == 1) return element.firstDescendant();
  1510. return Object.isNumber(expression) ? element.descendants()[expression] :
  1511. Element.select(element, expression)[index || 0];
  1512. },
  1513. previous: function(element, expression, index) {
  1514. element = $(element);
  1515. if (arguments.length == 1) return $(Selector.handlers.previousElementSibling(element));
  1516. var previousSiblings = element.previousSiblings();
  1517. return Object.isNumber(expression) ? previousSiblings[expression] :
  1518. Selector.findElement(previousSiblings, expression, index);
  1519. },
  1520. next: function(element, expression, index) {
  1521. element = $(element);
  1522. if (arguments.length == 1) return $(Selector.handlers.nextElementSibling(element));
  1523. var nextSiblings = element.nextSiblings();
  1524. return Object.isNumber(expression) ? nextSiblings[expression] :
  1525. Selector.findElement(nextSiblings, expression, index);
  1526. },
  1527. select: function() {
  1528. var args = $A(arguments), element = $(args.shift());
  1529. return Selector.findChildElements(element, args);
  1530. },
  1531. adjacent: function() {
  1532. var args = $A(arguments), element = $(args.shift());
  1533. return Selector.findChildElements(element.parentNode, args).without(element);
  1534. },
  1535. identify: function(element) {
  1536. element = $(element);
  1537. var id = element.readAttribute('id'), self = arguments.callee;
  1538. if (id) return id;
  1539. do { id = 'anonymous_element_' + self.counter++ } while ($(id));
  1540. element.writeAttribute('id', id);
  1541. return id;
  1542. },
  1543. readAttribute: function(element, name) {
  1544. element = $(element);
  1545. var t = Element._attributeTranslations.read;
  1546. if (t.names[name]) name = t.names[name];
  1547. if (Prototype.Browser.IE) {
  1548. // If we're reading from a form, avoid a conflict between an attribute
  1549. // and a child name.
  1550. if (element.tagName.toUpperCase() == 'FORM' &&
  1551. !/^((child|parent)Node|(next|previous)Sibling)$/.test(name) &&
  1552. element.children[name]){
  1553. element = $(element.cloneNode(false));
  1554. }
  1555. if (t.values[name]) return t.values[name](element, name);
  1556. if (name.include(':')) {
  1557. return (!element.attributes || !element.attributes[name]) ? null :
  1558. element.attributes[name].value;
  1559. }
  1560. } else if (t.values[name]) return t.values[name](element, name);
  1561. return element.getAttribute(name);
  1562. },
  1563. writeAttribute: function(element, name, value) {
  1564. element = $(element);
  1565. var attributes = { }, t = Element._attributeTranslations.write;
  1566. if (typeof name == 'object') attributes = name;
  1567. else attributes[name] = Object.isUndefined(value) ? true : value;
  1568. for (var attr in attributes) {
  1569. name = t.names[attr] || attr;
  1570. value = attributes[attr];
  1571. if (t.values[name]) name = t.values[name](element, value);
  1572. if (value === false || value === null)
  1573. element.removeAttribute(name);
  1574. else if (value === true)
  1575. element.setAttribute(name, name);
  1576. else element.setAttribute(name, value);
  1577. }
  1578. return element;
  1579. },
  1580. getHeight: function(element) {
  1581. return $(element).getDimensions().height;
  1582. },
  1583. getWidth: function(element) {
  1584. return $(element).getDimensions().width;
  1585. },
  1586. classNames: function(element) {
  1587. return new Element.ClassNames(element);
  1588. },
  1589. hasClassName: function(element, className) {
  1590. if (!(element = $(element))) return;
  1591. var elementClassName = element.className;
  1592. return (elementClassName.length > 0 && (elementClassName == className ||
  1593. new RegExp("(^|\\s)" + className + "(\\s|$)").test(elementClassName)));
  1594. },
  1595. addClassName: function(element, className) {
  1596. if (!(element = $(element))) return;
  1597. if (!element.hasClassName(className))
  1598. element.className += (element.className ? ' ' : '') + className;
  1599. return element;
  1600. },
  1601. removeClassName: function(element, className) {
  1602. if (!(element = $(element))) return;
  1603. element.className = element.className.replace(
  1604. new RegExp("(^|\\s+)" + className + "(\\s+|$)"), ' ').strip();
  1605. return element;
  1606. },
  1607. toggleClassName: function(element, className) {
  1608. if (!(element = $(element))) return;
  1609. return element[element.hasClassName(className) ?
  1610. 'removeClassName' : 'addClassName'](className);
  1611. },
  1612. // removes whitespace-only text node children
  1613. cleanWhitespace: function(element) {
  1614. element = $(element);
  1615. var node = element.firstChild;
  1616. while (node) {
  1617. var nextNode = node.nextSibling;
  1618. if (node.nodeType == 3 && !/\S/.test(node.nodeValue))
  1619. element.removeChild(node);
  1620. node = nextNode;
  1621. }
  1622. return element;
  1623. },
  1624. empty: function(element) {
  1625. return $(element).innerHTML.blank();
  1626. },
  1627. descendantOf: function(element, ancestor) {
  1628. element = $(element), ancestor = $(ancestor);
  1629. if (element.compareDocumentPosition)
  1630. return (element.compareDocumentPosition(ancestor) & 8) === 8;
  1631. if (ancestor.contains)
  1632. return ancestor.contains(element) && ancestor !== element;
  1633. while (element = element.parentNode)
  1634. if (element == ancestor) return true;
  1635. return false;
  1636. },
  1637. scrollTo: function(element) {
  1638. element = $(element);
  1639. var pos = element.cumulativeOffset();
  1640. window.scrollTo(pos[0], pos[1]);
  1641. return element;
  1642. },
  1643. getStyle: function(element, style) {
  1644. element = $(element);
  1645. style = style == 'float' ? 'cssFloat' : style.camelize();
  1646. var value = element.style[style];
  1647. if (!value || value == 'auto') {
  1648. var css = document.defaultView.getComputedStyle(element, null);
  1649. value = css ? css[style] : null;
  1650. }
  1651. if (style == 'opacity') return value ? parseFloat(value) : 1.0;
  1652. return value == 'auto' ? null : value;
  1653. },
  1654. getOpacity: function(element) {
  1655. return $(element).getStyle('opacity');
  1656. },
  1657. setStyle: function(element, styles) {
  1658. element = $(element);
  1659. var elementStyle = element.style, match;
  1660. if (Object.isString(styles)) {
  1661. element.style.cssText += ';' + styles;
  1662. return styles.include('opacity') ?
  1663. element.setOpacity(styles.match(/opacity:\s*(\d?\.?\d*)/)[1]) : element;
  1664. }
  1665. for (var property in styles)
  1666. if (property == 'opacity') element.setOpacity(styles[property]);
  1667. else
  1668. elementStyle[(property == 'float' || property == 'cssFloat') ?
  1669. (Object.isUndefined(elementStyle.styleFloat) ? 'cssFloat' : 'styleFloat') :
  1670. property] = styles[property];
  1671. return element;
  1672. },
  1673. setOpacity: function(element, value) {
  1674. element = $(element);
  1675. element.style.opacity = (value == 1 || value === '') ? '' :
  1676. (value < 0.00001) ? 0 : value;
  1677. return element;
  1678. },
  1679. getDimensions: function(element) {
  1680. element = $(element);
  1681. var display = element.getStyle('display'),
  1682. dimensions = { width: element.clientWidth, height: element.clientHeight };
  1683. // All *Width and *Height properties give 0 on elements with display: none,
  1684. // so enable the element temporarily
  1685. if (display === "none" || display === null) {
  1686. var els = element.style,
  1687. originalVisibility = els.visibility,
  1688. originalPosition = els.position,
  1689. originalDisplay = els.display;
  1690. els.visibility = 'hidden';
  1691. els.position = 'absolute';
  1692. els.display = 'block';
  1693. dimensions = { width: element.clientWidth, height: element.clientHeight };
  1694. els.display = originalDisplay;
  1695. els.position = originalPosition;
  1696. els.visibility = originalVisibility;
  1697. }
  1698. return dimensions;
  1699. },
  1700. makePositioned: function(element) {
  1701. element = $(element);
  1702. var pos = Element.getStyle(element, 'position');
  1703. if (pos == 'static' || !pos) {
  1704. element._madePositioned = true;
  1705. element.style.position = 'relative';
  1706. // Opera returns the offset relative to the positioning context, when an
  1707. // element is position relative but top and left have not been defined
  1708. if (window.opera) {
  1709. element.style.top = 0;
  1710. element.style.left = 0;
  1711. }
  1712. }
  1713. return element;
  1714. },
  1715. undoPositioned: function(element) {
  1716. element = $(element);
  1717. if (element._madePositioned) {
  1718. element._madePositioned = undefined;
  1719. element.style.position =
  1720. element.style.top =
  1721. element.style.left =
  1722. element.style.bottom =
  1723. element.style.right = '';
  1724. }
  1725. return element;
  1726. },
  1727. makeClipping: function(element) {
  1728. element = $(element);
  1729. if (element._overflow) return element;
  1730. element._overflow = Element.getStyle(element, 'overflow') || 'auto';
  1731. if (element._overflow !== 'hidden')
  1732. element.style.overflow = 'hidden';
  1733. return element;
  1734. },
  1735. undoClipping: function(element) {
  1736. element = $(element);
  1737. if (!element._overflow) return element;
  1738. element.style.overflow = element._overflow == 'auto' ? '' : element._overflow;
  1739. element._overflow = null;
  1740. return element;
  1741. },
  1742. cumulativeOffset: function(element) {
  1743. element = $(element);
  1744. var valueT = 0, valueL = 0;
  1745. do {
  1746. valueT += element.offsetTop || 0;
  1747. valueL += element.offsetLeft || 0;
  1748. element = element.offsetParent;
  1749. } while (element);
  1750. return Element._returnOffset(valueL, valueT);
  1751. },
  1752. positionedOffset: function(element) {
  1753. element = $(element);
  1754. var valueT = 0, valueL = 0;
  1755. do {
  1756. valueT += element.offsetTop || 0;
  1757. valueL += element.offsetLeft || 0;
  1758. element = element.offsetParent;
  1759. if (element) {
  1760. if (element.tagName.toUpperCase() == 'BODY') break;
  1761. var p = Element.getStyle(element, 'position');
  1762. if (p !== 'static') break;
  1763. }
  1764. } while (element);
  1765. return Element._returnOffset(valueL, valueT);
  1766. },
  1767. absolutize: function(element) {
  1768. element = $(element);
  1769. if (element.getStyle('position') == 'absolute') return element;
  1770. // Position.prepare(); // To be done manually by Scripty when it needs it.
  1771. var offsets = element.positionedOffset(),
  1772. dimensions = element.getDimensions(),
  1773. top = offsets[1],
  1774. left = offsets[0],
  1775. width = dimensions.width,
  1776. height = dimensions.height;
  1777. Object.extend(element, {
  1778. _originalLeft: left - parseFloat(element.style.left || 0),
  1779. _originalTop: top - parseFloat(element.style.top || 0),
  1780. _originalWidth: element.style.width,
  1781. _originalHeight: element.style.height
  1782. });
  1783. element.setStyle({
  1784. position: 'absolute',
  1785. top: top + 'px',
  1786. left: left + 'px',
  1787. width: width + 'px',
  1788. height: height + 'px'
  1789. });
  1790. return element;
  1791. },
  1792. relativize: function(element) {
  1793. element = $(element);
  1794. if (element.getStyle('position') == 'relative') return element;
  1795. if (!element._originalTop){
  1796. /* fix bizarre IE position issue with empty elements */
  1797. var isBuggy = element.outerHTML && element.innerHTML.blank();
  1798. if (isBuggy) element.innerHTML = '\x00';
  1799. Object.extend(element, {
  1800. _originalTop: element.offsetTop,
  1801. _originalLeft: element.offsetLeft,
  1802. _originalWidth: Element.getStyle(element, 'width'),
  1803. _originalHeight: Element.getStyle(element, 'height'),
  1804. _originalMarginTop: Element.getStyle(element, 'marginTop'),
  1805. _originalMarginLeft: Element.getStyle(element, 'marginLeft')
  1806. });
  1807. if (isBuggy) element.innerHTML = '';
  1808. }
  1809. Element.setStyle(element, {
  1810. position: 'relative',
  1811. width: element._originalWidth,
  1812. height: element._originalHeight,
  1813. marginTop: element._originalMarginTop,
  1814. marginLeft: element._originalMarginLeft
  1815. });
  1816. var offsets = element.positionedOffset(),
  1817. top = element._originalTop - offsets.top,
  1818. left = element._originalLeft - offsets.left;
  1819. var isAuto = /^(auto|)$/;
  1820. if (!isAuto.test(element.style.top)) top += element._originalTop;
  1821. if (!isAuto.test(element.style.left)) left += element._originalLeft;
  1822. Element.setStyle(element, {
  1823. top: top + 'px',
  1824. left: left + 'px'
  1825. });
  1826. return element;
  1827. },
  1828. getOffsetParent: function(element) {
  1829. element = $(element);
  1830. var op = element.offsetParent, docElement = document.documentElement;
  1831. if (op && op != docElement) return $(op);
  1832. while ((element = element.parentNode) && element !== docElement &&
  1833. element !== document) {
  1834. if (Element.getStyle(element, 'position') != 'static')
  1835. return $(element);
  1836. }
  1837. return $(document.body);
  1838. }
  1839. };
  1840. Object.extend(Element.Methods, (function() {
  1841. function getNumericStyle(element, style) {
  1842. return parseFloat(Element.getStyle(element, style)) || 0;
  1843. }
  1844. function getStyleDiff(element, source, style) {
  1845. return getNumericStyle(source, style) - getNumericStyle(element, style);
  1846. }
  1847. function cloneDimension(element, source, dimension) {
  1848. var d = Element.getDimensions(source), style = { };
  1849. style[dimension] = d[dimension] + 'px';
  1850. var styles = $w('margin padding');
  1851. var sides = (dimension === 'height') ? $w('top bottom') :
  1852. $w('left right');
  1853. var property;
  1854. for (var i = 0; i < 2; i++) {
  1855. for (var j = 0; j < 2; j++) {
  1856. property = styles[i] + sides[j].capitalize();
  1857. style[property] = (getNumericStyle(element, property) +
  1858. getStyleDiff(element, source, property)) + 'px';
  1859. }
  1860. }
  1861. Element.setStyle(element, style);
  1862. }
  1863. return {
  1864. cumulativeScrollOffset: function(element) {
  1865. element = $(element);
  1866. var valueT = 0, valueL = 0, endElement = document;
  1867. var B = Prototype.Browser;
  1868. // Safari and Opera need to stop at document.body or else they'll
  1869. // report inaccurate values.
  1870. if (B.WebKit || B.Opera && opera.version() < 9.5) {
  1871. if ([document, document.body, document.documentElement].include(element))
  1872. return Element._returnOffset(0, 0);
  1873. endElement = document.body;
  1874. }
  1875. if (Element.getStyle(element, 'position') !== 'fixed') {
  1876. while ((element = element.parentNode) && element !== endElement) {
  1877. if (Element.getStyle(element, 'position') === 'fixed') break;
  1878. valueT += element.scrollTop || 0;
  1879. valueL += element.scrollLeft || 0;
  1880. }
  1881. }
  1882. return Element._returnOffset(valueL, valueT);
  1883. },
  1884. cumulativeOffset: function(element) {
  1885. element = $(element);
  1886. var valueT = 0, valueL = 0;
  1887. do {
  1888. valueT += (element.offsetTop || 0);
  1889. valueL += (element.offsetLeft || 0);
  1890. } while ((element = Element.getOffsetParent(element)) != document.body);
  1891. return Element._returnOffset(valueL, valueT);
  1892. },
  1893. positionedOffset: function(element) {
  1894. element = $(element);
  1895. var valueT = 0, valueL = 0;
  1896. do {
  1897. valueT += (element.offsetTop || 0);
  1898. valueL += (element.offsetLeft || 0);
  1899. element = Element.getOffsetParent(element);
  1900. } while (element != document.body &&
  1901. Element.getStyle(element, 'position') == 'static');
  1902. return Element._returnOffset(valueL, valueT);
  1903. },
  1904. viewportOffset: function(forElement) {
  1905. forElement = $(forElement);
  1906. var op, element = forElement, valueT = 0, valueL = 0;
  1907. do {
  1908. valueT += (element.offsetTop || 0);
  1909. valueL += (element.offsetLeft || 0);
  1910. // Safari fix
  1911. op = Element.getOffsetParent(element);
  1912. if (op == document.body && Element.getStyle(element,
  1913. 'position') == 'absolute') break;
  1914. } while ((element = op) != document.body);
  1915. var scrollOffset = Element.cumulativeScrollOffset(forElement);
  1916. valueT -= scrollOffset.top;
  1917. valueL -= scrollOffset.left;
  1918. return Element._returnOffset(valueL, valueT);
  1919. },
  1920. clonePosition: function(element, source) {
  1921. element = $(element);
  1922. source = $(source);
  1923. var options = Object.extend({
  1924. setLeft: true,
  1925. setTop: true,
  1926. setWidth: true,
  1927. setHeight: true,
  1928. offsetTop: 0,
  1929. offsetLeft: 0
  1930. }, arguments[2] || { });
  1931. // find coordinate system to use
  1932. // delta [0,0] will do fine with position: fixed elements;
  1933. // position: absolute needs offsetParent deltas
  1934. var parent, delta = [0, 0];
  1935. if (Element.getStyle(element, 'position') == 'absolute') {
  1936. parent = Element.getOffsetParent(element);
  1937. delta = Element.viewportOffset(parent);
  1938. }
  1939. // correct by body offsets (fixes Safari)
  1940. if (parent == document.body) {
  1941. delta[0] -= document.body.offsetLeft;
  1942. delta[1] -= document.body.offsetTop;
  1943. }
  1944. // set dimensions
  1945. if (options.setWidth) cloneDimension(element, source, 'width');
  1946. if (options.setHeight) cloneDimension(element, source, 'height');
  1947. // find page position of source
  1948. var p = Element.viewportOffset(source),
  1949. borderOffset = ['borderLeftWidth', 'borderTopWidth'].map(
  1950. function(style) { return getStyleDiff(element, source, style); });
  1951. if (options.setLeft) {
  1952. var left = p[0] - delta[0] + borderOffset[0];
  1953. if (options.offsetLeft)
  1954. left += options.offsetLeft + getNumericStyle(element, 'paddingLeft');
  1955. element.style.left = left + 'px';
  1956. }
  1957. if (options.setTop) {
  1958. var top = p[1] - delta[1] + borderOffset[1];
  1959. if (options.offsetTop)
  1960. top += options.offsetTop + getNumericStyle(element, 'paddingTop');
  1961. element.style.top = top + 'px';
  1962. }
  1963. return element;
  1964. }
  1965. };
  1966. })());
  1967. Element.Methods.identify.counter = 1;
  1968. Object.extend(Element.Methods, {
  1969. getElementsBySelector: Element.Methods.select,
  1970. childElements: Element.Methods.immediateDescendants
  1971. });
  1972. Element._attributeTranslations = {
  1973. write: {
  1974. names: {
  1975. className: 'class',
  1976. htmlFor: 'for'
  1977. },
  1978. values: { }
  1979. },
  1980. read: {
  1981. names: { },
  1982. values: {
  1983. _flag: function(element, attribute) {
  1984. return $(element).hasAttribute(attribute) ? attribute : null;
  1985. }
  1986. }
  1987. }
  1988. };
  1989. (function(v) {
  1990. Object.extend(v, {
  1991. disabled: v._flag,
  1992. checked: v._flag,
  1993. readonly: v._flag,
  1994. multiple: v._flag
  1995. });
  1996. })(Element._attributeTranslations.read.values);
  1997. if (Prototype.Browser.Opera) {
  1998. Element.Methods.getStyle = Element.Methods.getStyle.wrap(
  1999. function(proceed, element, style) {
  2000. switch (style) {
  2001. case 'left': case 'top': case 'right': case 'bottom':
  2002. if (proceed(element, 'position') === 'static') return null;
  2003. case 'height': case 'width':
  2004. // returns '0px' for hidden elements; we want it to return null
  2005. if (!Element.visible(element)) return null;
  2006. // returns the border-box dimensions rather than the content-box
  2007. // dimensions, so we subtract padding and borders from the value
  2008. var dim = parseInt(proceed(element, style), 10);
  2009. if (dim !== element['offset' + style.capitalize()])
  2010. return dim + 'px';
  2011. var properties;
  2012. if (style === 'height') {
  2013. properties = ['border-top-width', 'padding-top',
  2014. 'padding-bottom', 'border-bottom-width'];
  2015. }
  2016. else {
  2017. properties = ['border-left-width', 'padding-left',
  2018. 'padding-right', 'border-right-width'];
  2019. }
  2020. return properties.inject(dim, function(memo, property) {
  2021. var val = proceed(element, property);
  2022. return val === null ? memo : memo - parseInt(val, 10);
  2023. }) + 'px';
  2024. default: return proceed(element, style);
  2025. }
  2026. }
  2027. );
  2028. Element.Methods.readAttribute = Element.Methods.readAttribute.wrap(
  2029. function(proceed, element, attribute) {
  2030. if (attribute === 'title') return $(element).title;
  2031. return proceed(element, attribute);
  2032. }
  2033. );
  2034. }
  2035. else if (Prototype.Browser.IE) {
  2036. // IE doesn't report offsets correctly for static elements, so we change them
  2037. // to "relative" to get the values, then change them back.
  2038. Element.Methods.getOffsetParent = Element.Methods.getOffsetParent.wrap(
  2039. function(proceed, element) {
  2040. element = $(element);
  2041. // IE throws an error if element is not in document
  2042. try { element.offsetParent; }
  2043. catch(e) { return $(document.body); }
  2044. var position = element.getStyle('position');
  2045. if (position !== 'static') return proceed(element);
  2046. element.setStyle({ position: 'relative' });
  2047. var value = proceed(element);
  2048. element.setStyle({ position: position });
  2049. return value;
  2050. }
  2051. );
  2052. $w('positionedOffset viewportOffset').each(function(method) {
  2053. Element.Methods[method] = Element.Methods[method].wrap(
  2054. function(proceed, element) {
  2055. element = $(element);
  2056. var position = Element.getStyle(element, 'position');
  2057. if (position !== 'static') return proceed(element);
  2058. // Trigger hasLayout on the offset parent so that IE6 reports
  2059. // accurate offsetTop and offsetLeft values for position: fixed.
  2060. var offsetParent = Element.getOffsetParent(element),
  2061. style = { position: 'relative' };
  2062. if (Element.getOffsetParent(offsetParent, 'position') === 'fixed')
  2063. style.zoom = '1';
  2064. Element.setStyle(element, style);
  2065. var value = proceed(element);
  2066. Element.setStyle(element, { position: position});
  2067. return value;
  2068. }
  2069. );
  2070. });
  2071. Element.Methods.getStyle = function(element, style) {
  2072. element = $(element);
  2073. style = (style == 'float' || style == 'cssFloat') ? 'styleFloat' : style.camelize();
  2074. var value = element.style[style];
  2075. if (!value && element.currentStyle) value = element.currentStyle[style];
  2076. if (style == 'opacity') {
  2077. if (value = (element.getStyle('filter') || '').match(/alpha\(opacity=(.*)\)/))
  2078. if (value[1]) return parseFloat(value[1]) / 100;
  2079. return 1.0;
  2080. }
  2081. if (value == 'auto') {
  2082. if ((style == 'width' || style == 'height') && (element.getStyle('display') != 'none'))
  2083. return element['offset' + style.capitalize()] + 'px';
  2084. return null;
  2085. }
  2086. return value;
  2087. };
  2088. Element.Methods.setOpacity = function(element, value) {
  2089. function stripAlpha(filter){
  2090. return filter.replace(/alpha\([^\)]*\)/gi,'');
  2091. }
  2092. element = $(element);
  2093. var currentStyle = element.currentStyle;
  2094. if ((currentStyle && !currentStyle.hasLayout) ||
  2095. (!currentStyle && element.style.zoom == 'normal'))
  2096. element.style.zoom = 1;
  2097. var filter = element.getStyle('filter'), style = element.style;
  2098. if (value == 1 || value === '') {
  2099. (filter = stripAlpha(filter)) ?
  2100. style.filter = filter : style.removeAttribute('filter');
  2101. return element;
  2102. } else if (value < 0.00001) value = 0;
  2103. style.filter = stripAlpha(filter) +
  2104. 'alpha(opacity=' + (value * 100) + ')';
  2105. return element;
  2106. };
  2107. (function(t) {
  2108. t.has = { };
  2109. t.write.names = { };
  2110. $w('cellPadding cellSpacing colSpan rowSpan vAlign dateTime accessKey ' +
  2111. 'tabIndex encType maxLength readOnly longDesc frameBorder').each(function(attr) {
  2112. var lower = attr.toLowerCase();
  2113. t.has[lower] = attr;
  2114. t.read.names[lower] = attr;
  2115. t.write.names[lower] = attr;
  2116. });
  2117. [t.write.names, t.read.names].each(function(n) {
  2118. Object.extend(n, {
  2119. 'class': 'className',
  2120. 'for': 'htmlFor'
  2121. });
  2122. });
  2123. })(Element._attributeTranslations);
  2124. Object.extend(Element._attributeTranslations.read.values, {
  2125. _getAttr: function(element, attribute) {
  2126. return element.getAttribute(attribute, 2);
  2127. },
  2128. _getAttrNode: function(element, attribute) {
  2129. var node = element.getAttributeNode(attribute);
  2130. return node ? node.value : "";
  2131. },
  2132. _getEv: function(element, attribute) {
  2133. attribute = element.getAttribute(attribute);
  2134. return attribute ? attribute.toString().slice(23, -2) : null;
  2135. },
  2136. style: function(element) {
  2137. return element.style.cssText.toLowerCase();
  2138. },
  2139. title: function(element) {
  2140. return element.title;
  2141. }
  2142. });
  2143. Object.extend(Element._attributeTranslations.write.values, {
  2144. checked: function(element, value) {
  2145. element.checked = !!value;
  2146. },
  2147. encType: function(element, value) {
  2148. element.getAttributeNode('encType').value = value;
  2149. },
  2150. style: function(element, value) {
  2151. element.style.cssText = value ? value : '';
  2152. }
  2153. });
  2154. (function(v) {
  2155. delete v.readonly;
  2156. Object.extend(v, {
  2157. href: v._getAttr,
  2158. src: v._getAttr,
  2159. type: v._getAttr,
  2160. action: v._getAttrNode,
  2161. onload: v._getEv,
  2162. onunload: v._getEv,
  2163. onclick: v._getEv,
  2164. ondblclick: v._getEv,
  2165. onmousedown: v._getEv,
  2166. onmouseup: v._getEv,
  2167. onmouseover: v._getEv,
  2168. onmousemove: v._getEv,
  2169. onmouseout: v._getEv,
  2170. onfocus: v._getEv,
  2171. onblur: v._getEv,
  2172. onkeypress: v._getEv,
  2173. onkeydown: v._getEv,
  2174. onkeyup: v._getEv,
  2175. onsubmit: v._getEv,
  2176. onreset: v._getEv,
  2177. onselect: v._getEv,
  2178. onchange: v._getEv,
  2179. readOnly: v._flag.wrap(function(proceed, element, attribute) {
  2180. attribute = proceed(element, attribute);
  2181. return attribute? 'readonly' : null;
  2182. })
  2183. });
  2184. })(Element._attributeTranslations.read.values);
  2185. }
  2186. else if (Prototype.Browser.Gecko && /rv:1\.8\.0/.test(navigator.userAgent)) {
  2187. Element.Methods.setOpacity = function(element, value) {
  2188. element = $(element);
  2189. element.style.opacity = (value == 1) ? 0.999999 :
  2190. (value === '') ? '' : (value < 0.00001) ? 0 : value;
  2191. return element;
  2192. };
  2193. }
  2194. else if (Prototype.Browser.WebKit) {
  2195. Element.Methods.setOpacity = function(element, value) {
  2196. element = $(element);
  2197. element.style.opacity = (value == 1 || value === '') ? '' :
  2198. (value < 0.00001) ? 0 : value;
  2199. if (value == 1)
  2200. if (element.tagName.toUpperCase() == 'IMG' && element.width) {
  2201. element.width++; element.width--;
  2202. } else try {
  2203. var n = document.createTextNode(' ');
  2204. element.appendChild(n);
  2205. element.removeChild(n);
  2206. } catch (e) { }
  2207. return element;
  2208. };
  2209. // Safari returns margins on body which is incorrect if the child is absolutely
  2210. // positioned. For performance reasons, redefine Element#cumulativeOffset for
  2211. // KHTML/WebKit only.
  2212. Element.Methods.cumulativeOffset = function(element) {
  2213. element = $(element);
  2214. var valueT = 0, valueL = 0;
  2215. do {
  2216. valueT += element.offsetTop || 0;
  2217. valueL += element.offsetLeft || 0;
  2218. if (element.offsetParent == document.body)
  2219. if (Element.getStyle(element, 'position') == 'absolute') break;
  2220. element = element.offsetParent;
  2221. } while (element);
  2222. return Element._returnOffset(valueL, valueT);
  2223. };
  2224. }
  2225. if (Prototype.Browser.IE || Prototype.Browser.Opera) {
  2226. // IE and Opera are missing .innerHTML support for TABLE-related and SELECT elements
  2227. Element.Methods.update = function(element, content) {
  2228. element = $(element);
  2229. if (content && content.toElement) content = content.toElement();
  2230. if (Object.isElement(content)) return element.update().insert(content);
  2231. content = Object.toHTML(content);
  2232. var tagName = element.tagName.toUpperCase();
  2233. if (tagName in Element._insertionTranslations.tags) {
  2234. $A(element.childNodes).each(function(node) { element.removeChild(node) });
  2235. Element._getContentFromAnonymousElement(tagName, content.stripScripts())
  2236. .each(function(node) { element.appendChild(node) });
  2237. }
  2238. else element.innerHTML = content.stripScripts();
  2239. content.evalScripts.bind(content).defer();
  2240. return element;
  2241. };
  2242. }
  2243. if (Prototype.Browser.IE) {
  2244. // Wrap Element#update to clean up event handlers on
  2245. // newly-removed elements. Prevents memory leaks in IE.
  2246. Element.Methods.update = Element.Methods.update.wrap(
  2247. function(proceed, element, contents) {
  2248. Element.select(element, '*').each(Event.stopObserving);
  2249. return proceed(element, contents);
  2250. }
  2251. );
  2252. }
  2253. if ('outerHTML' in document.createElement('div')) {
  2254. Element.Methods.replace = function(element, content) {
  2255. element = $(element);
  2256. if (content && content.toElement) content = content.toElement();
  2257. if (Object.isElement(content)) {
  2258. element.parentNode.replaceChild(content, element);
  2259. return element;
  2260. }
  2261. content = Object.toHTML(content);
  2262. var parent = element.parentNode, tagName = parent.tagName.toUpperCase();
  2263. // Avoid outerHTML in IE because it incorrectly removes the replaced
  2264. // elements' child nodes.
  2265. if (Element._insertionTranslations.tags[tagName] || Prototype.Browser.IE) {
  2266. var nextSibling = element.next();
  2267. var fragments = Element._getContentFromAnonymousElement(tagName,
  2268. content.stripScripts());
  2269. parent.removeChild(element);
  2270. if (nextSibling)
  2271. fragments.each(function(node) { parent.insertBefore(node, nextSibling) });
  2272. else
  2273. fragments.each(function(node) { parent.appendChild(node) });
  2274. }
  2275. else element.outerHTML = content.stripScripts();
  2276. content.evalScripts.bind(content).defer();
  2277. return element;
  2278. };
  2279. }
  2280. Element._returnOffset = function(l, t) {
  2281. var result = [l, t];
  2282. result.left = l;
  2283. result.top = t;
  2284. return result;
  2285. };
  2286. Element._getContentFromAnonymousElement = function(tagName, html) {
  2287. var div = new Element('div'), t = Element._insertionTranslations.tags[tagName];
  2288. if (t) {
  2289. div.innerHTML = t[0] + html + t[1];
  2290. t[2].times(function() { div = div.firstChild });
  2291. } else div.innerHTML = html;
  2292. return $A(div.childNodes);
  2293. };
  2294. Element._insertionTranslations = {
  2295. before: function(element, node) {
  2296. element.parentNode.insertBefore(node, element);
  2297. },
  2298. top: function(element, node) {
  2299. element.insertBefore(node, element.firstChild);
  2300. },
  2301. bottom: function(element, node) {
  2302. element.appendChild(node);
  2303. },
  2304. after: function(element, node) {
  2305. element.parentNode.insertBefore(node, element.nextSibling);
  2306. },
  2307. tags: {
  2308. TABLE: ['<table>', '</table>', 1],
  2309. TBODY: ['<table><tbody>', '</tbody></table>', 2],
  2310. TR: ['<table><tbody><tr>', '</tr></tbody></table>', 3],
  2311. TD: ['<table><tbody><tr><td>', '</td></tr></tbody></table>', 4],
  2312. SELECT: ['<select>', '</select>', 1]
  2313. }
  2314. };
  2315. (function() {
  2316. Object.extend(this.tags, {
  2317. THEAD: this.tags.TBODY,
  2318. TFOOT: this.tags.TBODY,
  2319. TH: this.tags.TD
  2320. });
  2321. }).call(Element._insertionTranslations);
  2322. Element.Methods.Simulated = {
  2323. // No use of $ in this function in order to keep things fast.
  2324. // Used by the Selector class.
  2325. hasAttribute: function(element, attribute) {
  2326. attribute = Element._attributeTranslations.has[attribute] || attribute;
  2327. var node = element.getAttributeNode(attribute);
  2328. return !!(node && node.specified);
  2329. }
  2330. };
  2331. Element.Methods.ByTag = { };
  2332. Object.extend(Element, Element.Methods);
  2333. if (!Prototype.BrowserFeatures.ElementExtensions &&
  2334. document.createElement('div')['__proto__']) {
  2335. window.HTMLElement = { };
  2336. window.HTMLElement.prototype = document.createElement('div')['__proto__'];
  2337. Prototype.BrowserFeatures.ElementExtensions = true;
  2338. }
  2339. Element.extend = (function() {
  2340. if (Prototype.BrowserFeatures.SpecificElementExtensions)
  2341. return Prototype.K;
  2342. var Methods = { }, ByTag = Element.Methods.ByTag;
  2343. var extend = Object.extend(function(element) {
  2344. if (!element || element._extendedByPrototype ||
  2345. element.nodeType != 1 || element == window) return element;
  2346. // Filter out XML nodes in IE.
  2347. if (!(element.ownerDocument || element).body) return element;
  2348. var methods = Object.clone(Methods),
  2349. tagName = element.tagName.toUpperCase(), property, value;
  2350. // extend methods for specific tags
  2351. if (ByTag[tagName]) Object.extend(methods, ByTag[tagName]);
  2352. for (property in methods) {
  2353. value = methods[property];
  2354. if (Object.isFunction(value) && !(property in element))
  2355. element[property] = value.methodize();
  2356. }
  2357. element._extendedByPrototype = Prototype.emptyFunction;
  2358. return element;
  2359. }, {
  2360. refresh: function() {
  2361. // extend methods for all tags (Safari doesn't need this)
  2362. if (!Prototype.BrowserFeatures.ElementExtensions) {
  2363. Object.extend(Methods, Element.Methods);
  2364. Object.extend(Methods, Element.Methods.Simulated);
  2365. }
  2366. }
  2367. });
  2368. extend.refresh();
  2369. return extend;
  2370. })();
  2371. // No use of $ in this function in order to keep things fast.
  2372. // Used by the Selector class.
  2373. Element.hasAttribute = function(element, attribute) {
  2374. if (element.hasAttribute) return element.hasAttribute(attribute);
  2375. return Element.Methods.Simulated.hasAttribute(element, attribute);
  2376. };
  2377. Element.addMethods = function(methods) {
  2378. var F = Prototype.BrowserFeatures, T = Element.Methods.ByTag;
  2379. if (!methods) {
  2380. Object.extend(Form, Form.Methods);
  2381. Object.extend(Form.Element, Form.Element.Methods);
  2382. Object.extend(Element.Methods.ByTag, {
  2383. "BUTTON": Object.clone(Form.Element.Methods),
  2384. "FORM": Object.clone(Form.Methods),
  2385. "INPUT": Object.clone(Form.Element.Methods),
  2386. "SELECT": Object.clone(Form.Element.Methods),
  2387. "TEXTAREA": Object.clone(Form.Element.Methods)
  2388. });
  2389. }
  2390. if (arguments.length == 2) {
  2391. var tagName = methods;
  2392. methods = arguments[1];
  2393. }
  2394. if (!tagName) Object.extend(Element.Methods, methods || { });
  2395. else {
  2396. if (Object.isArray(tagName)) tagName.each(extend);
  2397. else extend(tagName);
  2398. }
  2399. function extend(tagName) {
  2400. tagName = tagName.toUpperCase();
  2401. if (!Element.Methods.ByTag[tagName])
  2402. Element.Methods.ByTag[tagName] = { };
  2403. Object.extend(Element.Methods.ByTag[tagName], methods);
  2404. }
  2405. function copy(methods, destination, onlyIfAbsent) {
  2406. onlyIfAbsent = onlyIfAbsent || false;
  2407. for (var property in methods) {
  2408. var value = methods[property];
  2409. if (!Object.isFunction(value)) continue;
  2410. if (!onlyIfAbsent || !(property in destination))
  2411. destination[property] = value.methodize();
  2412. }
  2413. }
  2414. function findDOMClass(tagName) {
  2415. var klass;
  2416. var trans = {
  2417. "OPTGROUP": "OptGroup", "TEXTAREA": "TextArea", "P": "Paragraph",
  2418. "FIELDSET": "FieldSet", "UL": "UList", "OL": "OList", "DL": "DList",
  2419. "DIR": "Directory", "H1": "Heading", "H2": "Heading", "H3": "Heading",
  2420. "H4": "Heading", "H5": "Heading", "H6": "Heading", "Q": "Quote",
  2421. "INS": "Mod", "DEL": "Mod", "A": "Anchor", "IMG": "Image", "CAPTION":
  2422. "TableCaption", "COL": "TableCol", "COLGROUP": "TableCol", "THEAD":
  2423. "TableSection", "TFOOT": "TableSection", "TBODY": "TableSection", "TR":
  2424. "TableRow", "TH": "TableCell", "TD": "TableCell", "FRAMESET":
  2425. "FrameSet", "IFRAME": "IFrame"
  2426. };
  2427. if (trans[tagName]) klass = 'HTML' + trans[tagName] + 'Element';
  2428. if (window[klass]) return window[klass];
  2429. klass = 'HTML' + tagName + 'Element';
  2430. if (window[klass]) return window[klass];
  2431. klass = 'HTML' + tagName.capitalize() + 'Element';
  2432. if (window[klass]) return window[klass];
  2433. window[klass] = { };
  2434. window[klass].prototype = document.createElement(tagName)['__proto__'];
  2435. return window[klass];
  2436. }
  2437. if (F.ElementExtensions) {
  2438. copy(Element.Methods, HTMLElement.prototype);
  2439. copy(Element.Methods.Simulated, HTMLElement.prototype, true);
  2440. }
  2441. if (F.SpecificElementExtensions) {
  2442. for (var tag in Element.Methods.ByTag) {
  2443. var klass = findDOMClass(tag);
  2444. if (Object.isUndefined(klass)) continue;
  2445. copy(T[tag], klass.prototype);
  2446. }
  2447. }
  2448. Object.extend(Element, Element.Methods);
  2449. delete Element.ByTag;
  2450. if (Element.extend.refresh) Element.extend.refresh();
  2451. Element.cache = { };
  2452. };
  2453. document.viewport = {
  2454. getDimensions: function() {
  2455. var dimensions = { }, B = Prototype.Browser;
  2456. $w('width height').each(function(d) {
  2457. var D = d.capitalize();
  2458. dimensions[d] = (B.WebKit && !document.evaluate) ? self['inner' + D] :
  2459. (B.Opera && opera.version() < 9.5) ? document.body['client' + D] : document.documentElement['client' + D];
  2460. });
  2461. return dimensions;
  2462. },
  2463. getWidth: function() {
  2464. return this.getDimensions().width;
  2465. },
  2466. getHeight: function() {
  2467. return this.getDimensions().height;
  2468. },
  2469. getScrollOffsets: function() {
  2470. return Element._returnOffset(
  2471. window.pageXOffset || document.documentElement.scrollLeft || document.body.scrollLeft,
  2472. window.pageYOffset || document.documentElement.scrollTop || document.body.scrollTop);
  2473. }
  2474. };
  2475. /* Portions of the Selector class are derived from Jack Slocum's DomQuery,
  2476. * part of YUI-Ext version 0.40, distributed under the terms of an MIT-style
  2477. * license. Please see http://www.yui-ext.com/ for more information. */
  2478. var Selector = Class.create({
  2479. initialize: function(expression) {
  2480. this.expression = expression.strip();
  2481. if (this.shouldUseSelectorsAPI()) {
  2482. this.mode = 'selectorsAPI';
  2483. } else if (this.shouldUseXPath()) {
  2484. this.mode = 'xpath';
  2485. this.compileXPathMatcher();
  2486. } else {
  2487. this.mode = "normal";
  2488. this.compileMatcher();
  2489. }
  2490. },
  2491. shouldUseXPath: function() {
  2492. if (!Prototype.BrowserFeatures.XPath) return false;
  2493. var e = this.expression;
  2494. // Safari 3 chokes on :*-of-type and :empty
  2495. if (Prototype.Browser.WebKit &&
  2496. (e.include("-of-type") || e.include(":empty")))
  2497. return false;
  2498. // XPath can't do namespaced attributes, nor can it read
  2499. // the "checked" property from DOM nodes
  2500. if ((/(\[[\w-]*?:|:checked)/).test(e))
  2501. return false;
  2502. return true;
  2503. },
  2504. shouldUseSelectorsAPI: function() {
  2505. if (!Prototype.BrowserFeatures.SelectorsAPI) return false;
  2506. if (!Selector._div) Selector._div = new Element('div');
  2507. // Make sure the browser treats the selector as valid. Test on an
  2508. // isolated element to minimize cost of this check.
  2509. try {
  2510. Selector._div.querySelector(this.expression);
  2511. } catch(e) {
  2512. return false;
  2513. }
  2514. return true;
  2515. },
  2516. compileMatcher: function() {
  2517. var e = this.expression, ps = Selector.patterns, h = Selector.handlers,
  2518. c = Selector.criteria, le, p, m;
  2519. if (Selector._cache[e]) {
  2520. this.matcher = Selector._cache[e];
  2521. return;
  2522. }
  2523. this.matcher = ["this.matcher = function(root) {",
  2524. "var r = root, h = Selector.handlers, c = false, n;"];
  2525. while (e && le != e && (/\S/).test(e)) {
  2526. le = e;
  2527. for (var i in ps) {
  2528. p = ps[i];
  2529. if (m = e.match(p)) {
  2530. this.matcher.push(Object.isFunction(c[i]) ? c[i](m) :
  2531. new Template(c[i]).evaluate(m));
  2532. e = e.replace(m[0], '');
  2533. break;
  2534. }
  2535. }
  2536. }
  2537. this.matcher.push("return h.unique(n);\n}");
  2538. eval(this.matcher.join('\n'));
  2539. Selector._cache[this.expression] = this.matcher;
  2540. },
  2541. compileXPathMatcher: function() {
  2542. var e = this.expression, ps = Selector.patterns,
  2543. x = Selector.xpath, le, m;
  2544. if (Selector._cache[e]) {
  2545. this.xpath = Selector._cache[e]; return;
  2546. }
  2547. this.matcher = ['.//*'];
  2548. while (e && le != e && (/\S/).test(e)) {
  2549. le = e;
  2550. for (var i in ps) {
  2551. if (m = e.match(ps[i])) {
  2552. this.matcher.push(Object.isFunction(x[i]) ? x[i](m) :
  2553. new Template(x[i]).evaluate(m));
  2554. e = e.replace(m[0], '');
  2555. break;
  2556. }
  2557. }
  2558. }
  2559. this.xpath = this.matcher.join('');
  2560. Selector._cache[this.expression] = this.xpath;
  2561. },
  2562. findElements: function(root) {
  2563. root = root || document;
  2564. var e = this.expression, results;
  2565. switch (this.mode) {
  2566. case 'selectorsAPI':
  2567. // querySelectorAll queries document-wide, then filters to descendants
  2568. // of the context element. That's not what we want.
  2569. // Add an explicit context to the selector if necessary.
  2570. if (root !== document) {
  2571. var oldId = root.id, id = $(root).identify();
  2572. e = "#" + id + " " + e;
  2573. }
  2574. results = $A(root.querySelectorAll(e)).map(Element.extend);
  2575. root.id = oldId;
  2576. return results;
  2577. case 'xpath':
  2578. return document._getElementsByXPath(this.xpath, root);
  2579. default:
  2580. return this.matcher(root);
  2581. }
  2582. },
  2583. match: function(element) {
  2584. this.tokens = [];
  2585. var e = this.expression, ps = Selector.patterns, as = Selector.assertions;
  2586. var le, p, m;
  2587. while (e && le !== e && (/\S/).test(e)) {
  2588. le = e;
  2589. for (var i in ps) {
  2590. p = ps[i];
  2591. if (m = e.match(p)) {
  2592. // use the Selector.assertions methods unless the selector
  2593. // is too complex.
  2594. if (as[i]) {
  2595. this.tokens.push([i, Object.clone(m)]);
  2596. e = e.replace(m[0], '');
  2597. } else {
  2598. // reluctantly do a document-wide search
  2599. // and look for a match in the array
  2600. return this.findElements(document).include(element);
  2601. }
  2602. }
  2603. }
  2604. }
  2605. var match = true, name, matches;
  2606. for (var i = 0, token; token = this.tokens[i]; i++) {
  2607. name = token[0], matches = token[1];
  2608. if (!Selector.assertions[name](element, matches)) {
  2609. match = false; break;
  2610. }
  2611. }
  2612. return match;
  2613. },
  2614. toString: function() {
  2615. return this.expression;
  2616. },
  2617. inspect: function() {
  2618. return "#<Selector:" + this.expression.inspect() + ">";
  2619. }
  2620. });
  2621. Object.extend(Selector, {
  2622. _cache: { },
  2623. xpath: {
  2624. descendant: "//*",
  2625. child: "/*",
  2626. adjacent: "/following-sibling::*[1]",
  2627. laterSibling: '/following-sibling::*',
  2628. tagName: function(m) {
  2629. if (m[1] == '*') return '';
  2630. return "[local-name()='" + m[1].toLowerCase() +
  2631. "' or local-name()='" + m[1].toUpperCase() + "']";
  2632. },
  2633. className: "[contains(concat(' ', @class, ' '), ' #{1} ')]",
  2634. id: "[@id='#{1}']",
  2635. attrPresence: function(m) {
  2636. m[1] = m[1].toLowerCase();
  2637. return new Template("[@#{1}]").evaluate(m);
  2638. },
  2639. attr: function(m) {
  2640. m[1] = m[1].toLowerCase();
  2641. m[3] = m[5] || m[6];
  2642. return new Template(Selector.xpath.operators[m[2]]).evaluate(m);
  2643. },
  2644. pseudo: function(m) {
  2645. var h = Selector.xpath.pseudos[m[1]];
  2646. if (!h) return '';
  2647. if (Object.isFunction(h)) return h(m);
  2648. return new Template(Selector.xpath.pseudos[m[1]]).evaluate(m);
  2649. },
  2650. operators: {
  2651. '=': "[@#{1}='#{3}']",
  2652. '!=': "[@#{1}!='#{3}']",
  2653. '^=': "[starts-with(@#{1}, '#{3}')]",
  2654. '$=': "[substring(@#{1}, (string-length(@#{1}) - string-length('#{3}') + 1))='#{3}']",
  2655. '*=': "[contains(@#{1}, '#{3}')]",
  2656. '~=': "[contains(concat(' ', @#{1}, ' '), ' #{3} ')]",
  2657. '|=': "[contains(concat('-', @#{1}, '-'), '-#{3}-')]"
  2658. },
  2659. pseudos: {
  2660. 'first-child': '[not(preceding-sibling::*)]',
  2661. 'last-child': '[not(following-sibling::*)]',
  2662. 'only-child': '[not(preceding-sibling::* or following-sibling::*)]',
  2663. 'empty': "[count(*) = 0 and (count(text()) = 0)]",
  2664. 'checked': "[@checked]",
  2665. 'disabled': "[(@disabled) and (@type!='hidden')]",
  2666. 'enabled': "[not(@disabled) and (@type!='hidden')]",
  2667. 'not': function(m) {
  2668. var e = m[6], p = Selector.patterns,
  2669. x = Selector.xpath, le, v;
  2670. var exclusion = [];
  2671. while (e && le != e && (/\S/).test(e)) {
  2672. le = e;
  2673. for (var i in p) {
  2674. if (m = e.match(p[i])) {
  2675. v = Object.isFunction(x[i]) ? x[i](m) : new Template(x[i]).evaluate(m);
  2676. exclusion.push("(" + v.substring(1, v.length - 1) + ")");
  2677. e = e.replace(m[0], '');
  2678. break;
  2679. }
  2680. }
  2681. }
  2682. return "[not(" + exclusion.join(" and ") + ")]";
  2683. },
  2684. 'nth-child': function(m) {
  2685. return Selector.xpath.pseudos.nth("(count(./preceding-sibling::*) + 1) ", m);
  2686. },
  2687. 'nth-last-child': function(m) {
  2688. return Selector.xpath.pseudos.nth("(count(./following-sibling::*) + 1) ", m);
  2689. },
  2690. 'nth-of-type': function(m) {
  2691. return Selector.xpath.pseudos.nth("position() ", m);
  2692. },
  2693. 'nth-last-of-type': function(m) {
  2694. return Selector.xpath.pseudos.nth("(last() + 1 - position()) ", m);
  2695. },
  2696. 'first-of-type': function(m) {
  2697. m[6] = "1"; return Selector.xpath.pseudos['nth-of-type'](m);
  2698. },
  2699. 'last-of-type': function(m) {
  2700. m[6] = "1"; return Selector.xpath.pseudos['nth-last-of-type'](m);
  2701. },
  2702. 'only-of-type': function(m) {
  2703. var p = Selector.xpath.pseudos; return p['first-of-type'](m) + p['last-of-type'](m);
  2704. },
  2705. nth: function(fragment, m) {
  2706. var mm, formula = m[6], predicate;
  2707. if (formula == 'even') formula = '2n+0';
  2708. if (formula == 'odd') formula = '2n+1';
  2709. if (mm = formula.match(/^(\d+)$/)) // digit only
  2710. return '[' + fragment + "= " + mm[1] + ']';
  2711. if (mm = formula.match(/^(-?\d*)?n(([+-])(\d+))?/)) { // an+b
  2712. if (mm[1] == "-") mm[1] = -1;
  2713. var a = mm[1] ? Number(mm[1]) : 1;
  2714. var b = mm[2] ? Number(mm[2]) : 0;
  2715. predicate = "[((#{fragment} - #{b}) mod #{a} = 0) and " +
  2716. "((#{fragment} - #{b}) div #{a} >= 0)]";
  2717. return new Template(predicate).evaluate({
  2718. fragment: fragment, a: a, b: b });
  2719. }
  2720. }
  2721. }
  2722. },
  2723. criteria: {
  2724. tagName: 'n = h.tagName(n, r, "#{1}", c); c = false;',
  2725. className: 'n = h.className(n, r, "#{1}", c); c = false;',
  2726. id: 'n = h.id(n, r, "#{1}", c); c = false;',
  2727. attrPresence: 'n = h.attrPresence(n, r, "#{1}", c); c = false;',
  2728. attr: function(m) {
  2729. m[3] = (m[5] || m[6]);
  2730. return new Template('n = h.attr(n, r, "#{1}", "#{3}", "#{2}", c); c = false;').evaluate(m);
  2731. },
  2732. pseudo: function(m) {
  2733. if (m[6]) m[6] = m[6].replace(/"/g, '\\"');
  2734. return new Template('n = h.pseudo(n, "#{1}", "#{6}", r, c); c = false;').evaluate(m);
  2735. },
  2736. descendant: 'c = "descendant";',
  2737. child: 'c = "child";',
  2738. adjacent: 'c = "adjacent";',
  2739. laterSibling: 'c = "laterSibling";'
  2740. },
  2741. patterns: {
  2742. // combinators must be listed first
  2743. // (and descendant needs to be last combinator)
  2744. laterSibling: /^\s*~\s*/,
  2745. child: /^\s*>\s*/,
  2746. adjacent: /^\s*\+\s*/,
  2747. descendant: /^\s/,
  2748. // selectors follow
  2749. tagName: /^\s*(\*|[\w\-]+)(\b|$)?/,
  2750. id: /^#([\w\-\*]+)(\b|$)/,
  2751. className: /^\.([\w\-\*]+)(\b|$)/,
  2752. pseudo:
  2753. /^:((first|last|nth|nth-last|only)(-child|-of-type)|empty|checked|(en|dis)abled|not)(\((.*?)\))?(\b|$|(?=\s|[:+~>]))/,
  2754. attrPresence: /^\[((?:[\w]+:)?[\w]+)\]/,
  2755. attr: /\[((?:[\w-]*:)?[\w-]+)\s*(?:([!^$*~|]?=)\s*((['"])([^\4]*?)\4|([^'"][^\]]*?)))?\]/
  2756. },
  2757. // for Selector.match and Element#match
  2758. assertions: {
  2759. tagName: function(element, matches) {
  2760. return matches[1].toUpperCase() == element.tagName.toUpperCase();
  2761. },
  2762. className: function(element, matches) {
  2763. return Element.hasClassName(element, matches[1]);
  2764. },
  2765. id: function(element, matches) {
  2766. return element.id === matches[1];
  2767. },
  2768. attrPresence: function(element, matches) {
  2769. return Element.hasAttribute(element, matches[1]);
  2770. },
  2771. attr: function(element, matches) {
  2772. var nodeValue = Element.readAttribute(element, matches[1]);
  2773. return nodeValue && Selector.operators[matches[2]](nodeValue, matches[5] || matches[6]);
  2774. }
  2775. },
  2776. handlers: {
  2777. // UTILITY FUNCTIONS
  2778. // joins two collections
  2779. concat: function(a, b) {
  2780. for (var i = 0, node; node = b[i]; i++)
  2781. a.push(node);
  2782. return a;
  2783. },
  2784. // marks an array of nodes for counting
  2785. mark: function(nodes) {
  2786. var _true = Prototype.emptyFunction;
  2787. for (var i = 0, node; node = nodes[i]; i++)
  2788. node._countedByPrototype = _true;
  2789. return nodes;
  2790. },
  2791. unmark: function(nodes) {
  2792. for (var i = 0, node; node = nodes[i]; i++)
  2793. node._countedByPrototype = undefined;
  2794. return nodes;
  2795. },
  2796. // mark each child node with its position (for nth calls)
  2797. // "ofType" flag indicates whether we're indexing for nth-of-type
  2798. // rather than nth-child
  2799. index: function(parentNode, reverse, ofType) {
  2800. parentNode._countedByPrototype = Prototype.emptyFunction;
  2801. if (reverse) {
  2802. for (var nodes = parentNode.childNodes, i = nodes.length - 1, j = 1; i >= 0; i--) {
  2803. var node = nodes[i];
  2804. if (node.nodeType == 1 && (!ofType || node._countedByPrototype)) node.nodeIndex = j++;
  2805. }
  2806. } else {
  2807. for (var i = 0, j = 1, nodes = parentNode.childNodes; node = nodes[i]; i++)
  2808. if (node.nodeType == 1 && (!ofType || node._countedByPrototype)) node.nodeIndex = j++;
  2809. }
  2810. },
  2811. // filters out duplicates and extends all nodes
  2812. unique: function(nodes) {
  2813. if (nodes.length == 0) return nodes;
  2814. var results = [], n;
  2815. for (var i = 0, l = nodes.length; i < l; i++)
  2816. if (!(n = nodes[i])._countedByPrototype) {
  2817. n._countedByPrototype = Prototype.emptyFunction;
  2818. results.push(Element.extend(n));
  2819. }
  2820. return Selector.handlers.unmark(results);
  2821. },
  2822. // COMBINATOR FUNCTIONS
  2823. descendant: function(nodes) {
  2824. var h = Selector.handlers;
  2825. for (var i = 0, results = [], node; node = nodes[i]; i++)
  2826. h.concat(results, node.getElementsByTagName('*'));
  2827. return results;
  2828. },
  2829. child: function(nodes) {
  2830. var h = Selector.handlers;
  2831. for (var i = 0, results = [], node; node = nodes[i]; i++) {
  2832. for (var j = 0, child; child = node.childNodes[j]; j++)
  2833. if (child.nodeType == 1 && child.tagName != '!') results.push(child);
  2834. }
  2835. return results;
  2836. },
  2837. adjacent: function(nodes) {
  2838. for (var i = 0, results = [], node; node = nodes[i]; i++) {
  2839. var next = this.nextElementSibling(node);
  2840. if (next) results.push(next);
  2841. }
  2842. return results;
  2843. },
  2844. laterSibling: function(nodes) {
  2845. var h = Selector.handlers;
  2846. for (var i = 0, results = [], node; node = nodes[i]; i++)
  2847. h.concat(results, Element.nextSiblings(node));
  2848. return results;
  2849. },
  2850. nextElementSibling: function(node) {
  2851. while (node = node.nextSibling)
  2852. if (node.nodeType == 1) return node;
  2853. return null;
  2854. },
  2855. previousElementSibling: function(node) {
  2856. while (node = node.previousSibling)
  2857. if (node.nodeType == 1) return node;
  2858. return null;
  2859. },
  2860. // TOKEN FUNCTIONS
  2861. tagName: function(nodes, root, tagName, combinator) {
  2862. var uTagName = tagName.toUpperCase();
  2863. var results = [], h = Selector.handlers;
  2864. if (nodes) {
  2865. if (combinator) {
  2866. // fastlane for ordinary descendant combinators
  2867. if (combinator == "descendant") {
  2868. for (var i = 0, node; node = nodes[i]; i++)
  2869. h.concat(results, node.getElementsByTagName(tagName));
  2870. return results;
  2871. } else nodes = this[combinator](nodes);
  2872. if (tagName == "*") return nodes;
  2873. }
  2874. for (var i = 0, node; node = nodes[i]; i++)
  2875. if (node.tagName.toUpperCase() === uTagName) results.push(node);
  2876. return results;
  2877. } else return root.getElementsByTagName(tagName);
  2878. },
  2879. id: function(nodes, root, id, combinator) {
  2880. var targetNode = $(id), h = Selector.handlers;
  2881. if (!targetNode) {
  2882. // IE doesn't find elements by ID if they're not attached to the
  2883. // document.
  2884. if (Prototype.Browser.IE && (root.sourceIndex < 1 || root === document)) {
  2885. var nodes = root.getElementsByTagName('*');
  2886. for (var i = 0, node; node = nodes[i]; i++) {
  2887. if (node[id] = id) {
  2888. targetNode = node; break;
  2889. }
  2890. } if (!targetNode) return [];
  2891. } else return [];
  2892. }
  2893. if (!nodes && root === document) return [targetNode];
  2894. if (nodes) {
  2895. if (combinator) {
  2896. if (combinator == 'child') {
  2897. for (var i = 0, node; node = nodes[i]; i++)
  2898. if (targetNode.parentNode == node) return [targetNode];
  2899. } else if (combinator == 'descendant') {
  2900. for (var i = 0, node; node = nodes[i]; i++)
  2901. if (Element.descendantOf(targetNode, node)) return [targetNode];
  2902. } else if (combinator == 'adjacent') {
  2903. for (var i = 0, node; node = nodes[i]; i++)
  2904. if (Selector.handlers.previousElementSibling(targetNode) == node)
  2905. return [targetNode];
  2906. } else nodes = h[combinator](nodes);
  2907. }
  2908. for (var i = 0, node; node = nodes[i]; i++)
  2909. if (node == targetNode) return [targetNode];
  2910. return [];
  2911. }
  2912. return (targetNode && Element.descendantOf(targetNode, root)) ? [targetNode] : [];
  2913. },
  2914. className: function(nodes, root, className, combinator) {
  2915. if (nodes && combinator) nodes = this[combinator](nodes);
  2916. return Selector.handlers.byClassName(nodes, root, className);
  2917. },
  2918. byClassName: function(nodes, root, className) {
  2919. if (!nodes) nodes = Selector.handlers.descendant([root]);
  2920. var needle = ' ' + className + ' ';
  2921. for (var i = 0, results = [], node, nodeClassName; node = nodes[i]; i++) {
  2922. nodeClassName = node.className;
  2923. if (nodeClassName.length == 0) continue;
  2924. if (nodeClassName == className || (' ' + nodeClassName + ' ').include(needle))
  2925. results.push(node);
  2926. }
  2927. return results;
  2928. },
  2929. attrPresence: function(nodes, root, attr, combinator) {
  2930. if (!nodes) nodes = root.getElementsByTagName("*");
  2931. if (nodes && combinator) nodes = this[combinator](nodes);
  2932. var results = [];
  2933. for (var i = 0, node; node = nodes[i]; i++)
  2934. if (Element.hasAttribute(node, attr)) results.push(node);
  2935. return results;
  2936. },
  2937. attr: function(nodes, root, attr, value, operator, combinator) {
  2938. if (!nodes) nodes = root.getElementsByTagName("*");
  2939. if (nodes && combinator) nodes = this[combinator](nodes);
  2940. var handler = Selector.operators[operator], results = [];
  2941. for (var i = 0, node; node = nodes[i]; i++) {
  2942. var nodeValue = Element.readAttribute(node, attr);
  2943. if (nodeValue === null) continue;
  2944. if (handler(nodeValue, value)) results.push(node);
  2945. }
  2946. return results;
  2947. },
  2948. pseudo: function(nodes, name, value, root, combinator) {
  2949. if (nodes && combinator) nodes = this[combinator](nodes);
  2950. if (!nodes) nodes = root.getElementsByTagName("*");
  2951. return Selector.pseudos[name](nodes, value, root);
  2952. }
  2953. },
  2954. pseudos: {
  2955. 'first-child': function(nodes, value, root) {
  2956. for (var i = 0, results = [], node; node = nodes[i]; i++) {
  2957. if (Selector.handlers.previousElementSibling(node)) continue;
  2958. results.push(node);
  2959. }
  2960. return results;
  2961. },
  2962. 'last-child': function(nodes, value, root) {
  2963. for (var i = 0, results = [], node; node = nodes[i]; i++) {
  2964. if (Selector.handlers.nextElementSibling(node)) continue;
  2965. results.push(node);
  2966. }
  2967. return results;
  2968. },
  2969. 'only-child': function(nodes, value, root) {
  2970. var h = Selector.handlers;
  2971. for (var i = 0, results = [], node; node = nodes[i]; i++)
  2972. if (!h.previousElementSibling(node) && !h.nextElementSibling(node))
  2973. results.push(node);
  2974. return results;
  2975. },
  2976. 'nth-child': function(nodes, formula, root) {
  2977. return Selector.pseudos.nth(nodes, formula, root);
  2978. },
  2979. 'nth-last-child': function(nodes, formula, root) {
  2980. return Selector.pseudos.nth(nodes, formula, root, true);
  2981. },
  2982. 'nth-of-type': function(nodes, formula, root) {
  2983. return Selector.pseudos.nth(nodes, formula, root, false, true);
  2984. },
  2985. 'nth-last-of-type': function(nodes, formula, root) {
  2986. return Selector.pseudos.nth(nodes, formula, root, true, true);
  2987. },
  2988. 'first-of-type': function(nodes, formula, root) {
  2989. return Selector.pseudos.nth(nodes, "1", root, false, true);
  2990. },
  2991. 'last-of-type': function(nodes, formula, root) {
  2992. return Selector.pseudos.nth(nodes, "1", root, true, true);
  2993. },
  2994. 'only-of-type': function(nodes, formula, root) {
  2995. var p = Selector.pseudos;
  2996. return p['last-of-type'](p['first-of-type'](nodes, formula, root), formula, root);
  2997. },
  2998. // handles the an+b logic
  2999. getIndices: function(a, b, total) {
  3000. if (a == 0) return b > 0 ? [b] : [];
  3001. return $R(1, total).inject([], function(memo, i) {
  3002. if (0 == (i - b) % a && (i - b) / a >= 0) memo.push(i);
  3003. return memo;
  3004. });
  3005. },
  3006. // handles nth(-last)-child, nth(-last)-of-type, and (first|last)-of-type
  3007. nth: function(nodes, formula, root, reverse, ofType) {
  3008. if (nodes.length == 0) return [];
  3009. if (formula == 'even') formula = '2n+0';
  3010. if (formula == 'odd') formula = '2n+1';
  3011. var h = Selector.handlers, results = [], indexed = [], m;
  3012. h.mark(nodes);
  3013. for (var i = 0, node; node = nodes[i]; i++) {
  3014. if (!node.parentNode._countedByPrototype) {
  3015. h.index(node.parentNode, reverse, ofType);
  3016. indexed.push(node.parentNode);
  3017. }
  3018. }
  3019. if (formula.match(/^\d+$/)) { // just a number
  3020. formula = Number(formula);
  3021. for (var i = 0, node; node = nodes[i]; i++)
  3022. if (node.nodeIndex == formula) results.push(node);
  3023. } else if (m = formula.match(/^(-?\d*)?n(([+-])(\d+))?/)) { // an+b
  3024. if (m[1] == "-") m[1] = -1;
  3025. var a = m[1] ? Number(m[1]) : 1;
  3026. var b = m[2] ? Number(m[2]) : 0;
  3027. var indices = Selector.pseudos.getIndices(a, b, nodes.length);
  3028. for (var i = 0, node, l = indices.length; node = nodes[i]; i++) {
  3029. for (var j = 0; j < l; j++)
  3030. if (node.nodeIndex == indices[j]) results.push(node);
  3031. }
  3032. }
  3033. h.unmark(nodes);
  3034. h.unmark(indexed);
  3035. return results;
  3036. },
  3037. 'empty': function(nodes, value, root) {
  3038. for (var i = 0, results = [], node; node = nodes[i]; i++) {
  3039. // IE treats comments as element nodes
  3040. if (node.tagName == '!' || node.firstChild) continue;
  3041. results.push(node);
  3042. }
  3043. return results;
  3044. },
  3045. 'not': function(nodes, selector, root) {
  3046. var h = Selector.handlers, selectorType, m;
  3047. var exclusions = new Selector(selector).findElements(root);
  3048. h.mark(exclusions);
  3049. for (var i = 0, results = [], node; node = nodes[i]; i++)
  3050. if (!node._countedByPrototype) results.push(node);
  3051. h.unmark(exclusions);
  3052. return results;
  3053. },
  3054. 'enabled': function(nodes, value, root) {
  3055. for (var i = 0, results = [], node; node = nodes[i]; i++)
  3056. if (!node.disabled && (!node.type || node.type !== 'hidden'))
  3057. results.push(node);
  3058. return results;
  3059. },
  3060. 'disabled': function(nodes, value, root) {
  3061. for (var i = 0, results = [], node; node = nodes[i]; i++)
  3062. if (node.disabled) results.push(node);
  3063. return results;
  3064. },
  3065. 'checked': function(nodes, value, root) {
  3066. for (var i = 0, results = [], node; node = nodes[i]; i++)
  3067. if (node.checked) results.push(node);
  3068. return results;
  3069. }
  3070. },
  3071. operators: {
  3072. '=': function(nv, v) { return nv == v; },
  3073. '!=': function(nv, v) { return nv != v; },
  3074. '^=': function(nv, v) { return nv == v || nv && nv.startsWith(v); },
  3075. '$=': function(nv, v) { return nv == v || nv && nv.endsWith(v); },
  3076. '*=': function(nv, v) { return nv == v || nv && nv.include(v); },
  3077. '$=': function(nv, v) { return nv.endsWith(v); },
  3078. '*=': function(nv, v) { return nv.include(v); },
  3079. '~=': function(nv, v) { return (' ' + nv + ' ').include(' ' + v + ' '); },
  3080. '|=': function(nv, v) { return ('-' + (nv || "").toUpperCase() +
  3081. '-').include('-' + (v || "").toUpperCase() + '-'); }
  3082. },
  3083. split: function(expression) {
  3084. var expressions = [];
  3085. expression.scan(/(([\w#:.~>+()\s-]+|\*|\[.*?\])+)\s*(,|$)/, function(m) {
  3086. expressions.push(m[1].strip());
  3087. });
  3088. return expressions;
  3089. },
  3090. matchElements: function(elements, expression) {
  3091. var matches = $$(expression), h = Selector.handlers;
  3092. h.mark(matches);
  3093. for (var i = 0, results = [], element; element = elements[i]; i++)
  3094. if (element._countedByPrototype) results.push(element);
  3095. h.unmark(matches);
  3096. return results;
  3097. },
  3098. findElement: function(elements, expression, index) {
  3099. if (Object.isNumber(expression)) {
  3100. index = expression; expression = false;
  3101. }
  3102. return Selector.matchElements(elements, expression || '*')[index || 0];
  3103. },
  3104. findChildElements: function(element, expressions) {
  3105. expressions = Selector.split(expressions.join(','));
  3106. var results = [], h = Selector.handlers;
  3107. for (var i = 0, l = expressions.length, selector; i < l; i++) {
  3108. selector = new Selector(expressions[i].strip());
  3109. h.concat(results, selector.findElements(element));
  3110. }
  3111. return (l > 1) ? h.unique(results) : results;
  3112. }
  3113. });
  3114. if (Prototype.Browser.IE) {
  3115. Object.extend(Selector.handlers, {
  3116. // IE returns comment nodes on getElementsByTagName("*").
  3117. // Filter them out.
  3118. concat: function(a, b) {
  3119. for (var i = 0, node; node = b[i]; i++)
  3120. if (node.tagName !== "!") a.push(node);
  3121. return a;
  3122. },
  3123. // IE improperly serializes _countedByPrototype in (inner|outer)HTML.
  3124. unmark: function(nodes) {
  3125. for (var i = 0, node; node = nodes[i]; i++)
  3126. node.removeAttribute('_countedByPrototype');
  3127. return nodes;
  3128. }
  3129. });
  3130. }
  3131. function $$() {
  3132. return Selector.findChildElements(document, $A(arguments));
  3133. }
  3134. var Form = {
  3135. reset: function(form) {
  3136. $(form).reset();
  3137. return form;
  3138. },
  3139. serializeElements: function(elements, options) {
  3140. if (typeof options !== 'object') options = { hash: !!options };
  3141. else if (Object.isUndefined(options.hash)) options.hash = true;
  3142. var key, value, type, isImageType, isSubmitButton, submitSerialized;
  3143. var submit = options.submit;
  3144. var data = elements.inject({ }, function(result, element) {
  3145. element = $(element);
  3146. key = element.name;
  3147. value = element.getValue();
  3148. type = element.type;
  3149. isImageType = type === 'image';
  3150. isSubmitButton = (type === 'submit' || isImageType);
  3151. // Null values don't get serialized
  3152. if (value === null) return result;
  3153. // Disabled elements don't get serialized
  3154. if (element.disabled) return result;
  3155. // <input type="file|reset" /> doesn't get serialized
  3156. if (type === 'file' || type === 'reset') return result;
  3157. // Non-active submit buttons don't get serialized
  3158. if (isSubmitButton &&
  3159. (submit === false || submitSerialized ||
  3160. (submit && !(key === submit || element === submit))))
  3161. return result;
  3162. if (isSubmitButton) {
  3163. submitSerialized = true;
  3164. if (isImageType) {
  3165. var prefix = key ? key + '.' : '',
  3166. x = options.x || 0, y = options.y || 0;
  3167. result[prefix + 'x'] = x;
  3168. result[prefix + 'y'] = y;
  3169. return result;
  3170. }
  3171. }
  3172. else if (!key) return result;
  3173. if (key in result) {
  3174. // a key is already present; construct an array of values
  3175. if (!Object.isArray(result[key])) result[key] = [result[key]];
  3176. result[key].push(value);
  3177. } else result[key] = value;
  3178. return result;
  3179. });
  3180. return options.hash ? data : Object.toQueryString(data);
  3181. }
  3182. };
  3183. Form.Methods = {
  3184. serialize: function(form, options) {
  3185. return Form.serializeElements(Form.getElements(form), options);
  3186. },
  3187. getElements: function(form) {
  3188. return $A($(form).getElementsByTagName('*')).inject([],
  3189. function(elements, child) {
  3190. if (Form.Element.Serializers[child.tagName.toLowerCase()])
  3191. elements.push(Element.extend(child));
  3192. return elements;
  3193. }
  3194. );
  3195. },
  3196. getInputs: function(form, typeName, name) {
  3197. form = $(form);
  3198. var inputs = form.getElementsByTagName('input');
  3199. if (!typeName && !name) return $A(inputs).map(Element.extend);
  3200. for (var i = 0, matchingInputs = [], length = inputs.length; i < length; i++) {
  3201. var input = inputs[i];
  3202. if ((typeName && input.type != typeName) || (name && input.name != name))
  3203. continue;
  3204. matchingInputs.push(Element.extend(input));
  3205. }
  3206. return matchingInputs;
  3207. },
  3208. disable: function(form) {
  3209. form = $(form);
  3210. Form.getElements(form).invoke('disable');
  3211. return form;
  3212. },
  3213. enable: function(form) {
  3214. form = $(form);
  3215. Form.getElements(form).invoke('enable');
  3216. return form;
  3217. },
  3218. findFirstElement: function(form) {
  3219. var elements = $(form).getElements().findAll(function(element) {
  3220. return 'hidden' != element.type && !element.disabled;
  3221. });
  3222. var firstByIndex = elements.findAll(function(element) {
  3223. return element.hasAttribute('tabIndex') && element.tabIndex >= 0;
  3224. }).sortBy(function(element) { return element.tabIndex }).first();
  3225. return firstByIndex ? firstByIndex : elements.find(function(element) {
  3226. return ['button', 'input', 'select', 'textarea'].include(element.tagName.toLowerCase());
  3227. });
  3228. },
  3229. focusFirstElement: function(form) {
  3230. form = $(form);
  3231. form.findFirstElement().activate();
  3232. return form;
  3233. },
  3234. request: function(form, options) {
  3235. form = $(form), options = Object.clone(options || { });
  3236. var params = options.parameters, action = form.readAttribute('action') || '';
  3237. if (action.blank()) action = window.location.href;
  3238. options.parameters = form.serialize(true);
  3239. if (params) {
  3240. if (Object.isString(params)) params = params.toQueryParams();
  3241. Object.extend(options.parameters, params);
  3242. }
  3243. if (form.hasAttribute('method') && !options.method)
  3244. options.method = form.method;
  3245. return new Ajax.Request(action, options);
  3246. }
  3247. };
  3248. /*--------------------------------------------------------------------------*/
  3249. Form.Element = {
  3250. focus: function(element) {
  3251. $(element).focus();
  3252. return element;
  3253. },
  3254. select: function(element) {
  3255. $(element).select();
  3256. return element;
  3257. }
  3258. };
  3259. Form.Element.Methods = {
  3260. serialize: function(element) {
  3261. element = $(element);
  3262. if (!element.disabled && element.name) {
  3263. var value = element.getValue();
  3264. if (value != undefined) {
  3265. var pair = { };
  3266. pair[element.name] = value;
  3267. return Object.toQueryString(pair);
  3268. }
  3269. }
  3270. return '';
  3271. },
  3272. getValue: function(element) {
  3273. if (!(element = $(element))) return null;
  3274. var method = element.tagName.toLowerCase(), s = Form.Element.Serializers;
  3275. return s[method]? s[method](element) : null;
  3276. },
  3277. setValue: function(element, value) {
  3278. if (!(element = $(element))) return null;
  3279. var method = element.tagName.toLowerCase(), s = Form.Element.Serializers;
  3280. if (s[method]) s[method](element, value);
  3281. return element;
  3282. },
  3283. clear: function(element) {
  3284. $(element).value = '';
  3285. return element;
  3286. },
  3287. present: function(element) {
  3288. return $(element).value != '';
  3289. },
  3290. activate: function(element) {
  3291. element = $(element);
  3292. try {
  3293. element.focus();
  3294. if (element.select && (element.tagName.toLowerCase() != 'input' ||
  3295. !['button', 'image', 'reset', 'submit'].include(element.type)))
  3296. element.select();
  3297. } catch (e) { }
  3298. return element;
  3299. },
  3300. disable: function(element) {
  3301. element = $(element);
  3302. element.disabled = true;
  3303. return element;
  3304. },
  3305. enable: function(element) {
  3306. element = $(element);
  3307. element.disabled = false;
  3308. return element;
  3309. }
  3310. };
  3311. /*--------------------------------------------------------------------------*/
  3312. var Field = Form.Element;
  3313. var $F = Form.Element.Methods.getValue;
  3314. /*--------------------------------------------------------------------------*/
  3315. Form.Element.Serializers = {
  3316. input: function(element, value) {
  3317. switch (element.type.toLowerCase()) {
  3318. case 'checkbox':
  3319. case 'radio':
  3320. return Form.Element.Serializers.inputSelector(element, value);
  3321. default:
  3322. return Form.Element.Serializers.textarea(element, value);
  3323. }
  3324. },
  3325. inputSelector: function(element, value) {
  3326. if (Object.isUndefined(value)) return element.checked ? element.value : null;
  3327. else element.checked = !!value;
  3328. },
  3329. button: function(element, value){
  3330. if (Object.isUndefined(value)) return element.innerHTML;
  3331. else element.innerHTML = value;
  3332. },
  3333. textarea: function(element, value) {
  3334. if (Object.isUndefined(value)) return element.value;
  3335. else element.value = value;
  3336. },
  3337. select: function(element, index) {
  3338. if (Object.isUndefined(index))
  3339. return this[element.type == 'select-one' ?
  3340. 'selectOne' : 'selectMany'](element);
  3341. else {
  3342. var opt, value, single = !Object.isArray(index);
  3343. for (var i = 0, length = element.length; i < length; i++) {
  3344. opt = element.options[i];
  3345. value = this.optionValue(opt);
  3346. if (single) {
  3347. if (value == index) {
  3348. opt.selected = true;
  3349. return;
  3350. }
  3351. }
  3352. else opt.selected = index.include(value);
  3353. }
  3354. }
  3355. },
  3356. selectOne: function(element) {
  3357. var index = element.selectedIndex;
  3358. return index >= 0 ? this.optionValue(element.options[index]) : null;
  3359. },
  3360. selectMany: function(element) {
  3361. var values, length = element.length;
  3362. if (!length) return null;
  3363. for (var i = 0, values = []; i < length; i++) {
  3364. var opt = element.options[i];
  3365. if (opt.selected) values.push(this.optionValue(opt));
  3366. }
  3367. return values;
  3368. },
  3369. optionValue: function(opt) {
  3370. // extend element because hasAttribute may not be native
  3371. return Element.extend(opt).hasAttribute('value') ? opt.value : opt.text;
  3372. }
  3373. };
  3374. /*--------------------------------------------------------------------------*/
  3375. Abstract.TimedObserver = Class.create(PeriodicalExecuter, {
  3376. initialize: function($super, element, frequency, callback) {
  3377. $super(callback, frequency);
  3378. this.element = $(element);
  3379. this.lastValue = this.getValue();
  3380. },
  3381. execute: function() {
  3382. var value = this.getValue();
  3383. if (Object.isString(this.lastValue) && Object.isString(value) ?
  3384. this.lastValue != value : String(this.lastValue) != String(value)) {
  3385. this.callback(this.element, value);
  3386. this.lastValue = value;
  3387. }
  3388. }
  3389. });
  3390. Form.Element.Observer = Class.create(Abstract.TimedObserver, {
  3391. getValue: function() {
  3392. return Form.Element.getValue(this.element);
  3393. }
  3394. });
  3395. Form.Observer = Class.create(Abstract.TimedObserver, {
  3396. getValue: function() {
  3397. return Form.serialize(this.element);
  3398. }
  3399. });
  3400. /*--------------------------------------------------------------------------*/
  3401. Abstract.EventObserver = Class.create({
  3402. initialize: function(element, callback) {
  3403. this.element = $(element);
  3404. this.callback = callback;
  3405. this.lastValue = this.getValue();
  3406. if (this.element.tagName.toLowerCase() == 'form')
  3407. this.registerFormCallbacks();
  3408. else
  3409. this.registerCallback(this.element);
  3410. },
  3411. onElementEvent: function() {
  3412. var value = this.getValue();
  3413. if (this.lastValue != value) {
  3414. this.callback(this.element, value);
  3415. this.lastValue = value;
  3416. }
  3417. },
  3418. registerFormCallbacks: function() {
  3419. Form.getElements(this.element).each(this.registerCallback, this);
  3420. },
  3421. registerCallback: function(element) {
  3422. if (element.type) {
  3423. switch (element.type.toLowerCase()) {
  3424. case 'checkbox':
  3425. case 'radio':
  3426. Event.observe(element, 'click', this.onElementEvent.bind(this));
  3427. break;
  3428. default:
  3429. Event.observe(element, 'change', this.onElementEvent.bind(this));
  3430. break;
  3431. }
  3432. }
  3433. }
  3434. });
  3435. Form.Element.EventObserver = Class.create(Abstract.EventObserver, {
  3436. getValue: function() {
  3437. return Form.Element.getValue(this.element);
  3438. }
  3439. });
  3440. Form.EventObserver = Class.create(Abstract.EventObserver, {
  3441. getValue: function() {
  3442. return Form.serialize(this.element);
  3443. }
  3444. });
  3445. if (!window.Event) var Event = { };
  3446. Object.extend(Event, {
  3447. KEY_BACKSPACE: 8,
  3448. KEY_TAB: 9,
  3449. KEY_RETURN: 13,
  3450. KEY_ESC: 27,
  3451. KEY_LEFT: 37,
  3452. KEY_UP: 38,
  3453. KEY_RIGHT: 39,
  3454. KEY_DOWN: 40,
  3455. KEY_DELETE: 46,
  3456. KEY_HOME: 36,
  3457. KEY_END: 35,
  3458. KEY_PAGEUP: 33,
  3459. KEY_PAGEDOWN: 34,
  3460. KEY_INSERT: 45,
  3461. cache: { },
  3462. relatedTarget: function(event) {
  3463. var element;
  3464. switch(event.type) {
  3465. case 'mouseover': element = event.fromElement; break;
  3466. case 'mouseout': element = event.toElement; break;
  3467. default: return null;
  3468. }
  3469. return Element.extend(element);
  3470. }
  3471. });
  3472. Event.Methods = (function() {
  3473. var isButton;
  3474. if (Prototype.Browser.IE) {
  3475. var buttonMap = { 0: 1, 1: 4, 2: 2 };
  3476. isButton = function(event, code) {
  3477. return event.button == buttonMap[code];
  3478. };
  3479. } else if (Prototype.Browser.WebKit) {
  3480. isButton = function(event, code) {
  3481. switch (code) {
  3482. case 0: return event.which == 1 && !event.metaKey;
  3483. case 1: return event.which == 1 && event.metaKey;
  3484. default: return false;
  3485. }
  3486. };
  3487. } else {
  3488. isButton = function(event, code) {
  3489. return event.which ? (event.which === code + 1) : (event.button === code);
  3490. };
  3491. }
  3492. return {
  3493. isLeftClick: function(event) { return isButton(event, 0) },
  3494. isMiddleClick: function(event) { return isButton(event, 1) },
  3495. isRightClick: function(event) { return isButton(event, 2) },
  3496. element: function(event) {
  3497. event = Event.extend(event);
  3498. var node = event.target, currentTarget = event.currentTarget, type = event.type;
  3499. if (currentTarget && currentTarget.tagName) {
  3500. // Firefox screws up the "click" event when moving between radio buttons
  3501. // via arrow keys. It also screws up the "load" and "error" events on images,
  3502. // reporting the document as the target instead of the original image.
  3503. if (['load', 'error'].include(type) ||
  3504. (currentTarget.tagName.toUpperCase() === "INPUT" && currentTarget.type === "radio" && type === "click"))
  3505. node = currentTarget;
  3506. }
  3507. return Element.extend(node && node.nodeType == Node.TEXT_NODE ?
  3508. node.parentNode : node);
  3509. },
  3510. findElement: function(event, expression) {
  3511. var element = Event.element(event);
  3512. if (!expression) return element;
  3513. var elements = [element].concat(element.ancestors());
  3514. return Selector.findElement(elements, expression, 0);
  3515. },
  3516. pointer: function(event) {
  3517. var docElement = document.documentElement,
  3518. body = document.body || { scrollLeft: 0, scrollTop: 0 };
  3519. return {
  3520. x: event.pageX || (event.clientX +
  3521. (docElement.scrollLeft || body.scrollLeft) -
  3522. (docElement.clientLeft || 0)),
  3523. y: event.pageY || (event.clientY +
  3524. (docElement.scrollTop || body.scrollTop) -
  3525. (docElement.clientTop || 0))
  3526. };
  3527. },
  3528. pointerX: function(event) { return Event.pointer(event).x },
  3529. pointerY: function(event) { return Event.pointer(event).y },
  3530. stop: function(event) {
  3531. Event.extend(event);
  3532. event.preventDefault();
  3533. event.stopPropagation();
  3534. event.stopped = true;
  3535. }
  3536. };
  3537. })();
  3538. Event.extend = (function() {
  3539. var methods = Object.keys(Event.Methods).inject({ }, function(m, name) {
  3540. m[name] = Event.Methods[name].methodize();
  3541. return m;
  3542. });
  3543. if (Prototype.Browser.IE) {
  3544. Object.extend(methods, {
  3545. stopPropagation: function() { this.cancelBubble = true },
  3546. preventDefault: function() { this.returnValue = false },
  3547. inspect: function() { return "[object Event]" }
  3548. });
  3549. return function(event) {
  3550. if (!event) return false;
  3551. if (event._extendedByPrototype) return event;
  3552. var pointer = Event.pointer(event);
  3553. Object.extend(event, {
  3554. _extendedByPrototype: Prototype.emptyFunction,
  3555. target: Element.extend(event.srcElement),
  3556. relatedTarget: Event.relatedTarget(event),
  3557. pageX: pointer.x,
  3558. pageY: pointer.y
  3559. });
  3560. return Object.extend(event, methods);
  3561. };
  3562. } else {
  3563. Event.prototype = Event.prototype || document.createEvent("HTMLEvents")['__proto__'];
  3564. Object.extend(Event.prototype, methods);
  3565. return Prototype.K;
  3566. }
  3567. })();
  3568. Object.extend(Event, (function() {
  3569. var cache = Event.cache;
  3570. function getEventID(element) {
  3571. // Event ID is stored as the 0th index in a one-item array so that it
  3572. // won't get copied to a new node when cloneNode is called.
  3573. if (element === window) return 1;
  3574. if (element._prototypeEventID) return element._prototypeEventID[0];
  3575. return element._prototypeEventID = [arguments.callee.id++];
  3576. }
  3577. getEventID.id = 2;
  3578. function getDOMEventName(eventName) {
  3579. if (eventName && eventName.include(':')) return "dataavailable";
  3580. return eventName;
  3581. }
  3582. function getCacheForID(id) {
  3583. return cache[id] = cache[id] || { };
  3584. }
  3585. function addEventDispatcher(element, eventName, dispatchWrapper) {
  3586. var id = getEventID(element), wrappers = getWrappersForEventName(id, eventName);
  3587. if (wrappers.dispatcher) return;
  3588. wrappers.dispatcher = function(event) {
  3589. var w = getWrappersForEventName(id, eventName);
  3590. for(var i = 0, l = w.length; i < l; i++) w[i](event); // execute wrappers
  3591. };
  3592. if (dispatchWrapper) wrappers.dispatcher = wrappers.dispatcher.wrap(dispatchWrapper);
  3593. element.attachEvent("on" + getDOMEventName(eventName), wrappers.dispatcher);
  3594. }
  3595. function getWrappersForEventName(id, eventName) {
  3596. var c = getCacheForID(id);
  3597. return c[eventName] = c[eventName] || [];
  3598. }
  3599. function createWrapper(element, eventName, handler) {
  3600. var id = getEventID(element), c = getCacheForID(id);
  3601. // Attach the element itself onto its cache entry so we can retrieve it for
  3602. // cleanup on page unload.
  3603. if (!c.element) c.element = element;
  3604. var w = getWrappersForEventName(id, eventName);
  3605. if (w.pluck("handler").include(handler)) return false;
  3606. var wrapper = function(event) {
  3607. if (!Event || !Event.extend ||
  3608. (event.eventName && event.eventName != eventName))
  3609. return false;
  3610. handler.call(element, Event.extend(event));
  3611. };
  3612. wrapper.handler = handler;
  3613. w.push(wrapper);
  3614. return wrapper;
  3615. }
  3616. function findWrapper(id, eventName, handler) {
  3617. var w = getWrappersForEventName(id, eventName);
  3618. return w.find(function(wrapper) { return wrapper.handler == handler });
  3619. }
  3620. function destroyWrapper(id, eventName, handler) {
  3621. var c = getCacheForID(id);
  3622. if (!c[eventName]) return false;
  3623. var d = c[eventName].dispatcher;
  3624. c[eventName] = c[eventName].without(findWrapper(id, eventName, handler));
  3625. c[eventName].dispatcher = d;
  3626. }
  3627. // Loop through all elements and remove all handlers on page unload. IE
  3628. // needs this in order to prevent memory leaks.
  3629. function purgeListeners() {
  3630. var element, entry;
  3631. for (var i in Event.cache) {
  3632. entry = Event.cache[i];
  3633. Event.stopObserving(entry.element);
  3634. entry.element = null;
  3635. }
  3636. }
  3637. function onStop() {
  3638. document.detachEvent("onstop", onStop);
  3639. purgeListeners();
  3640. }
  3641. function onBeforeUnload() {
  3642. if (document.readyState === "interactive") {
  3643. document.attachEvent("onstop", onStop);
  3644. (function() { document.detachEvent("onstop", onStop); }).defer();
  3645. }
  3646. }
  3647. if (window.attachEvent && !window.addEventListener) {
  3648. // Internet Explorer needs to remove event handlers on page unload
  3649. // in order to avoid memory leaks.
  3650. window.attachEvent("onunload", purgeListeners);
  3651. // IE also doesn't fire the unload event if the page is navigated away
  3652. // from before it's done loading. Workaround adapted from
  3653. // http://blog.moxiecode.com/2008/04/08/unload-event-never-fires-in-ie/.
  3654. window.attachEvent("onbeforeunload", onBeforeUnload);
  3655. // Ensure window onload is fired after "dom:loaded"
  3656. addEventDispatcher(window, 'load', function(proceed, event) {
  3657. if (document.loaded) {
  3658. proceed(event);
  3659. } else {
  3660. arguments.callee.defer(proceed, event);
  3661. }
  3662. });
  3663. // Ensure window onresize is fired only once per resize
  3664. addEventDispatcher(window, 'resize', function(proceed, event) {
  3665. var callee = arguments.callee, dimensions = document.viewport.getDimensions();
  3666. if (dimensions.width != callee.prevWidth || dimensions.height != callee.prevHeight) {
  3667. callee.prevWidth = dimensions.width;
  3668. callee.prevHeight = dimensions.height;
  3669. proceed(event);
  3670. }
  3671. });
  3672. }
  3673. // Safari has a dummy event handler on page unload so that it won't
  3674. // use its bfcache. Safari <= 3.1 has an issue with restoring the "document"
  3675. // object when page is returned to via the back button using its bfcache.
  3676. else if (Prototype.Browser.WebKit) {
  3677. window.addEventListener("unload", Prototype.emptyFunction, false);
  3678. }
  3679. return {
  3680. observe: function(element, eventName, handler) {
  3681. element = $(element);
  3682. var name = getDOMEventName(eventName);
  3683. var wrapper = createWrapper(element, eventName, handler);
  3684. if (!wrapper) return element;
  3685. if (element.addEventListener) {
  3686. element.addEventListener(name, wrapper, false);
  3687. } else {
  3688. addEventDispatcher(element, eventName);
  3689. }
  3690. return element;
  3691. },
  3692. stopObserving: function(element, eventName, handler) {
  3693. element = $(element);
  3694. eventName = Object.isString(eventName) ? eventName : null;
  3695. var id = getEventID(element), c = cache[id];
  3696. if (!c) {
  3697. return element;
  3698. }
  3699. else if (!handler && eventName) {
  3700. getWrappersForEventName(id, eventName).each(function(wrapper) {
  3701. Event.stopObserving(element, eventName, wrapper.handler);
  3702. });
  3703. return element;
  3704. }
  3705. else if (!eventName) {
  3706. Object.keys(c).without("element").each(function(eventName) {
  3707. Event.stopObserving(element, eventName);
  3708. });
  3709. return element;
  3710. }
  3711. var wrapper = findWrapper(id, eventName, handler);
  3712. if (!wrapper) return element;
  3713. var name = getDOMEventName(eventName);
  3714. if (element.removeEventListener) {
  3715. element.removeEventListener(name, wrapper, false);
  3716. destroyWrapper(id, eventName, handler);
  3717. } else {
  3718. destroyWrapper(id, eventName, handler);
  3719. var wrappers = getWrappersForEventName(id, eventName);
  3720. if (!wrappers.length) {
  3721. element.detachEvent("on" + name, wrappers.dispatcher);
  3722. wrappers.dispatcher = null;
  3723. }
  3724. }
  3725. return element;
  3726. },
  3727. fire: function(element, eventName, memo) {
  3728. element = $(element);
  3729. if (element == document && document.createEvent && !element.dispatchEvent)
  3730. element = document.documentElement;
  3731. var event;
  3732. if (document.createEvent) {
  3733. event = document.createEvent("HTMLEvents");
  3734. event.initEvent("dataavailable", true, true);
  3735. } else {
  3736. event = document.createEventObject();
  3737. event.eventType = "ondataavailable";
  3738. }
  3739. event.eventName = eventName;
  3740. event.memo = memo || { };
  3741. if (document.createEvent) {
  3742. element.dispatchEvent(event);
  3743. } else {
  3744. element.fireEvent(event.eventType, event);
  3745. }
  3746. return Event.extend(event);
  3747. }
  3748. };
  3749. })());
  3750. Object.extend(Event, Event.Methods);
  3751. Element.addMethods({
  3752. fire: Event.fire,
  3753. observe: Event.observe,
  3754. stopObserving: Event.stopObserving
  3755. });
  3756. Object.extend(document, {
  3757. fire: Element.Methods.fire.methodize(),
  3758. observe: Element.Methods.observe.methodize(),
  3759. stopObserving: Element.Methods.stopObserving.methodize(),
  3760. loaded: false
  3761. });
  3762. (function() {
  3763. /* Support for the DOMContentLoaded event is based on work by Dan Webb,
  3764. Matthias Miller, Dean Edwards, John Resig and Diego Perini. */
  3765. var timer;
  3766. function fireContentLoadedEvent() {
  3767. if (document.loaded) return;
  3768. if (timer) window.clearInterval(timer);
  3769. document.loaded = true;
  3770. document.fire("dom:loaded");
  3771. }
  3772. if (document.addEventListener) {
  3773. document.addEventListener("DOMContentLoaded", fireContentLoadedEvent, false);
  3774. } else {
  3775. document.attachEvent("onreadystatechange", function() {
  3776. if (document.readyState == "complete") {
  3777. document.detachEvent("onreadystatechange", arguments.callee);
  3778. fireContentLoadedEvent();
  3779. }
  3780. });
  3781. if (window == top) {
  3782. timer = setInterval(function() {
  3783. try {
  3784. document.documentElement.doScroll("left");
  3785. } catch(e) { return }
  3786. fireContentLoadedEvent();
  3787. }, 10);
  3788. }
  3789. }
  3790. // Safari <3.1 doesn't support DOMContentLoaded
  3791. if (Prototype.Browser.WebKit && (navigator.userAgent.match(/AppleWebKit\/(\d+)/)[1] < 525)) {
  3792. timer = setInterval(function() {
  3793. if (/loaded|complete/.test(document.readyState))
  3794. fireContentLoadedEvent();
  3795. }, 10);
  3796. }
  3797. // Worst case fallback...
  3798. Event.observe(window, "load", fireContentLoadedEvent);
  3799. })();
  3800. /*------------------------------- DEPRECATED -------------------------------*/
  3801. Hash.toQueryString = Object.toQueryString;
  3802. var Toggle = { display: Element.toggle };
  3803. Element.Methods.childOf = Element.Methods.descendantOf;
  3804. var Insertion = {
  3805. Before: function(element, content) {
  3806. return Element.insert(element, {before:content});
  3807. },
  3808. Top: function(element, content) {
  3809. return Element.insert(element, {top:content});
  3810. },
  3811. Bottom: function(element, content) {
  3812. return Element.insert(element, {bottom:content});
  3813. },
  3814. After: function(element, content) {
  3815. return Element.insert(element, {after:content});
  3816. }
  3817. };
  3818. var $continue = new Error('"throw $continue" is deprecated, use "return" instead');
  3819. // This should be moved to script.aculo.us; notice the deprecated methods
  3820. // further below, that map to the newer Element methods.
  3821. var Position = {
  3822. // set to true if needed, warning: firefox performance problems
  3823. // NOT neeeded for page scrolling, only if draggable contained in
  3824. // scrollable elements
  3825. includeScrollOffsets: false,
  3826. // must be called before calling withinIncludingScrolloffset, every time the
  3827. // page is scrolled
  3828. prepare: function() {
  3829. this.deltaX = window.pageXOffset
  3830. || document.documentElement.scrollLeft
  3831. || document.body.scrollLeft
  3832. || 0;
  3833. this.deltaY = window.pageYOffset
  3834. || document.documentElement.scrollTop
  3835. || document.body.scrollTop
  3836. || 0;
  3837. },
  3838. // caches x/y coordinate pair to use with overlap
  3839. within: function(element, x, y) {
  3840. if (this.includeScrollOffsets)
  3841. return this.withinIncludingScrolloffsets(element, x, y);
  3842. var dimensions = Element.getDimensions(element);
  3843. this.xcomp = x;
  3844. this.ycomp = y;
  3845. this.offset = Element.cumulativeOffset(element);
  3846. return (y >= this.offset[1] &&
  3847. y < this.offset[1] + dimensions.height &&
  3848. x >= this.offset[0] &&
  3849. x < this.offset[0] + dimensions.width);
  3850. },
  3851. withinIncludingScrolloffsets: function(element, x, y) {
  3852. var offsetcache = Element.cumulativeScrollOffset(element),
  3853. dimensions = Element.getDimensions(element);
  3854. this.xcomp = x + offsetcache[0] - this.deltaX;
  3855. this.ycomp = y + offsetcache[1] - this.deltaY;
  3856. this.offset = Element.cumulativeOffset(element);
  3857. return (this.ycomp >= this.offset[1] &&
  3858. this.ycomp < this.offset[1] + dimensions.height &&
  3859. this.xcomp >= this.offset[0] &&
  3860. this.xcomp < this.offset[0] + dimensions.width);
  3861. },
  3862. // within must be called directly before
  3863. overlap: function(mode, element) {
  3864. var dimensions = Element.getDimensions(element);
  3865. if (!mode) return 0;
  3866. if (mode == 'vertical')
  3867. return ((this.offset[1] + dimensions.height) - this.ycomp) /
  3868. dimensions.height;
  3869. if (mode == 'horizontal')
  3870. return ((this.offset[0] + dimensions.width) - this.xcomp) /
  3871. dimensions.width;
  3872. },
  3873. // Deprecation layer -- use newer Element methods now (1.5.2).
  3874. cumulativeOffset: Element.Methods.cumulativeOffset,
  3875. positionedOffset: Element.Methods.positionedOffset,
  3876. absolutize: function(element) {
  3877. Position.prepare();
  3878. return Element.absolutize(element);
  3879. },
  3880. relativize: function(element) {
  3881. Position.prepare();
  3882. return Element.relativize(element);
  3883. },
  3884. realOffset: Element.Methods.cumulativeScrollOffset,
  3885. offsetParent: Element.Methods.getOffsetParent,
  3886. page: Element.Methods.viewportOffset,
  3887. clone: function(source, target, options) {
  3888. options = options || { };
  3889. return Element.clonePosition(target, source, options);
  3890. }
  3891. };
  3892. /*--------------------------------------------------------------------------*/
  3893. if (!document.getElementsByClassName) document.getElementsByClassName = function(instanceMethods){
  3894. function iter(name) {
  3895. return name.blank() ? null : "[contains(concat(' ', @class, ' '), ' " + name + " ')]";
  3896. }
  3897. instanceMethods.getElementsByClassName = Prototype.BrowserFeatures.XPath ?
  3898. function(element, className) {
  3899. className = className.toString().strip();
  3900. var cond = /\s/.test(className) ? $w(className).map(iter).join('') : iter(className);
  3901. return cond ? document._getElementsByXPath('.//*' + cond, element) : [];
  3902. } : function(element, className) {
  3903. className = className.toString().strip();
  3904. var elements = [], classNames = (/\s/.test(className) ? $w(className) : null);
  3905. if (!classNames && !className) return elements;
  3906. var nodes = $(element).getElementsByTagName('*');
  3907. className = ' ' + className + ' ';
  3908. for (var i = 0, child, cn; child = nodes[i]; i++) {
  3909. if (child.className && (cn = ' ' + child.className + ' ') && (cn.include(className) ||
  3910. (classNames && classNames.all(function(name) {
  3911. return !name.toString().blank() && cn.include(' ' + name + ' ');
  3912. }))))
  3913. elements.push(Element.extend(child));
  3914. }
  3915. return elements;
  3916. };
  3917. return function(className, parentElement) {
  3918. return $(parentElement || document.body).getElementsByClassName(className);
  3919. };
  3920. }(Element.Methods);
  3921. /*--------------------------------------------------------------------------*/
  3922. Element.ClassNames = Class.create();
  3923. Element.ClassNames.prototype = {
  3924. initialize: function(element) {
  3925. this.element = $(element);
  3926. },
  3927. _each: function(iterator) {
  3928. this.element.className.split(/\s+/).select(function(name) {
  3929. return name.length > 0;
  3930. })._each(iterator);
  3931. },
  3932. set: function(className) {
  3933. this.element.className = className;
  3934. },
  3935. add: function(classNameToAdd) {
  3936. if (this.include(classNameToAdd)) return;
  3937. this.set($A(this).concat(classNameToAdd).join(' '));
  3938. },
  3939. remove: function(classNameToRemove) {
  3940. if (!this.include(classNameToRemove)) return;
  3941. this.set($A(this).without(classNameToRemove).join(' '));
  3942. },
  3943. toString: function() {
  3944. return $A(this).join(' ');
  3945. }
  3946. };
  3947. Object.extend(Element.ClassNames.prototype, Enumerable);
  3948. /*--------------------------------------------------------------------------*/
  3949. Element.addMethods();