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

/Web/wp-includes/js/prototype.js

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