PageRenderTime 72ms CodeModel.GetById 13ms RepoModel.GetById 0ms app.codeStats 0ms

/lib/gemcache/ruby/1.9.1/arch/win32/thin-1.3.0-x86-mingw32/spec/rails_app/public/javascripts/prototype.js

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