PageRenderTime 77ms CodeModel.GetById 20ms RepoModel.GetById 1ms app.codeStats 0ms

/lib/gemcache/ruby/1.9.1/arch/linux64/json-1.6.6/data/prototype.js

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