PageRenderTime 44ms CodeModel.GetById 15ms RepoModel.GetById 0ms app.codeStats 1ms

/vendor/gems/newrelic_rpm-2.9.9/ui/views/newrelic/javascript/prototype-scriptaculous.js

https://github.com/ZenCocoon/Synchronizer_model_crash_with_newrelic_rpm_2-9-9
JavaScript | 7288 lines | 6265 code | 809 blank | 214 comment | 1173 complexity | 47710d0e1ab882915b030c3106785458 MD5 | raw file
Possible License(s): MPL-2.0-no-copyleft-exception
  1. /* Prototype JavaScript framework, version 1.6.0.2
  2. * (c) 2005-2008 Sam Stephenson
  3. *
  4. * Prototype is freely distributable under the terms of an MIT-style license.
  5. * For details, see the Prototype web site: http://www.prototypejs.org/
  6. *
  7. *--------------------------------------------------------------------------*/
  8. var Prototype = {
  9. Version: '1.6.0.2',
  10. Browser: {
  11. IE: !!(window.attachEvent && !window.opera),
  12. Opera: !!window.opera,
  13. WebKit: navigator.userAgent.indexOf('AppleWebKit/') > -1,
  14. Gecko: navigator.userAgent.indexOf('Gecko') > -1 && navigator.userAgent.indexOf('KHTML') == -1,
  15. MobileSafari: !!navigator.userAgent.match(/Apple.*Mobile.*Safari/)
  16. },
  17. BrowserFeatures: {
  18. XPath: !!document.evaluate,
  19. 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() : String(object);
  92. } catch (e) {
  93. if (e instanceof RangeError) return '...';
  94. throw e;
  95. }
  96. },
  97. toJSON: function(object) {
  98. var type = typeof object;
  99. switch (type) {
  100. case 'undefined':
  101. case 'function':
  102. case 'unknown': return;
  103. case 'boolean': return object.toString();
  104. }
  105. if (object === null) return 'null';
  106. if (object.toJSON) return object.toJSON();
  107. if (Object.isElement(object)) return;
  108. var results = [];
  109. for (var property in object) {
  110. var value = Object.toJSON(object[property]);
  111. if (!Object.isUndefined(value))
  112. results.push(property.toJSON() + ': ' + value);
  113. }
  114. return '{' + results.join(', ') + '}';
  115. },
  116. toQueryString: function(object) {
  117. return $H(object).toQueryString();
  118. },
  119. toHTML: function(object) {
  120. return object && object.toHTML ? object.toHTML() : String.interpret(object);
  121. },
  122. keys: function(object) {
  123. var keys = [];
  124. for (var property in object)
  125. keys.push(property);
  126. return keys;
  127. },
  128. values: function(object) {
  129. var values = [];
  130. for (var property in object)
  131. values.push(object[property]);
  132. return values;
  133. },
  134. clone: function(object) {
  135. return Object.extend({ }, object);
  136. },
  137. isElement: function(object) {
  138. return object && object.nodeType == 1;
  139. },
  140. isArray: function(object) {
  141. return object != null && typeof object == "object" &&
  142. 'splice' in object && 'join' in object;
  143. },
  144. isHash: function(object) {
  145. return object instanceof Hash;
  146. },
  147. isFunction: function(object) {
  148. return typeof object == "function";
  149. },
  150. isString: function(object) {
  151. return typeof object == "string";
  152. },
  153. isNumber: function(object) {
  154. return typeof object == "number";
  155. },
  156. isUndefined: function(object) {
  157. return typeof object == "undefined";
  158. }
  159. });
  160. Object.extend(Function.prototype, {
  161. argumentNames: function() {
  162. var names = this.toString().match(/^[\s\(]*function[^(]*\((.*?)\)/)[1].split(",").invoke("strip");
  163. return names.length == 1 && !names[0] ? [] : names;
  164. },
  165. bind: function() {
  166. if (arguments.length < 2 && Object.isUndefined(arguments[0])) return this;
  167. var __method = this, args = $A(arguments), object = args.shift();
  168. return function() {
  169. return __method.apply(object, args.concat($A(arguments)));
  170. }
  171. },
  172. bindAsEventListener: function() {
  173. var __method = this, args = $A(arguments), object = args.shift();
  174. return function(event) {
  175. return __method.apply(object, [event || window.event].concat(args));
  176. }
  177. },
  178. curry: function() {
  179. if (!arguments.length) return this;
  180. var __method = this, args = $A(arguments);
  181. return function() {
  182. return __method.apply(this, args.concat($A(arguments)));
  183. }
  184. },
  185. delay: function() {
  186. var __method = this, args = $A(arguments), timeout = args.shift() * 1000;
  187. return window.setTimeout(function() {
  188. return __method.apply(__method, args);
  189. }, timeout);
  190. },
  191. wrap: function(wrapper) {
  192. var __method = this;
  193. return function() {
  194. return wrapper.apply(this, [__method.bind(this)].concat($A(arguments)));
  195. }
  196. },
  197. methodize: function() {
  198. if (this._methodized) return this._methodized;
  199. var __method = this;
  200. return this._methodized = function() {
  201. return __method.apply(null, [this].concat($A(arguments)));
  202. };
  203. }
  204. });
  205. Function.prototype.defer = Function.prototype.delay.curry(0.01);
  206. Date.prototype.toJSON = function() {
  207. return '"' + this.getUTCFullYear() + '-' +
  208. (this.getUTCMonth() + 1).toPaddedString(2) + '-' +
  209. this.getUTCDate().toPaddedString(2) + 'T' +
  210. this.getUTCHours().toPaddedString(2) + ':' +
  211. this.getUTCMinutes().toPaddedString(2) + ':' +
  212. this.getUTCSeconds().toPaddedString(2) + 'Z"';
  213. };
  214. var Try = {
  215. these: function() {
  216. var returnValue;
  217. for (var i = 0, length = arguments.length; i < length; i++) {
  218. var lambda = arguments[i];
  219. try {
  220. returnValue = lambda();
  221. break;
  222. } catch (e) { }
  223. }
  224. return returnValue;
  225. }
  226. };
  227. RegExp.prototype.match = RegExp.prototype.test;
  228. RegExp.escape = function(str) {
  229. return String(str).replace(/([.*+?^=!:${}()|[\]\/\\])/g, '\\$1');
  230. };
  231. /*--------------------------------------------------------------------------*/
  232. var PeriodicalExecuter = Class.create({
  233. initialize: function(callback, frequency) {
  234. this.callback = callback;
  235. this.frequency = frequency;
  236. this.currentlyExecuting = false;
  237. this.registerCallback();
  238. },
  239. registerCallback: function() {
  240. this.timer = setInterval(this.onTimerEvent.bind(this), this.frequency * 1000);
  241. },
  242. execute: function() {
  243. this.callback(this);
  244. },
  245. stop: function() {
  246. if (!this.timer) return;
  247. clearInterval(this.timer);
  248. this.timer = null;
  249. },
  250. onTimerEvent: function() {
  251. if (!this.currentlyExecuting) {
  252. try {
  253. this.currentlyExecuting = true;
  254. this.execute();
  255. } finally {
  256. this.currentlyExecuting = false;
  257. }
  258. }
  259. }
  260. });
  261. Object.extend(String, {
  262. interpret: function(value) {
  263. return value == null ? '' : String(value);
  264. },
  265. specialChar: {
  266. '\b': '\\b',
  267. '\t': '\\t',
  268. '\n': '\\n',
  269. '\f': '\\f',
  270. '\r': '\\r',
  271. '\\': '\\\\'
  272. }
  273. });
  274. Object.extend(String.prototype, {
  275. gsub: function(pattern, replacement) {
  276. var result = '', source = this, match;
  277. replacement = arguments.callee.prepareReplacement(replacement);
  278. while (source.length > 0) {
  279. if (match = source.match(pattern)) {
  280. result += source.slice(0, match.index);
  281. result += String.interpret(replacement(match));
  282. source = source.slice(match.index + match[0].length);
  283. } else {
  284. result += source, source = '';
  285. }
  286. }
  287. return result;
  288. },
  289. sub: function(pattern, replacement, count) {
  290. replacement = this.gsub.prepareReplacement(replacement);
  291. count = Object.isUndefined(count) ? 1 : count;
  292. return this.gsub(pattern, function(match) {
  293. if (--count < 0) return match[0];
  294. return replacement(match);
  295. });
  296. },
  297. scan: function(pattern, iterator) {
  298. this.gsub(pattern, iterator);
  299. return String(this);
  300. },
  301. truncate: function(length, truncation) {
  302. length = length || 30;
  303. truncation = Object.isUndefined(truncation) ? '...' : truncation;
  304. return this.length > length ?
  305. this.slice(0, length - truncation.length) + truncation : String(this);
  306. },
  307. strip: function() {
  308. return this.replace(/^\s+/, '').replace(/\s+$/, '');
  309. },
  310. stripTags: function() {
  311. return this.replace(/<\/?[^>]+>/gi, '');
  312. },
  313. stripScripts: function() {
  314. return this.replace(new RegExp(Prototype.ScriptFragment, 'img'), '');
  315. },
  316. extractScripts: function() {
  317. var matchAll = new RegExp(Prototype.ScriptFragment, 'img');
  318. var matchOne = new RegExp(Prototype.ScriptFragment, 'im');
  319. return (this.match(matchAll) || []).map(function(scriptTag) {
  320. return (scriptTag.match(matchOne) || ['', ''])[1];
  321. });
  322. },
  323. evalScripts: function() {
  324. return this.extractScripts().map(function(script) { return eval(script) });
  325. },
  326. escapeHTML: function() {
  327. var self = arguments.callee;
  328. self.text.data = this;
  329. return self.div.innerHTML;
  330. },
  331. unescapeHTML: function() {
  332. var div = new Element('div');
  333. div.innerHTML = this.stripTags();
  334. return div.childNodes[0] ? (div.childNodes.length > 1 ?
  335. $A(div.childNodes).inject('', function(memo, node) { return memo+node.nodeValue }) :
  336. div.childNodes[0].nodeValue) : '';
  337. },
  338. toQueryParams: function(separator) {
  339. var match = this.strip().match(/([^?#]*)(#.*)?$/);
  340. if (!match) return { };
  341. return match[1].split(separator || '&').inject({ }, function(hash, pair) {
  342. if ((pair = pair.split('='))[0]) {
  343. var key = decodeURIComponent(pair.shift());
  344. var value = pair.length > 1 ? pair.join('=') : pair[0];
  345. if (value != undefined) value = decodeURIComponent(value);
  346. if (key in hash) {
  347. if (!Object.isArray(hash[key])) hash[key] = [hash[key]];
  348. hash[key].push(value);
  349. }
  350. else hash[key] = value;
  351. }
  352. return hash;
  353. });
  354. },
  355. toArray: function() {
  356. return this.split('');
  357. },
  358. succ: function() {
  359. return this.slice(0, this.length - 1) +
  360. String.fromCharCode(this.charCodeAt(this.length - 1) + 1);
  361. },
  362. times: function(count) {
  363. return count < 1 ? '' : new Array(count + 1).join(this);
  364. },
  365. camelize: function() {
  366. var parts = this.split('-'), len = parts.length;
  367. if (len == 1) return parts[0];
  368. var camelized = this.charAt(0) == '-'
  369. ? parts[0].charAt(0).toUpperCase() + parts[0].substring(1)
  370. : parts[0];
  371. for (var i = 1; i < len; i++)
  372. camelized += parts[i].charAt(0).toUpperCase() + parts[i].substring(1);
  373. return camelized;
  374. },
  375. capitalize: function() {
  376. return this.charAt(0).toUpperCase() + this.substring(1).toLowerCase();
  377. },
  378. underscore: function() {
  379. return this.gsub(/::/, '/').gsub(/([A-Z]+)([A-Z][a-z])/,'#{1}_#{2}').gsub(/([a-z\d])([A-Z])/,'#{1}_#{2}').gsub(/-/,'_').toLowerCase();
  380. },
  381. dasherize: function() {
  382. return this.gsub(/_/,'-');
  383. },
  384. inspect: function(useDoubleQuotes) {
  385. var escapedString = this.gsub(/[\x00-\x1f\\]/, function(match) {
  386. var character = String.specialChar[match[0]];
  387. return character ? character : '\\u00' + match[0].charCodeAt().toPaddedString(2, 16);
  388. });
  389. if (useDoubleQuotes) return '"' + escapedString.replace(/"/g, '\\"') + '"';
  390. return "'" + escapedString.replace(/'/g, '\\\'') + "'";
  391. },
  392. toJSON: function() {
  393. return this.inspect(true);
  394. },
  395. unfilterJSON: function(filter) {
  396. return this.sub(filter || Prototype.JSONFilter, '#{1}');
  397. },
  398. isJSON: function() {
  399. var str = this;
  400. if (str.blank()) return false;
  401. str = this.replace(/\\./g, '@').replace(/"[^"\\\n\r]*"/g, '');
  402. return (/^[,:{}\[\]0-9.\-+Eaeflnr-u \n\r\t]*$/).test(str);
  403. },
  404. evalJSON: function(sanitize) {
  405. var json = this.unfilterJSON();
  406. try {
  407. if (!sanitize || json.isJSON()) return eval('(' + json + ')');
  408. } catch (e) { }
  409. throw new SyntaxError('Badly formed JSON string: ' + this.inspect());
  410. },
  411. include: function(pattern) {
  412. return this.indexOf(pattern) > -1;
  413. },
  414. startsWith: function(pattern) {
  415. return this.indexOf(pattern) === 0;
  416. },
  417. endsWith: function(pattern) {
  418. var d = this.length - pattern.length;
  419. return d >= 0 && this.lastIndexOf(pattern) === d;
  420. },
  421. empty: function() {
  422. return this == '';
  423. },
  424. blank: function() {
  425. return /^\s*$/.test(this);
  426. },
  427. interpolate: function(object, pattern) {
  428. return new Template(this, pattern).evaluate(object);
  429. }
  430. });
  431. if (Prototype.Browser.WebKit || Prototype.Browser.IE) Object.extend(String.prototype, {
  432. escapeHTML: function() {
  433. return this.replace(/&/g,'&amp;').replace(/</g,'&lt;').replace(/>/g,'&gt;');
  434. },
  435. unescapeHTML: function() {
  436. return this.replace(/&amp;/g,'&').replace(/&lt;/g,'<').replace(/&gt;/g,'>');
  437. }
  438. });
  439. String.prototype.gsub.prepareReplacement = function(replacement) {
  440. if (Object.isFunction(replacement)) return replacement;
  441. var template = new Template(replacement);
  442. return function(match) { return template.evaluate(match) };
  443. };
  444. String.prototype.parseQuery = String.prototype.toQueryParams;
  445. Object.extend(String.prototype.escapeHTML, {
  446. div: document.createElement('div'),
  447. text: document.createTextNode('')
  448. });
  449. with (String.prototype.escapeHTML) div.appendChild(text);
  450. var Template = Class.create({
  451. initialize: function(template, pattern) {
  452. this.template = template.toString();
  453. this.pattern = pattern || Template.Pattern;
  454. },
  455. evaluate: function(object) {
  456. if (Object.isFunction(object.toTemplateReplacements))
  457. object = object.toTemplateReplacements();
  458. return this.template.gsub(this.pattern, function(match) {
  459. if (object == null) return '';
  460. var before = match[1] || '';
  461. if (before == '\\') return match[2];
  462. var ctx = object, expr = match[3];
  463. var pattern = /^([^.[]+|\[((?:.*?[^\\])?)\])(\.|\[|$)/;
  464. match = pattern.exec(expr);
  465. if (match == null) return before;
  466. while (match != null) {
  467. var comp = match[1].startsWith('[') ? match[2].gsub('\\\\]', ']') : match[1];
  468. ctx = ctx[comp];
  469. if (null == ctx || '' == match[3]) break;
  470. expr = expr.substring('[' == match[3] ? match[1].length : match[0].length);
  471. match = pattern.exec(expr);
  472. }
  473. return before + String.interpret(ctx);
  474. });
  475. }
  476. });
  477. Template.Pattern = /(^|.|\r|\n)(#\{(.*?)\})/;
  478. var $break = { };
  479. var Enumerable = {
  480. each: function(iterator, context) {
  481. var index = 0;
  482. iterator = iterator.bind(context);
  483. try {
  484. this._each(function(value) {
  485. iterator(value, index++);
  486. });
  487. } catch (e) {
  488. if (e != $break) throw e;
  489. }
  490. return this;
  491. },
  492. eachSlice: function(number, iterator, context) {
  493. iterator = iterator ? iterator.bind(context) : Prototype.K;
  494. var index = -number, slices = [], array = this.toArray();
  495. while ((index += number) < array.length)
  496. slices.push(array.slice(index, index+number));
  497. return slices.collect(iterator, context);
  498. },
  499. all: function(iterator, context) {
  500. iterator = iterator ? iterator.bind(context) : Prototype.K;
  501. var result = true;
  502. this.each(function(value, index) {
  503. result = result && !!iterator(value, index);
  504. if (!result) throw $break;
  505. });
  506. return result;
  507. },
  508. any: function(iterator, context) {
  509. iterator = iterator ? iterator.bind(context) : Prototype.K;
  510. var result = false;
  511. this.each(function(value, index) {
  512. if (result = !!iterator(value, index))
  513. throw $break;
  514. });
  515. return result;
  516. },
  517. collect: function(iterator, context) {
  518. iterator = iterator ? iterator.bind(context) : Prototype.K;
  519. var results = [];
  520. this.each(function(value, index) {
  521. results.push(iterator(value, index));
  522. });
  523. return results;
  524. },
  525. detect: function(iterator, context) {
  526. iterator = iterator.bind(context);
  527. var result;
  528. this.each(function(value, index) {
  529. if (iterator(value, index)) {
  530. result = value;
  531. throw $break;
  532. }
  533. });
  534. return result;
  535. },
  536. findAll: function(iterator, context) {
  537. iterator = iterator.bind(context);
  538. var results = [];
  539. this.each(function(value, index) {
  540. if (iterator(value, index))
  541. results.push(value);
  542. });
  543. return results;
  544. },
  545. grep: function(filter, iterator, context) {
  546. iterator = iterator ? iterator.bind(context) : Prototype.K;
  547. var results = [];
  548. if (Object.isString(filter))
  549. filter = new RegExp(filter);
  550. this.each(function(value, index) {
  551. if (filter.match(value))
  552. results.push(iterator(value, index));
  553. });
  554. return results;
  555. },
  556. include: function(object) {
  557. if (Object.isFunction(this.indexOf))
  558. if (this.indexOf(object) != -1) return true;
  559. var found = false;
  560. this.each(function(value) {
  561. if (value == object) {
  562. found = true;
  563. throw $break;
  564. }
  565. });
  566. return found;
  567. },
  568. inGroupsOf: function(number, fillWith) {
  569. fillWith = Object.isUndefined(fillWith) ? null : fillWith;
  570. return this.eachSlice(number, function(slice) {
  571. while(slice.length < number) slice.push(fillWith);
  572. return slice;
  573. });
  574. },
  575. inject: function(memo, iterator, context) {
  576. iterator = iterator.bind(context);
  577. this.each(function(value, index) {
  578. memo = iterator(memo, value, index);
  579. });
  580. return memo;
  581. },
  582. invoke: function(method) {
  583. var args = $A(arguments).slice(1);
  584. return this.map(function(value) {
  585. return value[method].apply(value, args);
  586. });
  587. },
  588. max: function(iterator, context) {
  589. iterator = iterator ? iterator.bind(context) : Prototype.K;
  590. var result;
  591. this.each(function(value, index) {
  592. value = iterator(value, index);
  593. if (result == null || value >= result)
  594. result = value;
  595. });
  596. return result;
  597. },
  598. min: function(iterator, context) {
  599. iterator = iterator ? iterator.bind(context) : Prototype.K;
  600. var result;
  601. this.each(function(value, index) {
  602. value = iterator(value, index);
  603. if (result == null || value < result)
  604. result = value;
  605. });
  606. return result;
  607. },
  608. partition: function(iterator, context) {
  609. iterator = iterator ? iterator.bind(context) : Prototype.K;
  610. var trues = [], falses = [];
  611. this.each(function(value, index) {
  612. (iterator(value, index) ?
  613. trues : falses).push(value);
  614. });
  615. return [trues, falses];
  616. },
  617. pluck: function(property) {
  618. var results = [];
  619. this.each(function(value) {
  620. results.push(value[property]);
  621. });
  622. return results;
  623. },
  624. reject: function(iterator, context) {
  625. iterator = iterator.bind(context);
  626. var results = [];
  627. this.each(function(value, index) {
  628. if (!iterator(value, index))
  629. results.push(value);
  630. });
  631. return results;
  632. },
  633. sortBy: function(iterator, context) {
  634. iterator = iterator.bind(context);
  635. return this.map(function(value, index) {
  636. return {value: value, criteria: iterator(value, index)};
  637. }).sort(function(left, right) {
  638. var a = left.criteria, b = right.criteria;
  639. return a < b ? -1 : a > b ? 1 : 0;
  640. }).pluck('value');
  641. },
  642. toArray: function() {
  643. return this.map();
  644. },
  645. zip: function() {
  646. var iterator = Prototype.K, args = $A(arguments);
  647. if (Object.isFunction(args.last()))
  648. iterator = args.pop();
  649. var collections = [this].concat(args).map($A);
  650. return this.map(function(value, index) {
  651. return iterator(collections.pluck(index));
  652. });
  653. },
  654. size: function() {
  655. return this.toArray().length;
  656. },
  657. inspect: function() {
  658. return '#<Enumerable:' + this.toArray().inspect() + '>';
  659. }
  660. };
  661. Object.extend(Enumerable, {
  662. map: Enumerable.collect,
  663. find: Enumerable.detect,
  664. select: Enumerable.findAll,
  665. filter: Enumerable.findAll,
  666. member: Enumerable.include,
  667. entries: Enumerable.toArray,
  668. every: Enumerable.all,
  669. some: Enumerable.any
  670. });
  671. function $A(iterable) {
  672. if (!iterable) return [];
  673. if (iterable.toArray) return iterable.toArray();
  674. var length = iterable.length || 0, results = new Array(length);
  675. while (length--) results[length] = iterable[length];
  676. return results;
  677. }
  678. if (Prototype.Browser.WebKit) {
  679. $A = function(iterable) {
  680. if (!iterable) return [];
  681. if (!(Object.isFunction(iterable) && iterable == '[object NodeList]') &&
  682. iterable.toArray) return iterable.toArray();
  683. var length = iterable.length || 0, results = new Array(length);
  684. while (length--) results[length] = iterable[length];
  685. return results;
  686. };
  687. }
  688. Array.from = $A;
  689. Object.extend(Array.prototype, Enumerable);
  690. if (!Array.prototype._reverse) Array.prototype._reverse = Array.prototype.reverse;
  691. Object.extend(Array.prototype, {
  692. _each: function(iterator) {
  693. for (var i = 0, length = this.length; i < length; i++)
  694. iterator(this[i]);
  695. },
  696. clear: function() {
  697. this.length = 0;
  698. return this;
  699. },
  700. first: function() {
  701. return this[0];
  702. },
  703. last: function() {
  704. return this[this.length - 1];
  705. },
  706. compact: function() {
  707. return this.select(function(value) {
  708. return value != null;
  709. });
  710. },
  711. flatten: function() {
  712. return this.inject([], function(array, value) {
  713. return array.concat(Object.isArray(value) ?
  714. value.flatten() : [value]);
  715. });
  716. },
  717. without: function() {
  718. var values = $A(arguments);
  719. return this.select(function(value) {
  720. return !values.include(value);
  721. });
  722. },
  723. reverse: function(inline) {
  724. return (inline !== false ? this : this.toArray())._reverse();
  725. },
  726. reduce: function() {
  727. return this.length > 1 ? this : this[0];
  728. },
  729. uniq: function(sorted) {
  730. return this.inject([], function(array, value, index) {
  731. if (0 == index || (sorted ? array.last() != value : !array.include(value)))
  732. array.push(value);
  733. return array;
  734. });
  735. },
  736. intersect: function(array) {
  737. return this.uniq().findAll(function(item) {
  738. return array.detect(function(value) { return item === value });
  739. });
  740. },
  741. clone: function() {
  742. return [].concat(this);
  743. },
  744. size: function() {
  745. return this.length;
  746. },
  747. inspect: function() {
  748. return '[' + this.map(Object.inspect).join(', ') + ']';
  749. },
  750. toJSON: function() {
  751. var results = [];
  752. this.each(function(object) {
  753. var value = Object.toJSON(object);
  754. if (!Object.isUndefined(value)) results.push(value);
  755. });
  756. return '[' + results.join(', ') + ']';
  757. }
  758. });
  759. // use native browser JS 1.6 implementation if available
  760. if (Object.isFunction(Array.prototype.forEach))
  761. Array.prototype._each = Array.prototype.forEach;
  762. if (!Array.prototype.indexOf) Array.prototype.indexOf = function(item, i) {
  763. i || (i = 0);
  764. var length = this.length;
  765. if (i < 0) i = length + i;
  766. for (; i < length; i++)
  767. if (this[i] === item) return i;
  768. return -1;
  769. };
  770. if (!Array.prototype.lastIndexOf) Array.prototype.lastIndexOf = function(item, i) {
  771. i = isNaN(i) ? this.length : (i < 0 ? this.length + i : i) + 1;
  772. var n = this.slice(0, i).reverse().indexOf(item);
  773. return (n < 0) ? n : i - n - 1;
  774. };
  775. Array.prototype.toArray = Array.prototype.clone;
  776. function $w(string) {
  777. if (!Object.isString(string)) return [];
  778. string = string.strip();
  779. return string ? string.split(/\s+/) : [];
  780. }
  781. if (Prototype.Browser.Opera){
  782. Array.prototype.concat = function() {
  783. var array = [];
  784. for (var i = 0, length = this.length; i < length; i++) array.push(this[i]);
  785. for (var i = 0, length = arguments.length; i < length; i++) {
  786. if (Object.isArray(arguments[i])) {
  787. for (var j = 0, arrayLength = arguments[i].length; j < arrayLength; j++)
  788. array.push(arguments[i][j]);
  789. } else {
  790. array.push(arguments[i]);
  791. }
  792. }
  793. return array;
  794. };
  795. }
  796. Object.extend(Number.prototype, {
  797. toColorPart: function() {
  798. return this.toPaddedString(2, 16);
  799. },
  800. succ: function() {
  801. return this + 1;
  802. },
  803. times: function(iterator) {
  804. $R(0, this, true).each(iterator);
  805. return this;
  806. },
  807. toPaddedString: function(length, radix) {
  808. var string = this.toString(radix || 10);
  809. return '0'.times(length - string.length) + string;
  810. },
  811. toJSON: function() {
  812. return isFinite(this) ? this.toString() : 'null';
  813. }
  814. });
  815. $w('abs round ceil floor').each(function(method){
  816. Number.prototype[method] = Math[method].methodize();
  817. });
  818. function $H(object) {
  819. return new Hash(object);
  820. };
  821. var Hash = Class.create(Enumerable, (function() {
  822. function toQueryPair(key, value) {
  823. if (Object.isUndefined(value)) return key;
  824. return key + '=' + encodeURIComponent(String.interpret(value));
  825. }
  826. return {
  827. initialize: function(object) {
  828. this._object = Object.isHash(object) ? object.toObject() : Object.clone(object);
  829. },
  830. _each: function(iterator) {
  831. for (var key in this._object) {
  832. var value = this._object[key], pair = [key, value];
  833. pair.key = key;
  834. pair.value = value;
  835. iterator(pair);
  836. }
  837. },
  838. set: function(key, value) {
  839. return this._object[key] = value;
  840. },
  841. get: function(key) {
  842. return this._object[key];
  843. },
  844. unset: function(key) {
  845. var value = this._object[key];
  846. delete this._object[key];
  847. return value;
  848. },
  849. toObject: function() {
  850. return Object.clone(this._object);
  851. },
  852. keys: function() {
  853. return this.pluck('key');
  854. },
  855. values: function() {
  856. return this.pluck('value');
  857. },
  858. index: function(value) {
  859. var match = this.detect(function(pair) {
  860. return pair.value === value;
  861. });
  862. return match && match.key;
  863. },
  864. merge: function(object) {
  865. return this.clone().update(object);
  866. },
  867. update: function(object) {
  868. return new Hash(object).inject(this, function(result, pair) {
  869. result.set(pair.key, pair.value);
  870. return result;
  871. });
  872. },
  873. toQueryString: function() {
  874. return this.map(function(pair) {
  875. var key = encodeURIComponent(pair.key), values = pair.value;
  876. if (values && typeof values == 'object') {
  877. if (Object.isArray(values))
  878. return values.map(toQueryPair.curry(key)).join('&');
  879. }
  880. return toQueryPair(key, values);
  881. }).join('&');
  882. },
  883. inspect: function() {
  884. return '#<Hash:{' + this.map(function(pair) {
  885. return pair.map(Object.inspect).join(': ');
  886. }).join(', ') + '}>';
  887. },
  888. toJSON: function() {
  889. return Object.toJSON(this.toObject());
  890. },
  891. clone: function() {
  892. return new Hash(this);
  893. }
  894. }
  895. })());
  896. Hash.prototype.toTemplateReplacements = Hash.prototype.toObject;
  897. Hash.from = $H;
  898. var ObjectRange = Class.create(Enumerable, {
  899. initialize: function(start, end, exclusive) {
  900. this.start = start;
  901. this.end = end;
  902. this.exclusive = exclusive;
  903. },
  904. _each: function(iterator) {
  905. var value = this.start;
  906. while (this.include(value)) {
  907. iterator(value);
  908. value = value.succ();
  909. }
  910. },
  911. include: function(value) {
  912. if (value < this.start)
  913. return false;
  914. if (this.exclusive)
  915. return value < this.end;
  916. return value <= this.end;
  917. }
  918. });
  919. var $R = function(start, end, exclusive) {
  920. return new ObjectRange(start, end, exclusive);
  921. };
  922. var Ajax = {
  923. getTransport: function() {
  924. return Try.these(
  925. function() {return new XMLHttpRequest()},
  926. function() {return new ActiveXObject('Msxml2.XMLHTTP')},
  927. function() {return new ActiveXObject('Microsoft.XMLHTTP')}
  928. ) || false;
  929. },
  930. activeRequestCount: 0
  931. };
  932. Ajax.Responders = {
  933. responders: [],
  934. _each: function(iterator) {
  935. this.responders._each(iterator);
  936. },
  937. register: function(responder) {
  938. if (!this.include(responder))
  939. this.responders.push(responder);
  940. },
  941. unregister: function(responder) {
  942. this.responders = this.responders.without(responder);
  943. },
  944. dispatch: function(callback, request, transport, json) {
  945. this.each(function(responder) {
  946. if (Object.isFunction(responder[callback])) {
  947. try {
  948. responder[callback].apply(responder, [request, transport, json]);
  949. } catch (e) { }
  950. }
  951. });
  952. }
  953. };
  954. Object.extend(Ajax.Responders, Enumerable);
  955. Ajax.Responders.register({
  956. onCreate: function() { Ajax.activeRequestCount++ },
  957. onComplete: function() { Ajax.activeRequestCount-- }
  958. });
  959. Ajax.Base = Class.create({
  960. initialize: function(options) {
  961. this.options = {
  962. method: 'post',
  963. asynchronous: true,
  964. contentType: 'application/x-www-form-urlencoded',
  965. encoding: 'UTF-8',
  966. parameters: '',
  967. evalJSON: true,
  968. evalJS: true
  969. };
  970. Object.extend(this.options, options || { });
  971. this.options.method = this.options.method.toLowerCase();
  972. if (Object.isString(this.options.parameters))
  973. this.options.parameters = this.options.parameters.toQueryParams();
  974. else if (Object.isHash(this.options.parameters))
  975. this.options.parameters = this.options.parameters.toObject();
  976. }
  977. });
  978. Ajax.Request = Class.create(Ajax.Base, {
  979. _complete: false,
  980. initialize: function($super, url, options) {
  981. $super(options);
  982. this.transport = Ajax.getTransport();
  983. this.request(url);
  984. },
  985. request: function(url) {
  986. this.url = url;
  987. this.method = this.options.method;
  988. var params = Object.clone(this.options.parameters);
  989. if (!['get', 'post'].include(this.method)) {
  990. // simulate other verbs over post
  991. params['_method'] = this.method;
  992. this.method = 'post';
  993. }
  994. this.parameters = params;
  995. if (params = Object.toQueryString(params)) {
  996. // when GET, append parameters to URL
  997. if (this.method == 'get')
  998. this.url += (this.url.include('?') ? '&' : '?') + params;
  999. else if (/Konqueror|Safari|KHTML/.test(navigator.userAgent))
  1000. params += '&_=';
  1001. }
  1002. try {
  1003. var response = new Ajax.Response(this);
  1004. if (this.options.onCreate) this.options.onCreate(response);
  1005. Ajax.Responders.dispatch('onCreate', this, response);
  1006. this.transport.open(this.method.toUpperCase(), this.url,
  1007. this.options.asynchronous);
  1008. if (this.options.asynchronous) this.respondToReadyState.bind(this).defer(1);
  1009. this.transport.onreadystatechange = this.onStateChange.bind(this);
  1010. this.setRequestHeaders();
  1011. this.body = this.method == 'post' ? (this.options.postBody || params) : null;
  1012. this.transport.send(this.body);
  1013. /* Force Firefox to handle ready state 4 for synchronous requests */
  1014. if (!this.options.asynchronous && this.transport.overrideMimeType)
  1015. this.onStateChange();
  1016. }
  1017. catch (e) {
  1018. this.dispatchException(e);
  1019. }
  1020. },
  1021. onStateChange: function() {
  1022. var readyState = this.transport.readyState;
  1023. if (readyState > 1 && !((readyState == 4) && this._complete))
  1024. this.respondToReadyState(this.transport.readyState);
  1025. },
  1026. setRequestHeaders: function() {
  1027. var headers = {
  1028. 'X-Requested-With': 'XMLHttpRequest',
  1029. 'X-Prototype-Version': Prototype.Version,
  1030. 'Accept': 'text/javascript, text/html, application/xml, text/xml, */*'
  1031. };
  1032. if (this.method == 'post') {
  1033. headers['Content-type'] = this.options.contentType +
  1034. (this.options.encoding ? '; charset=' + this.options.encoding : '');
  1035. /* Force "Connection: close" for older Mozilla browsers to work
  1036. * around a bug where XMLHttpRequest sends an incorrect
  1037. * Content-length header. See Mozilla Bugzilla #246651.
  1038. */
  1039. if (this.transport.overrideMimeType &&
  1040. (navigator.userAgent.match(/Gecko\/(\d{4})/) || [0,2005])[1] < 2005)
  1041. headers['Connection'] = 'close';
  1042. }
  1043. // user-defined headers
  1044. if (typeof this.options.requestHeaders == 'object') {
  1045. var extras = this.options.requestHeaders;
  1046. if (Object.isFunction(extras.push))
  1047. for (var i = 0, length = extras.length; i < length; i += 2)
  1048. headers[extras[i]] = extras[i+1];
  1049. else
  1050. $H(extras).each(function(pair) { headers[pair.key] = pair.value });
  1051. }
  1052. for (var name in headers)
  1053. this.transport.setRequestHeader(name, headers[name]);
  1054. },
  1055. success: function() {
  1056. var status = this.getStatus();
  1057. return !status || (status >= 200 && status < 300);
  1058. },
  1059. getStatus: function() {
  1060. try {
  1061. return this.transport.status || 0;
  1062. } catch (e) { return 0 }
  1063. },
  1064. respondToReadyState: function(readyState) {
  1065. var state = Ajax.Request.Events[readyState], response = new Ajax.Response(this);
  1066. if (state == 'Complete') {
  1067. try {
  1068. this._complete = true;
  1069. (this.options['on' + response.status]
  1070. || this.options['on' + (this.success() ? 'Success' : 'Failure')]
  1071. || Prototype.emptyFunction)(response, response.headerJSON);
  1072. } catch (e) {
  1073. this.dispatchException(e);
  1074. }
  1075. var contentType = response.getHeader('Content-type');
  1076. if (this.options.evalJS == 'force'
  1077. || (this.options.evalJS && this.isSameOrigin() && contentType
  1078. && contentType.match(/^\s*(text|application)\/(x-)?(java|ecma)script(;.*)?\s*$/i)))
  1079. this.evalResponse();
  1080. }
  1081. try {
  1082. (this.options['on' + state] || Prototype.emptyFunction)(response, response.headerJSON);
  1083. Ajax.Responders.dispatch('on' + state, this, response, response.headerJSON);
  1084. } catch (e) {
  1085. this.dispatchException(e);
  1086. }
  1087. if (state == 'Complete') {
  1088. // avoid memory leak in MSIE: clean up
  1089. this.transport.onreadystatechange = Prototype.emptyFunction;
  1090. }
  1091. },
  1092. isSameOrigin: function() {
  1093. var m = this.url.match(/^\s*https?:\/\/[^\/]*/);
  1094. return !m || (m[0] == '#{protocol}//#{domain}#{port}'.interpolate({
  1095. protocol: location.protocol,
  1096. domain: document.domain,
  1097. port: location.port ? ':' + location.port : ''
  1098. }));
  1099. },
  1100. getHeader: function(name) {
  1101. try {
  1102. return this.transport.getResponseHeader(name) || null;
  1103. } catch (e) { return null }
  1104. },
  1105. evalResponse: function() {
  1106. try {
  1107. return eval((this.transport.responseText || '').unfilterJSON());
  1108. } catch (e) {
  1109. this.dispatchException(e);
  1110. }
  1111. },
  1112. dispatchException: function(exception) {
  1113. (this.options.onException || Prototype.emptyFunction)(this, exception);
  1114. Ajax.Responders.dispatch('onException', this, exception);
  1115. }
  1116. });
  1117. Ajax.Request.Events =
  1118. ['Uninitialized', 'Loading', 'Loaded', 'Interactive', 'Complete'];
  1119. Ajax.Response = Class.create({
  1120. initialize: function(request){
  1121. this.request = request;
  1122. var transport = this.transport = request.transport,
  1123. readyState = this.readyState = transport.readyState;
  1124. if((readyState > 2 && !Prototype.Browser.IE) || readyState == 4) {
  1125. this.status = this.getStatus();
  1126. this.statusText = this.getStatusText();
  1127. this.responseText = String.interpret(transport.responseText);
  1128. this.headerJSON = this._getHeaderJSON();
  1129. }
  1130. if(readyState == 4) {
  1131. var xml = transport.responseXML;
  1132. this.responseXML = Object.isUndefined(xml) ? null : xml;
  1133. this.responseJSON = this._getResponseJSON();
  1134. }
  1135. },
  1136. status: 0,
  1137. statusText: '',
  1138. getStatus: Ajax.Request.prototype.getStatus,
  1139. getStatusText: function() {
  1140. try {
  1141. return this.transport.statusText || '';
  1142. } catch (e) { return '' }
  1143. },
  1144. getHeader: Ajax.Request.prototype.getHeader,
  1145. getAllHeaders: function() {
  1146. try {
  1147. return this.getAllResponseHeaders();
  1148. } catch (e) { return null }
  1149. },
  1150. getResponseHeader: function(name) {
  1151. return this.transport.getResponseHeader(name);
  1152. },
  1153. getAllResponseHeaders: function() {
  1154. return this.transport.getAllResponseHeaders();
  1155. },
  1156. _getHeaderJSON: function() {
  1157. var json = this.getHeader('X-JSON');
  1158. if (!json) return null;
  1159. json = decodeURIComponent(escape(json));
  1160. try {
  1161. return json.evalJSON(this.request.options.sanitizeJSON ||
  1162. !this.request.isSameOrigin());
  1163. } catch (e) {
  1164. this.request.dispatchException(e);
  1165. }
  1166. },
  1167. _getResponseJSON: function() {
  1168. var options = this.request.options;
  1169. if (!options.evalJSON || (options.evalJSON != 'force' &&
  1170. !(this.getHeader('Content-type') || '').include('application/json')) ||
  1171. this.responseText.blank())
  1172. return null;
  1173. try {
  1174. return this.responseText.evalJSON(options.sanitizeJSON ||
  1175. !this.request.isSameOrigin());
  1176. } catch (e) {
  1177. this.request.dispatchException(e);
  1178. }
  1179. }
  1180. });
  1181. Ajax.Updater = Class.create(Ajax.Request, {
  1182. initialize: function($super, container, url, options) {
  1183. this.container = {
  1184. success: (container.success || container),
  1185. failure: (container.failure || (container.success ? null : container))
  1186. };
  1187. options = Object.clone(options);
  1188. var onComplete = options.onComplete;
  1189. options.onComplete = (function(response, json) {
  1190. this.updateContent(response.responseText);
  1191. if (Object.isFunction(onComplete)) onComplete(response, json);
  1192. }).bind(this);
  1193. $super(url, options);
  1194. },
  1195. updateContent: function(responseText) {
  1196. var receiver = this.container[this.success() ? 'success' : 'failure'],
  1197. options = this.options;
  1198. if (!options.evalScripts) responseText = responseText.stripScripts();
  1199. if (receiver = $(receiver)) {
  1200. if (options.insertion) {
  1201. if (Object.isString(options.insertion)) {
  1202. var insertion = { }; insertion[options.insertion] = responseText;
  1203. receiver.insert(insertion);
  1204. }
  1205. else options.insertion(receiver, responseText);
  1206. }
  1207. else receiver.update(responseText);
  1208. }
  1209. }
  1210. });
  1211. Ajax.PeriodicalUpdater = Class.create(Ajax.Base, {
  1212. initialize: function($super, container, url, options) {
  1213. $super(options);
  1214. this.onComplete = this.options.onComplete;
  1215. this.frequency = (this.options.frequency || 2);
  1216. this.decay = (this.options.decay || 1);
  1217. this.updater = { };
  1218. this.container = container;
  1219. this.url = url;
  1220. this.start();
  1221. },
  1222. start: function() {
  1223. this.options.onComplete = this.updateComplete.bind(this);
  1224. this.onTimerEvent();
  1225. },
  1226. stop: function() {
  1227. this.updater.options.onComplete = undefined;
  1228. clearTimeout(this.timer);
  1229. (this.onComplete || Prototype.emptyFunction).apply(this, arguments);
  1230. },
  1231. updateComplete: function(response) {
  1232. if (this.options.decay) {
  1233. this.decay = (response.responseText == this.lastText ?
  1234. this.decay * this.options.decay : 1);
  1235. this.lastText = response.responseText;
  1236. }
  1237. this.timer = this.onTimerEvent.bind(this).delay(this.decay * this.frequency);
  1238. },
  1239. onTimerEvent: function() {
  1240. this.updater = new Ajax.Updater(this.container, this.url, this.options);
  1241. }
  1242. });
  1243. function $(element) {
  1244. if (arguments.length > 1) {
  1245. for (var i = 0, elements = [], length = arguments.length; i < length; i++)
  1246. elements.push($(arguments[i]));
  1247. return elements;
  1248. }
  1249. if (Object.isString(element))
  1250. element = document.getElementById(element);
  1251. return Element.extend(element);
  1252. }
  1253. if (Prototype.BrowserFeatures.XPath) {
  1254. document._getElementsByXPath = function(expression, parentElement) {
  1255. var results = [];
  1256. var query = document.evaluate(expression, $(parentElement) || document,
  1257. null, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);
  1258. for (var i = 0, length = query.snapshotLength; i < length; i++)
  1259. results.push(Element.extend(query.snapshotItem(i)));
  1260. return results;
  1261. };
  1262. }
  1263. /*--------------------------------------------------------------------------*/
  1264. if (!window.Node) var Node = { };
  1265. if (!Node.ELEMENT_NODE) {
  1266. // DOM level 2 ECMAScript Language Binding
  1267. Object.extend(Node, {
  1268. ELEMENT_NODE: 1,
  1269. ATTRIBUTE_NODE: 2,
  1270. TEXT_NODE: 3,
  1271. CDATA_SECTION_NODE: 4,
  1272. ENTITY_REFERENCE_NODE: 5,
  1273. ENTITY_NODE: 6,
  1274. PROCESSING_INSTRUCTION_NODE: 7,
  1275. COMMENT_NODE: 8,
  1276. DOCUMENT_NODE: 9,
  1277. DOCUMENT_TYPE_NODE: 10,
  1278. DOCUMENT_FRAGMENT_NODE: 11,
  1279. NOTATION_NODE: 12
  1280. });
  1281. }
  1282. (function() {
  1283. var element = this.Element;
  1284. this.Element = function(tagName, attributes) {
  1285. attributes = attributes || { };
  1286. tagName = tagName.toLowerCase();
  1287. var cache = Element.cache;
  1288. if (Prototype.Browser.IE && attributes.name) {
  1289. tagName = '<' + tagName + ' name="' + attributes.name + '">';
  1290. delete attributes.name;
  1291. return Element.writeAttribute(document.createElement(tagName), attributes);
  1292. }
  1293. if (!cache[tagName]) cache[tagName] = Element.extend(document.createElement(tagName));
  1294. return Element.writeAttribute(cache[tagName].cloneNode(false), attributes);
  1295. };
  1296. Object.extend(this.Element, element || { });
  1297. }).call(window);
  1298. Element.cache = { };
  1299. Element.Methods = {
  1300. visible: function(element) {
  1301. return $(element).style.display != 'none';
  1302. },
  1303. toggle: function(element) {
  1304. element = $(element);
  1305. Element[Element.visible(element) ? 'hide' : 'show'](element);
  1306. return element;
  1307. },
  1308. hide: function(element) {
  1309. $(element).style.display = 'none';
  1310. return element;
  1311. },
  1312. show: function(element) {
  1313. $(element).style.display = '';
  1314. return element;
  1315. },
  1316. remove: function(element) {
  1317. element = $(element);
  1318. element.parentNode.removeChild(element);
  1319. return element;
  1320. },
  1321. update: function(element, content) {
  1322. element = $(element);
  1323. if (content && content.toElement) content = content.toElement();
  1324. if (Object.isElement(content)) return element.update().insert(content);
  1325. content = Object.toHTML(content);
  1326. element.innerHTML = content.stripScripts();
  1327. content.evalScripts.bind(content).defer();
  1328. return element;
  1329. },
  1330. replace: function(element, content) {
  1331. element = $(element);
  1332. if (content && content.toElement) content = content.toElement();
  1333. else if (!Object.isElement(content)) {
  1334. content = Object.toHTML(content);
  1335. var range = element.ownerDocument.createRange();
  1336. range.selectNode(element);
  1337. content.evalScripts.bind(content).defer();
  1338. content = range.createContextualFragment(content.stripScripts());
  1339. }
  1340. element.parentNode.replaceChild(content, element);
  1341. return element;
  1342. },
  1343. insert: function(element, insertions) {
  1344. element = $(element);
  1345. if (Object.isString(insertions) || Object.isNumber(insertions) ||
  1346. Object.isElement(insertions) || (insertions && (insertions.toElement || insertions.toHTML)))
  1347. insertions = {bottom:insertions};
  1348. var content, insert, tagName, childNodes;
  1349. for (var position in insertions) {
  1350. content = insertions[position];
  1351. position = position.toLowerCase();
  1352. insert = Element._insertionTranslations[position];
  1353. if (content && content.toElement) content = content.toElement();
  1354. if (Object.isElement(content)) {
  1355. insert(element, content);
  1356. continue;
  1357. }
  1358. content = Object.toHTML(content);
  1359. tagName = ((position == 'before' || position == 'after')
  1360. ? element.parentNode : element).tagName.toUpperCase();
  1361. childNodes = Element._getContentFromAnonymousElement(tagName, content.stripScripts());
  1362. if (position == 'top' || position == 'after') childNodes.reverse();
  1363. childNodes.each(insert.curry(element));
  1364. content.evalScripts.bind(content).defer();
  1365. }
  1366. return element;
  1367. },
  1368. wrap: function(element, wrapper, attributes) {
  1369. element = $(element);
  1370. if (Object.isElement(wrapper))
  1371. $(wrapper).writeAttribute(attributes || { });
  1372. else if (Object.isString(wrapper)) wrapper = new Element(wrapper, attributes);
  1373. else wrapper = new Element('div', wrapper);
  1374. if (element.parentNode)
  1375. element.parentNode.replaceChild(wrapper, element);
  1376. wrapper.appendChild(element);
  1377. return wrapper;
  1378. },
  1379. inspect: function(element) {
  1380. element = $(element);
  1381. var result = '<' + element.tagName.toLowerCase();
  1382. $H({'id': 'id', 'className': 'class'}).each(function(pair) {
  1383. var property = pair.first(), attribute = pair.last();
  1384. var value = (element[property] || '').toString();
  1385. if (value) result += ' ' + attribute + '=' + value.inspect(true);
  1386. });
  1387. return result + '>';
  1388. },
  1389. recursivelyCollect: function(element, property) {
  1390. element = $(element);
  1391. var elements = [];
  1392. while (element = element[property])
  1393. if (element.nodeType == 1)
  1394. elements.push(Element.extend(element));
  1395. return elements;
  1396. },
  1397. ancestors: function(element) {
  1398. return $(element).recursivelyCollect('parentNode');
  1399. },
  1400. descendants: function(element) {
  1401. return $(element).select("*");
  1402. },
  1403. firstDescendant: function(element) {
  1404. element = $(element).firstChild;
  1405. while (element && element.nodeType != 1) element = element.nextSibling;
  1406. return $(element);
  1407. },
  1408. immediateDescendants: function(element) {
  1409. if (!(element = $(element).firstChild)) return [];
  1410. while (element && element.nodeType != 1) element = element.nextSibling;
  1411. if (element) return [element].concat($(element).nextSiblings());
  1412. return [];
  1413. },
  1414. previousSiblings: function(element) {
  1415. return $(element).recursivelyCollect('previousSibling');
  1416. },
  1417. nextSiblings: function(element) {
  1418. return $(element).recursivelyCollect('nextSibling');
  1419. },
  1420. siblings: function(element) {
  1421. element = $(element);
  1422. return element.previousSiblings().reverse().concat(element.nextSiblings());
  1423. },
  1424. match: function(element, selector) {
  1425. if (Object.isString(selector))
  1426. selector = new Selector(selector);
  1427. return selector.match($(element));
  1428. },
  1429. up: function(element, expression, index) {
  1430. element = $(element);
  1431. if (arguments.length == 1) return $(element.parentNode);
  1432. var ancestors = element.ancestors();
  1433. return Object.isNumber(expression) ? ancestors[expression] :
  1434. Selector.findElement(ancestors, expression, index);
  1435. },
  1436. down: function(element, expression, index) {
  1437. element = $(element);
  1438. if (arguments.length == 1) return element.firstDescendant();
  1439. return Object.isNumber(expression) ? element.descendants()[expression] :
  1440. element.select(expression)[index || 0];
  1441. },
  1442. previous: function(element, expression, index) {
  1443. element = $(element);
  1444. if (arguments.length == 1) return $(Selector.handlers.previousElementSibling(element));
  1445. var previousSiblings = element.previousSiblings();
  1446. return Object.isNumber(expression) ? previousSiblings[expression] :
  1447. Selector.findElement(previousSiblings, expression, index);
  1448. },
  1449. next: function(element, expression, index) {
  1450. element = $(element);
  1451. if (arguments.length == 1) return $(Selector.handlers.nextElementSibling(element));
  1452. var nextSiblings = element.nextSiblings();
  1453. return Object.isNumber(expression) ? nextSiblings[expression] :
  1454. Selector.findElement(nextSiblings, expression, index);
  1455. },
  1456. select: function() {
  1457. var args = $A(arguments), element = $(args.shift());
  1458. return Selector.findChildElements(element, args);
  1459. },
  1460. adjacent: function() {
  1461. var args = $A(arguments), element = $(args.shift());
  1462. return Selector.findChildElements(element.parentNode, args).without(element);
  1463. },
  1464. identify: function(element) {
  1465. element = $(element);
  1466. var id = element.readAttribute('id'), self = arguments.callee;
  1467. if (id) return id;
  1468. do { id = 'anonymous_element_' + self.counter++ } while ($(id));
  1469. element.writeAttribute('id', id);
  1470. return id;
  1471. },
  1472. readAttribute: function(element, name) {
  1473. element = $(element);
  1474. if (Prototype.Browser.IE) {
  1475. var t = Element._attributeTranslations.read;
  1476. if (t.values[name]) return t.values[name](element, name);
  1477. if (t.names[name]) name = t.names[name];
  1478. if (name.include(':')) {
  1479. return (!element.attributes || !element.attributes[name]) ? null :
  1480. element.attributes[name].value;
  1481. }
  1482. }
  1483. return element.getAttribute(name);
  1484. },
  1485. writeAttribute: function(element, name, value) {
  1486. element = $(element);
  1487. var attributes = { }, t = Element._attributeTranslations.write;
  1488. if (typeof name == 'object') attributes = name;
  1489. else attributes[name] = Object.isUndefined(value) ? true : value;
  1490. for (var attr in attributes) {
  1491. name = t.names[attr] || attr;
  1492. value = attributes[attr];
  1493. if (t.values[attr]) name = t.values[attr](element, value);
  1494. if (value === false || value === null)
  1495. element.removeAttribute(name);
  1496. else if (value === true)
  1497. element.setAttribute(name, name);
  1498. else element.setAttribute(name, value);
  1499. }
  1500. return element;
  1501. },
  1502. getHeight: function(element) {
  1503. return $(element).getDimensions().height;
  1504. },
  1505. getWidth: function(element) {
  1506. return $(element).getDimensions().width;
  1507. },
  1508. classNames: function(element) {
  1509. return new Element.ClassNames(element);
  1510. },
  1511. hasClassName: function(element, className) {
  1512. if (!(element = $(element))) return;
  1513. var elementClassName = element.className;
  1514. return (elementClassName.length > 0 && (elementClassName == className ||
  1515. new RegExp("(^|\\s)" + className + "(\\s|$)").test(elementClassName)));
  1516. },
  1517. addClassName: function(element, className) {
  1518. if (!(element = $(element))) return;
  1519. if (!element.hasClassName(className))
  1520. element.className += (element.className ? ' ' : '') + className;
  1521. return element;
  1522. },
  1523. removeClassName: function(element, className) {
  1524. if (!(element = $(element))) return;
  1525. element.className = element.className.replace(
  1526. new RegExp("(^|\\s+)" + className + "(\\s+|$)"), ' ').strip();
  1527. return element;
  1528. },
  1529. toggleClassName: function(element, className) {
  1530. if (!(element = $(element))) return;
  1531. return element[element.hasClassName(className) ?
  1532. 'removeClassName' : 'addClassName'](className);
  1533. },
  1534. // removes whitespace-only text node children
  1535. cleanWhitespace: function(element) {
  1536. element = $(element);
  1537. var node = element.firstChild;
  1538. while (node) {
  1539. var nextNode = node.nextSibling;
  1540. if (node.nodeType == 3 && !/\S/.test(node.nodeValue))
  1541. element.removeChild(node);
  1542. node = nextNode;
  1543. }
  1544. return element;
  1545. },
  1546. empty: function(element) {
  1547. return $(element).innerHTML.blank();
  1548. },
  1549. descendantOf: function(element, ancestor) {
  1550. element = $(element), ancestor = $(ancestor);
  1551. var originalAncestor = ancestor;
  1552. if (element.compareDocumentPosition)
  1553. return (element.compareDocumentPosition(ancestor) & 8) === 8;
  1554. if (element.sourceIndex && !Prototype.Browser.Opera) {
  1555. var e = element.sourceIndex, a = ancestor.sourceIndex,
  1556. nextAncestor = ancestor.nextSibling;
  1557. if (!nextAncestor) {
  1558. do { ancestor = ancestor.parentNode; }
  1559. while (!(nextAncestor = ancestor.nextSibling) && ancestor.parentNode);
  1560. }
  1561. if (nextAncestor && nextAncestor.sourceIndex)
  1562. return (e > a && e < nextAncestor.sourceIndex);
  1563. }
  1564. while (element = element.parentNode)
  1565. if (element == originalAncestor) return true;
  1566. return false;
  1567. },
  1568. scrollTo: function(element) {
  1569. element = $(element);
  1570. var pos = element.cumulativeOffset();
  1571. window.scrollTo(pos[0], pos[1]);
  1572. return element;
  1573. },
  1574. getStyle: function(element, style) {
  1575. element = $(element);
  1576. style = style == 'float' ? 'cssFloat' : style.camelize();
  1577. var value = element.style[style];
  1578. if (!value) {
  1579. var css = document.defaultView.getComputedStyle(element, null);
  1580. value = css ? css[style] : null;
  1581. }
  1582. if (style == 'opacity') return value ? parseFloat(value) : 1.0;
  1583. return value == 'auto' ? null : value;
  1584. },
  1585. getOpacity: function(element) {
  1586. return $(element).getStyle('opacity');
  1587. },
  1588. setStyle: function(element, styles) {
  1589. element = $(element);
  1590. var elementStyle = element.style, match;
  1591. if (Object.isString(styles)) {
  1592. element.style.cssText += ';' + styles;
  1593. return styles.include('opacity') ?
  1594. element.setOpacity(styles.match(/opacity:\s*(\d?\.?\d*)/)[1]) : element;
  1595. }
  1596. for (var property in styles)
  1597. if (property == 'opacity') element.setOpacity(styles[property]);
  1598. else
  1599. elementStyle[(property == 'float' || property == 'cssFloat') ?
  1600. (Object.isUndefined(elementStyle.styleFloat) ? 'cssFloat' : 'styleFloat') :
  1601. property] = styles[property];
  1602. return element;
  1603. },
  1604. setOpacity: function(element, value) {
  1605. element = $(element);
  1606. element.style.opacity = (value == 1 || value === '') ? '' :
  1607. (value < 0.00001) ? 0 : value;
  1608. return element;
  1609. },
  1610. getDimensions: function(element) {
  1611. element = $(element);
  1612. var display = $(element).getStyle('display');
  1613. if (display != 'none' && display != null) // Safari bug
  1614. return {width: element.offsetWidth, height: element.offsetHeight};
  1615. // All *Width and *Height properties give 0 on elements with display none,
  1616. // so enable the element temporarily
  1617. var els = element.style;
  1618. var originalVisibility = els.visibility;
  1619. var originalPosition = els.position;
  1620. var originalDisplay = els.display;
  1621. els.visibility = 'hidden';
  1622. els.position = 'absolute';
  1623. els.display = 'block';
  1624. var originalWidth = element.clientWidth;
  1625. var originalHeight = element.clientHeight;
  1626. els.display = originalDisplay;
  1627. els.position = originalPosition;
  1628. els.visibility = originalVisibility;
  1629. return {width: originalWidth, height: originalHeight};
  1630. },
  1631. makePositioned: function(element) {
  1632. element = $(element);
  1633. var pos = Element.getStyle(element, 'position');
  1634. if (pos == 'static' || !pos) {
  1635. element._madePositioned = true;
  1636. element.style.position = 'relative';
  1637. // Opera returns the offset relative to the positioning context, when an
  1638. // element is position relative but top and left have not been defined
  1639. if (window.opera) {
  1640. element.style.top = 0;
  1641. element.style.left = 0;
  1642. }
  1643. }
  1644. return element;
  1645. },
  1646. undoPositioned: function(element) {
  1647. element = $(element);
  1648. if (element._madePositioned) {
  1649. element._madePositioned = undefined;
  1650. element.style.position =
  1651. element.style.top =
  1652. element.style.left =
  1653. element.style.bottom =
  1654. element.style.right = '';
  1655. }
  1656. return element;
  1657. },
  1658. makeClipping: function(element) {
  1659. element = $(element);
  1660. if (element._overflow) return element;
  1661. element._overflow = Element.getStyle(element, 'overflow') || 'auto';
  1662. if (element._overflow !== 'hidden')
  1663. element.style.overflow = 'hidden';
  1664. return element;
  1665. },
  1666. undoClipping: function(element) {
  1667. element = $(element);
  1668. if (!element._overflow) return element;
  1669. element.style.overflow = element._overflow == 'auto' ? '' : element._overflow;
  1670. element._overflow = null;
  1671. return element;
  1672. },
  1673. cumulativeOffset: function(element) {
  1674. var valueT = 0, valueL = 0;
  1675. do {
  1676. valueT += element.offsetTop || 0;
  1677. valueL += element.offsetLeft || 0;
  1678. element = element.offsetParent;
  1679. } while (element);
  1680. return Element._returnOffset(valueL, valueT);
  1681. },
  1682. positionedOffset: function(element) {
  1683. var valueT = 0, valueL = 0;
  1684. do {
  1685. valueT += element.offsetTop || 0;
  1686. valueL += element.offsetLeft || 0;
  1687. element = element.offsetParent;
  1688. if (element) {
  1689. if (element.tagName == 'BODY') break;
  1690. var p = Element.getStyle(element, 'position');
  1691. if (p !== 'static') break;
  1692. }
  1693. } while (element);
  1694. return Element._returnOffset(valueL, valueT);
  1695. },
  1696. absolutize: function(element) {
  1697. element = $(element);
  1698. if (element.getStyle('position') == 'absolute') return;
  1699. // Position.prepare(); // To be done manually by Scripty when it needs it.
  1700. var offsets = element.positionedOffset();
  1701. var top = offsets[1];
  1702. var left = offsets[0];
  1703. var width = element.clientWidth;
  1704. var height = element.clientHeight;
  1705. element._originalLeft = left - parseFloat(element.style.left || 0);
  1706. element._originalTop = top - parseFloat(element.style.top || 0);
  1707. element._originalWidth = element.style.width;
  1708. element._originalHeight = element.style.height;
  1709. element.style.position = 'absolute';
  1710. element.style.top = top + 'px';
  1711. element.style.left = left + 'px';
  1712. element.style.width = width + 'px';
  1713. element.style.height = height + 'px';
  1714. return element;
  1715. },
  1716. relativize: function(element) {
  1717. element = $(element);
  1718. if (element.getStyle('position') == 'relative') return;
  1719. // Position.prepare(); // To be done manually by Scripty when it needs it.
  1720. element.style.position = 'relative';
  1721. var top = parseFloat(element.style.top || 0) - (element._originalTop || 0);
  1722. var left = parseFloat(element.style.left || 0) - (element._originalLeft || 0);
  1723. element.style.top = top + 'px';
  1724. element.style.left = left + 'px';
  1725. element.style.height = element._originalHeight;
  1726. element.style.width = element._originalWidth;
  1727. return element;
  1728. },
  1729. cumulativeScrollOffset: function(element) {
  1730. var valueT = 0, valueL = 0;
  1731. do {
  1732. valueT += element.scrollTop || 0;
  1733. valueL += element.scrollLeft || 0;
  1734. element = element.parentNode;
  1735. } while (element);
  1736. return Element._returnOffset(valueL, valueT);
  1737. },
  1738. getOffsetParent: function(element) {
  1739. if (element.offsetParent) return $(element.offsetParent);
  1740. if (element == document.body) return $(element);
  1741. while ((element = element.parentNode) && element != document.body)
  1742. if (Element.getStyle(element, 'position') != 'static')
  1743. return $(element);
  1744. return $(document.body);
  1745. },
  1746. viewportOffset: function(forElement) {
  1747. var valueT = 0, valueL = 0;
  1748. var element = forElement;
  1749. do {
  1750. valueT += element.offsetTop || 0;
  1751. valueL += element.offsetLeft || 0;
  1752. // Safari fix
  1753. if (element.offsetParent == document.body &&
  1754. Element.getStyle(element, 'position') == 'absolute') break;
  1755. } while (element = element.offsetParent);
  1756. element = forElement;
  1757. do {
  1758. if (!Prototype.Browser.Opera || element.tagName == 'BODY') {
  1759. valueT -= element.scrollTop || 0;
  1760. valueL -= element.scrollLeft || 0;
  1761. }
  1762. } while (element = element.parentNode);
  1763. return Element._returnOffset(valueL, valueT);
  1764. },
  1765. clonePosition: function(element, source) {
  1766. var options = Object.extend({
  1767. setLeft: true,
  1768. setTop: true,
  1769. setWidth: true,
  1770. setHeight: true,
  1771. offsetTop: 0,
  1772. offsetLeft: 0
  1773. }, arguments[2] || { });
  1774. // find page position of source
  1775. source = $(source);
  1776. var p = source.viewportOffset();
  1777. // find coordinate system to use
  1778. element = $(element);
  1779. var delta = [0, 0];
  1780. var parent = null;
  1781. // delta [0,0] will do fine with position: fixed elements,
  1782. // position:absolute needs offsetParent deltas
  1783. if (Element.getStyle(element, 'position') == 'absolute') {
  1784. parent = element.getOffsetParent();
  1785. delta = parent.viewportOffset();
  1786. }
  1787. // correct by body offsets (fixes Safari)
  1788. if (parent == document.body) {
  1789. delta[0] -= document.body.offsetLeft;
  1790. delta[1] -= document.body.offsetTop;
  1791. }
  1792. // set position
  1793. if (options.setLeft) element.style.left = (p[0] - delta[0] + options.offsetLeft) + 'px';
  1794. if (options.setTop) element.style.top = (p[1] - delta[1] + options.offsetTop) + 'px';
  1795. if (options.setWidth) element.style.width = source.offsetWidth + 'px';
  1796. if (options.setHeight) element.style.height = source.offsetHeight + 'px';
  1797. return element;
  1798. }
  1799. };
  1800. Element.Methods.identify.counter = 1;
  1801. Object.extend(Element.Methods, {
  1802. getElementsBySelector: Element.Methods.select,
  1803. childElements: Element.Methods.immediateDescendants
  1804. });
  1805. Element._attributeTranslations = {
  1806. write: {
  1807. names: {
  1808. className: 'class',
  1809. htmlFor: 'for'
  1810. },
  1811. values: { }
  1812. }
  1813. };
  1814. if (Prototype.Browser.Opera) {
  1815. Element.Methods.getStyle = Element.Methods.getStyle.wrap(
  1816. function(proceed, element, style) {
  1817. switch (style) {
  1818. case 'left': case 'top': case 'right': case 'bottom':
  1819. if (proceed(element, 'position') === 'static') return null;
  1820. case 'height': case 'width':
  1821. // returns '0px' for hidden elements; we want it to return null
  1822. if (!Element.visible(element)) return null;
  1823. // returns the border-box dimensions rather than the content-box
  1824. // dimensions, so we subtract padding and borders from the value
  1825. var dim = parseInt(proceed(element, style), 10);
  1826. if (dim !== element['offset' + style.capitalize()])
  1827. return dim + 'px';
  1828. var properties;
  1829. if (style === 'height') {
  1830. properties = ['border-top-width', 'padding-top',
  1831. 'padding-bottom', 'border-bottom-width'];
  1832. }
  1833. else {
  1834. properties = ['border-left-width', 'padding-left',
  1835. 'padding-right', 'border-right-width'];
  1836. }
  1837. return properties.inject(dim, function(memo, property) {
  1838. var val = proceed(element, property);
  1839. return val === null ? memo : memo - parseInt(val, 10);
  1840. }) + 'px';
  1841. default: return proceed(element, style);
  1842. }
  1843. }
  1844. );
  1845. Element.Methods.readAttribute = Element.Methods.readAttribute.wrap(
  1846. function(proceed, element, attribute) {
  1847. if (attribute === 'title') return element.title;
  1848. return proceed(element, attribute);
  1849. }
  1850. );
  1851. }
  1852. else if (Prototype.Browser.IE) {
  1853. // IE doesn't report offsets correctly for static elements, so we change them
  1854. // to "relative" to get the values, then change them back.
  1855. Element.Methods.getOffsetParent = Element.Methods.getOffsetParent.wrap(
  1856. function(proceed, element) {
  1857. element = $(element);
  1858. var position = element.getStyle('position');
  1859. if (position !== 'static') return proceed(element);
  1860. element.setStyle({ position: 'relative' });
  1861. var value = proceed(element);
  1862. element.setStyle({ position: position });
  1863. return value;
  1864. }
  1865. );
  1866. $w('positionedOffset viewportOffset').each(function(method) {
  1867. Element.Methods[method] = Element.Methods[method].wrap(
  1868. function(proceed, element) {
  1869. element = $(element);
  1870. var position = element.getStyle('position');
  1871. if (position !== 'static') return proceed(element);
  1872. // Trigger hasLayout on the offset parent so that IE6 reports
  1873. // accurate offsetTop and offsetLeft values for position: fixed.
  1874. var offsetParent = element.getOffsetParent();
  1875. if (offsetParent && offsetParent.getStyle('position') === 'fixed')
  1876. offsetParent.setStyle({ zoom: 1 });
  1877. element.setStyle({ position: 'relative' });
  1878. var value = proceed(element);
  1879. element.setStyle({ position: position });
  1880. return value;
  1881. }
  1882. );
  1883. });
  1884. Element.Methods.getStyle = function(element, style) {
  1885. element = $(element);
  1886. style = (style == 'float' || style == 'cssFloat') ? 'styleFloat' : style.camelize();
  1887. var value = element.style[style];
  1888. if (!value && element.currentStyle) value = element.currentStyle[style];
  1889. if (style == 'opacity') {
  1890. if (value = (element.getStyle('filter') || '').match(/alpha\(opacity=(.*)\)/))
  1891. if (value[1]) return parseFloat(value[1]) / 100;
  1892. return 1.0;
  1893. }
  1894. if (value == 'auto') {
  1895. if ((style == 'width' || style == 'height') && (element.getStyle('display') != 'none'))
  1896. return element['offset' + style.capitalize()] + 'px';
  1897. return null;
  1898. }
  1899. return value;
  1900. };
  1901. Element.Methods.setOpacity = function(element, value) {
  1902. function stripAlpha(filter){
  1903. return filter.replace(/alpha\([^\)]*\)/gi,'');
  1904. }
  1905. element = $(element);
  1906. var currentStyle = element.currentStyle;
  1907. if ((currentStyle && !currentStyle.hasLayout) ||
  1908. (!currentStyle && element.style.zoom == 'normal'))
  1909. element.style.zoom = 1;
  1910. var filter = element.getStyle('filter'), style = element.style;
  1911. if (value == 1 || value === '') {
  1912. (filter = stripAlpha(filter)) ?
  1913. style.filter = filter : style.removeAttribute('filter');
  1914. return element;
  1915. } else if (value < 0.00001) value = 0;
  1916. style.filter = stripAlpha(filter) +
  1917. 'alpha(opacity=' + (value * 100) + ')';
  1918. return element;
  1919. };
  1920. Element._attributeTranslations = {
  1921. read: {
  1922. names: {
  1923. 'class': 'className',
  1924. 'for': 'htmlFor'
  1925. },
  1926. values: {
  1927. _getAttr: function(element, attribute) {
  1928. return element.getAttribute(attribute, 2);
  1929. },
  1930. _getAttrNode: function(element, attribute) {
  1931. var node = element.getAttributeNode(attribute);
  1932. return node ? node.value : "";
  1933. },
  1934. _getEv: function(element, attribute) {
  1935. attribute = element.getAttribute(attribute);
  1936. return attribute ? attribute.toString().slice(23, -2) : null;
  1937. },
  1938. _flag: function(element, attribute) {
  1939. return $(element).hasAttribute(attribute) ? attribute : null;
  1940. },
  1941. style: function(element) {
  1942. return element.style.cssText.toLowerCase();
  1943. },
  1944. title: function(element) {
  1945. return element.title;
  1946. }
  1947. }
  1948. }
  1949. };
  1950. Element._attributeTranslations.write = {
  1951. names: Object.extend({
  1952. cellpadding: 'cellPadding',
  1953. cellspacing: 'cellSpacing'
  1954. }, Element._attributeTranslations.read.names),
  1955. values: {
  1956. checked: function(element, value) {
  1957. element.checked = !!value;
  1958. },
  1959. style: function(element, value) {
  1960. element.style.cssText = value ? value : '';
  1961. }
  1962. }
  1963. };
  1964. Element._attributeTranslations.has = {};
  1965. $w('colSpan rowSpan vAlign dateTime accessKey tabIndex ' +
  1966. 'encType maxLength readOnly longDesc').each(function(attr) {
  1967. Element._attributeTranslations.write.names[attr.toLowerCase()] = attr;
  1968. Element._attributeTranslations.has[attr.toLowerCase()] = attr;
  1969. });
  1970. (function(v) {
  1971. Object.extend(v, {
  1972. href: v._getAttr,
  1973. src: v._getAttr,
  1974. type: v._getAttr,
  1975. action: v._getAttrNode,
  1976. disabled: v._flag,
  1977. checked: v._flag,
  1978. readonly: v._flag,
  1979. multiple: v._flag,
  1980. onload: v._getEv,
  1981. onunload: v._getEv,
  1982. onclick: v._getEv,
  1983. ondblclick: v._getEv,
  1984. onmousedown: v._getEv,
  1985. onmouseup: v._getEv,
  1986. onmouseover: v._getEv,
  1987. onmousemove: v._getEv,
  1988. onmouseout: v._getEv,
  1989. onfocus: v._getEv,
  1990. onblur: v._getEv,
  1991. onkeypress: v._getEv,
  1992. onkeydown: v._getEv,
  1993. onkeyup: v._getEv,
  1994. onsubmit: v._getEv,
  1995. onreset: v._getEv,
  1996. onselect: v._getEv,
  1997. onchange: v._getEv
  1998. });
  1999. })(Element._attributeTranslations.read.values);
  2000. }
  2001. else if (Prototype.Browser.Gecko && /rv:1\.8\.0/.test(navigator.userAgent)) {
  2002. Element.Methods.setOpacity = function(element, value) {
  2003. element = $(element);
  2004. element.style.opacity = (value == 1) ? 0.999999 :
  2005. (value === '') ? '' : (value < 0.00001) ? 0 : value;
  2006. return element;
  2007. };
  2008. }
  2009. else if (Prototype.Browser.WebKit) {
  2010. Element.Methods.setOpacity = function(element, value) {
  2011. element = $(element);
  2012. element.style.opacity = (value == 1 || value === '') ? '' :
  2013. (value < 0.00001) ? 0 : value;
  2014. if (value == 1)
  2015. if(element.tagName == 'IMG' && element.width) {
  2016. element.width++; element.width--;
  2017. } else try {
  2018. var n = document.createTextNode(' ');
  2019. element.appendChild(n);
  2020. element.removeChild(n);
  2021. } catch (e) { }
  2022. return element;
  2023. };
  2024. // Safari returns margins on body which is incorrect if the child is absolutely
  2025. // positioned. For performance reasons, redefine Element#cumulativeOffset for
  2026. // KHTML/WebKit only.
  2027. Element.Methods.cumulativeOffset = function(element) {
  2028. var valueT = 0, valueL = 0;
  2029. do {
  2030. valueT += element.offsetTop || 0;
  2031. valueL += element.offsetLeft || 0;
  2032. if (element.offsetParent == document.body)
  2033. if (Element.getStyle(element, 'position') == 'absolute') break;
  2034. element = element.offsetParent;
  2035. } while (element);
  2036. return Element._returnOffset(valueL, valueT);
  2037. };
  2038. }
  2039. if (Prototype.Browser.IE || Prototype.Browser.Opera) {
  2040. // IE and Opera are missing .innerHTML support for TABLE-related and SELECT elements
  2041. Element.Methods.update = function(element, content) {
  2042. element = $(element);
  2043. if (content && content.toElement) content = content.toElement();
  2044. if (Object.isElement(content)) return element.update().insert(content);
  2045. content = Object.toHTML(content);
  2046. var tagName = element.tagName.toUpperCase();
  2047. if (tagName in Element._insertionTranslations.tags) {
  2048. $A(element.childNodes).each(function(node) { element.removeChild(node) });
  2049. Element._getContentFromAnonymousElement(tagName, content.stripScripts())
  2050. .each(function(node) { element.appendChild(node) });
  2051. }
  2052. else element.innerHTML = content.stripScripts();
  2053. content.evalScripts.bind(content).defer();
  2054. return element;
  2055. };
  2056. }
  2057. if ('outerHTML' in document.createElement('div')) {
  2058. Element.Methods.replace = function(element, content) {
  2059. element = $(element);
  2060. if (content && content.toElement) content = content.toElement();
  2061. if (Object.isElement(content)) {
  2062. element.parentNode.replaceChild(content, element);
  2063. return element;
  2064. }
  2065. content = Object.toHTML(content);
  2066. var parent = element.parentNode, tagName = parent.tagName.toUpperCase();
  2067. if (Element._insertionTranslations.tags[tagName]) {
  2068. var nextSibling = element.next();
  2069. var fragments = Element._getContentFromAnonymousElement(tagName, content.stripScripts());
  2070. parent.removeChild(element);
  2071. if (nextSibling)
  2072. fragments.each(function(node) { parent.insertBefore(node, nextSibling) });
  2073. else
  2074. fragments.each(function(node) { parent.appendChild(node) });
  2075. }
  2076. else element.outerHTML = content.stripScripts();
  2077. content.evalScripts.bind(content).defer();
  2078. return element;
  2079. };
  2080. }
  2081. Element._returnOffset = function(l, t) {
  2082. var result = [l, t];
  2083. result.left = l;
  2084. result.top = t;
  2085. return result;
  2086. };
  2087. Element._getContentFromAnonymousElement = function(tagName, html) {
  2088. var div = new Element('div'), t = Element._insertionTranslations.tags[tagName];
  2089. if (t) {
  2090. div.innerHTML = t[0] + html + t[1];
  2091. t[2].times(function() { div = div.firstChild });
  2092. } else div.innerHTML = html;
  2093. return $A(div.childNodes);
  2094. };
  2095. Element._insertionTranslations = {
  2096. before: function(element, node) {
  2097. element.parentNode.insertBefore(node, element);
  2098. },
  2099. top: function(element, node) {
  2100. element.insertBefore(node, element.firstChild);
  2101. },
  2102. bottom: function(element, node) {
  2103. element.appendChild(node);
  2104. },
  2105. after: function(element, node) {
  2106. element.parentNode.insertBefore(node, element.nextSibling);
  2107. },
  2108. tags: {
  2109. TABLE: ['<table>', '</table>', 1],
  2110. TBODY: ['<table><tbody>', '</tbody></table>', 2],
  2111. TR: ['<table><tbody><tr>', '</tr></tbody></table>', 3],
  2112. TD: ['<table><tbody><tr><td>', '</td></tr></tbody></table>', 4],
  2113. SELECT: ['<select>', '</select>', 1]
  2114. }
  2115. };
  2116. (function() {
  2117. Object.extend(this.tags, {
  2118. THEAD: this.tags.TBODY,
  2119. TFOOT: this.tags.TBODY,
  2120. TH: this.tags.TD
  2121. });
  2122. }).call(Element._insertionTranslations);
  2123. Element.Methods.Simulated = {
  2124. hasAttribute: function(element, attribute) {
  2125. attribute = Element._attributeTranslations.has[attribute] || attribute;
  2126. var node = $(element).getAttributeNode(attribute);
  2127. return node && node.specified;
  2128. }
  2129. };
  2130. Element.Methods.ByTag = { };
  2131. Object.extend(Element, Element.Methods);
  2132. if (!Prototype.BrowserFeatures.ElementExtensions &&
  2133. document.createElement('div').__proto__) {
  2134. window.HTMLElement = { };
  2135. window.HTMLElement.prototype = document.createElement('div').__proto__;
  2136. Prototype.BrowserFeatures.ElementExtensions = true;
  2137. }
  2138. Element.extend = (function() {
  2139. if (Prototype.BrowserFeatures.SpecificElementExtensions)
  2140. return Prototype.K;
  2141. var Methods = { }, ByTag = Element.Methods.ByTag;
  2142. var extend = Object.extend(function(element) {
  2143. if (!element || element._extendedByPrototype ||
  2144. element.nodeType != 1 || element == window) return element;
  2145. var methods = Object.clone(Methods),
  2146. tagName = element.tagName, property, value;
  2147. // extend methods for specific tags
  2148. if (ByTag[tagName]) Object.extend(methods, ByTag[tagName]);
  2149. for (property in methods) {
  2150. value = methods[property];
  2151. if (Object.isFunction(value) && !(property in element))
  2152. element[property] = value.methodize();
  2153. }
  2154. element._extendedByPrototype = Prototype.emptyFunction;
  2155. return element;
  2156. }, {
  2157. refresh: function() {
  2158. // extend methods for all tags (Safari doesn't need this)
  2159. if (!Prototype.BrowserFeatures.ElementExtensions) {
  2160. Object.extend(Methods, Element.Methods);
  2161. Object.extend(Methods, Element.Methods.Simulated);
  2162. }
  2163. }
  2164. });
  2165. extend.refresh();
  2166. return extend;
  2167. })();
  2168. Element.hasAttribute = function(element, attribute) {
  2169. if (element.hasAttribute) return element.hasAttribute(attribute);
  2170. return Element.Methods.Simulated.hasAttribute(element, attribute);
  2171. };
  2172. Element.addMethods = function(methods) {
  2173. var F = Prototype.BrowserFeatures, T = Element.Methods.ByTag;
  2174. if (!methods) {
  2175. Object.extend(Form, Form.Methods);
  2176. Object.extend(Form.Element, Form.Element.Methods);
  2177. Object.extend(Element.Methods.ByTag, {
  2178. "FORM": Object.clone(Form.Methods),
  2179. "INPUT": Object.clone(Form.Element.Methods),
  2180. "SELECT": Object.clone(Form.Element.Methods),
  2181. "TEXTAREA": Object.clone(Form.Element.Methods)
  2182. });
  2183. }
  2184. if (arguments.length == 2) {
  2185. var tagName = methods;
  2186. methods = arguments[1];
  2187. }
  2188. if (!tagName) Object.extend(Element.Methods, methods || { });
  2189. else {
  2190. if (Object.isArray(tagName)) tagName.each(extend);
  2191. else extend(tagName);
  2192. }
  2193. function extend(tagName) {
  2194. tagName = tagName.toUpperCase();
  2195. if (!Element.Methods.ByTag[tagName])
  2196. Element.Methods.ByTag[tagName] = { };
  2197. Object.extend(Element.Methods.ByTag[tagName], methods);
  2198. }
  2199. function copy(methods, destination, onlyIfAbsent) {
  2200. onlyIfAbsent = onlyIfAbsent || false;
  2201. for (var property in methods) {
  2202. var value = methods[property];
  2203. if (!Object.isFunction(value)) continue;
  2204. if (!onlyIfAbsent || !(property in destination))
  2205. destination[property] = value.methodize();
  2206. }
  2207. }
  2208. function findDOMClass(tagName) {
  2209. var klass;
  2210. var trans = {
  2211. "OPTGROUP": "OptGroup", "TEXTAREA": "TextArea", "P": "Paragraph",
  2212. "FIELDSET": "FieldSet", "UL": "UList", "OL": "OList", "DL": "DList",
  2213. "DIR": "Directory", "H1": "Heading", "H2": "Heading", "H3": "Heading",
  2214. "H4": "Heading", "H5": "Heading", "H6": "Heading", "Q": "Quote",
  2215. "INS": "Mod", "DEL": "Mod", "A": "Anchor", "IMG": "Image", "CAPTION":
  2216. "TableCaption", "COL": "TableCol", "COLGROUP": "TableCol", "THEAD":
  2217. "TableSection", "TFOOT": "TableSection", "TBODY": "TableSection", "TR":
  2218. "TableRow", "TH": "TableCell", "TD": "TableCell", "FRAMESET":
  2219. "FrameSet", "IFRAME": "IFrame"
  2220. };
  2221. if (trans[tagName]) klass = 'HTML' + trans[tagName] + 'Element';
  2222. if (window[klass]) return window[klass];
  2223. klass = 'HTML' + tagName + 'Element';
  2224. if (window[klass]) return window[klass];
  2225. klass = 'HTML' + tagName.capitalize() + 'Element';
  2226. if (window[klass]) return window[klass];
  2227. window[klass] = { };
  2228. window[klass].prototype = document.createElement(tagName).__proto__;
  2229. return window[klass];
  2230. }
  2231. if (F.ElementExtensions) {
  2232. copy(Element.Methods, HTMLElement.prototype);
  2233. copy(Element.Methods.Simulated, HTMLElement.prototype, true);
  2234. }
  2235. if (F.SpecificElementExtensions) {
  2236. for (var tag in Element.Methods.ByTag) {
  2237. var klass = findDOMClass(tag);
  2238. if (Object.isUndefined(klass)) continue;
  2239. copy(T[tag], klass.prototype);
  2240. }
  2241. }
  2242. Object.extend(Element, Element.Methods);
  2243. delete Element.ByTag;
  2244. if (Element.extend.refresh) Element.extend.refresh();
  2245. Element.cache = { };
  2246. };
  2247. document.viewport = {
  2248. getDimensions: function() {
  2249. var dimensions = { };
  2250. var B = Prototype.Browser;
  2251. $w('width height').each(function(d) {
  2252. var D = d.capitalize();
  2253. dimensions[d] = (B.WebKit && !document.evaluate) ? self['inner' + D] :
  2254. (B.Opera) ? document.body['client' + D] : document.documentElement['client' + D];
  2255. });
  2256. return dimensions;
  2257. },
  2258. getWidth: function() {
  2259. return this.getDimensions().width;
  2260. },
  2261. getHeight: function() {
  2262. return this.getDimensions().height;
  2263. },
  2264. getScrollOffsets: function() {
  2265. return Element._returnOffset(
  2266. window.pageXOffset || document.documentElement.scrollLeft || document.body.scrollLeft,
  2267. window.pageYOffset || document.documentElement.scrollTop || document.body.scrollTop);
  2268. }
  2269. };
  2270. /* Portions of the Selector class are derived from Jack Slocum’s DomQuery,
  2271. * part of YUI-Ext version 0.40, distributed under the terms of an MIT-style
  2272. * license. Please see http://www.yui-ext.com/ for more information. */
  2273. var Selector = Class.create({
  2274. initialize: function(expression) {
  2275. this.expression = expression.strip();
  2276. this.compileMatcher();
  2277. },
  2278. shouldUseXPath: function() {
  2279. if (!Prototype.BrowserFeatures.XPath) return false;
  2280. var e = this.expression;
  2281. // Safari 3 chokes on :*-of-type and :empty
  2282. if (Prototype.Browser.WebKit &&
  2283. (e.include("-of-type") || e.include(":empty")))
  2284. return false;
  2285. // XPath can't do namespaced attributes, nor can it read
  2286. // the "checked" property from DOM nodes
  2287. if ((/(\[[\w-]*?:|:checked)/).test(this.expression))
  2288. return false;
  2289. return true;
  2290. },
  2291. compileMatcher: function() {
  2292. if (this.shouldUseXPath())
  2293. return this.compileXPathMatcher();
  2294. var e = this.expression, ps = Selector.patterns, h = Selector.handlers,
  2295. c = Selector.criteria, le, p, m;
  2296. if (Selector._cache[e]) {
  2297. this.matcher = Selector._cache[e];
  2298. return;
  2299. }
  2300. this.matcher = ["this.matcher = function(root) {",
  2301. "var r = root, h = Selector.handlers, c = false, n;"];
  2302. while (e && le != e && (/\S/).test(e)) {
  2303. le = e;
  2304. for (var i in ps) {
  2305. p = ps[i];
  2306. if (m = e.match(p)) {
  2307. this.matcher.push(Object.isFunction(c[i]) ? c[i](m) :
  2308. new Template(c[i]).evaluate(m));
  2309. e = e.replace(m[0], '');
  2310. break;
  2311. }
  2312. }
  2313. }
  2314. this.matcher.push("return h.unique(n);\n}");
  2315. eval(this.matcher.join('\n'));
  2316. Selector._cache[this.expression] = this.matcher;
  2317. },
  2318. compileXPathMatcher: function() {
  2319. var e = this.expression, ps = Selector.patterns,
  2320. x = Selector.xpath, le, m;
  2321. if (Selector._cache[e]) {
  2322. this.xpath = Selector._cache[e]; return;
  2323. }
  2324. this.matcher = ['.//*'];
  2325. while (e && le != e && (/\S/).test(e)) {
  2326. le = e;
  2327. for (var i in ps) {
  2328. if (m = e.match(ps[i])) {
  2329. this.matcher.push(Object.isFunction(x[i]) ? x[i](m) :
  2330. new Template(x[i]).evaluate(m));
  2331. e = e.replace(m[0], '');
  2332. break;
  2333. }
  2334. }
  2335. }
  2336. this.xpath = this.matcher.join('');
  2337. Selector._cache[this.expression] = this.xpath;
  2338. },
  2339. findElements: function(root) {
  2340. root = root || document;
  2341. if (this.xpath) return document._getElementsByXPath(this.xpath, root);
  2342. return this.matcher(root);
  2343. },
  2344. match: function(element) {
  2345. this.tokens = [];
  2346. var e = this.expression, ps = Selector.patterns, as = Selector.assertions;
  2347. var le, p, m;
  2348. while (e && le !== e && (/\S/).test(e)) {
  2349. le = e;
  2350. for (var i in ps) {
  2351. p = ps[i];
  2352. if (m = e.match(p)) {
  2353. // use the Selector.assertions methods unless the selector
  2354. // is too complex.
  2355. if (as[i]) {
  2356. this.tokens.push([i, Object.clone(m)]);
  2357. e = e.replace(m[0], '');
  2358. } else {
  2359. // reluctantly do a document-wide search
  2360. // and look for a match in the array
  2361. return this.findElements(document).include(element);
  2362. }
  2363. }
  2364. }
  2365. }
  2366. var match = true, name, matches;
  2367. for (var i = 0, token; token = this.tokens[i]; i++) {
  2368. name = token[0], matches = token[1];
  2369. if (!Selector.assertions[name](element, matches)) {
  2370. match = false; break;
  2371. }
  2372. }
  2373. return match;
  2374. },
  2375. toString: function() {
  2376. return this.expression;
  2377. },
  2378. inspect: function() {
  2379. return "#<Selector:" + this.expression.inspect() + ">";
  2380. }
  2381. });
  2382. Object.extend(Selector, {
  2383. _cache: { },
  2384. xpath: {
  2385. descendant: "//*",
  2386. child: "/*",
  2387. adjacent: "/following-sibling::*[1]",
  2388. laterSibling: '/following-sibling::*',
  2389. tagName: function(m) {
  2390. if (m[1] == '*') return '';
  2391. return "[local-name()='" + m[1].toLowerCase() +
  2392. "' or local-name()='" + m[1].toUpperCase() + "']";
  2393. },
  2394. className: "[contains(concat(' ', @class, ' '), ' #{1} ')]",
  2395. id: "[@id='#{1}']",
  2396. attrPresence: function(m) {
  2397. m[1] = m[1].toLowerCase();
  2398. return new Template("[@#{1}]").evaluate(m);
  2399. },
  2400. attr: function(m) {
  2401. m[1] = m[1].toLowerCase();
  2402. m[3] = m[5] || m[6];
  2403. return new Template(Selector.xpath.operators[m[2]]).evaluate(m);
  2404. },
  2405. pseudo: function(m) {
  2406. var h = Selector.xpath.pseudos[m[1]];
  2407. if (!h) return '';
  2408. if (Object.isFunction(h)) return h(m);
  2409. return new Template(Selector.xpath.pseudos[m[1]]).evaluate(m);
  2410. },
  2411. operators: {
  2412. '=': "[@#{1}='#{3}']",
  2413. '!=': "[@#{1}!='#{3}']",
  2414. '^=': "[starts-with(@#{1}, '#{3}')]",
  2415. '$=': "[substring(@#{1}, (string-length(@#{1}) - string-length('#{3}') + 1))='#{3}']",
  2416. '*=': "[contains(@#{1}, '#{3}')]",
  2417. '~=': "[contains(concat(' ', @#{1}, ' '), ' #{3} ')]",
  2418. '|=': "[contains(concat('-', @#{1}, '-'), '-#{3}-')]"
  2419. },
  2420. pseudos: {
  2421. 'first-child': '[not(preceding-sibling::*)]',
  2422. 'last-child': '[not(following-sibling::*)]',
  2423. 'only-child': '[not(preceding-sibling::* or following-sibling::*)]',
  2424. 'empty': "[count(*) = 0 and (count(text()) = 0 or translate(text(), ' \t\r\n', '') = '')]",
  2425. 'checked': "[@checked]",
  2426. 'disabled': "[@disabled]",
  2427. 'enabled': "[not(@disabled)]",
  2428. 'not': function(m) {
  2429. var e = m[6], p = Selector.patterns,
  2430. x = Selector.xpath, le, v;
  2431. var exclusion = [];
  2432. while (e && le != e && (/\S/).test(e)) {
  2433. le = e;
  2434. for (var i in p) {
  2435. if (m = e.match(p[i])) {
  2436. v = Object.isFunction(x[i]) ? x[i](m) : new Template(x[i]).evaluate(m);
  2437. exclusion.push("(" + v.substring(1, v.length - 1) + ")");
  2438. e = e.replace(m[0], '');
  2439. break;
  2440. }
  2441. }
  2442. }
  2443. return "[not(" + exclusion.join(" and ") + ")]";
  2444. },
  2445. 'nth-child': function(m) {
  2446. return Selector.xpath.pseudos.nth("(count(./preceding-sibling::*) + 1) ", m);
  2447. },
  2448. 'nth-last-child': function(m) {
  2449. return Selector.xpath.pseudos.nth("(count(./following-sibling::*) + 1) ", m);
  2450. },
  2451. 'nth-of-type': function(m) {
  2452. return Selector.xpath.pseudos.nth("position() ", m);
  2453. },
  2454. 'nth-last-of-type': function(m) {
  2455. return Selector.xpath.pseudos.nth("(last() + 1 - position()) ", m);
  2456. },
  2457. 'first-of-type': function(m) {
  2458. m[6] = "1"; return Selector.xpath.pseudos['nth-of-type'](m);
  2459. },
  2460. 'last-of-type': function(m) {
  2461. m[6] = "1"; return Selector.xpath.pseudos['nth-last-of-type'](m);
  2462. },
  2463. 'only-of-type': function(m) {
  2464. var p = Selector.xpath.pseudos; return p['first-of-type'](m) + p['last-of-type'](m);
  2465. },
  2466. nth: function(fragment, m) {
  2467. var mm, formula = m[6], predicate;
  2468. if (formula == 'even') formula = '2n+0';
  2469. if (formula == 'odd') formula = '2n+1';
  2470. if (mm = formula.match(/^(\d+)$/)) // digit only
  2471. return '[' + fragment + "= " + mm[1] + ']';
  2472. if (mm = formula.match(/^(-?\d*)?n(([+-])(\d+))?/)) { // an+b
  2473. if (mm[1] == "-") mm[1] = -1;
  2474. var a = mm[1] ? Number(mm[1]) : 1;
  2475. var b = mm[2] ? Number(mm[2]) : 0;
  2476. predicate = "[((#{fragment} - #{b}) mod #{a} = 0) and " +
  2477. "((#{fragment} - #{b}) div #{a} >= 0)]";
  2478. return new Template(predicate).evaluate({
  2479. fragment: fragment, a: a, b: b });
  2480. }
  2481. }
  2482. }
  2483. },
  2484. criteria: {
  2485. tagName: 'n = h.tagName(n, r, "#{1}", c); c = false;',
  2486. className: 'n = h.className(n, r, "#{1}", c); c = false;',
  2487. id: 'n = h.id(n, r, "#{1}", c); c = false;',
  2488. attrPresence: 'n = h.attrPresence(n, r, "#{1}", c); c = false;',
  2489. attr: function(m) {
  2490. m[3] = (m[5] || m[6]);
  2491. return new Template('n = h.attr(n, r, "#{1}", "#{3}", "#{2}", c); c = false;').evaluate(m);
  2492. },
  2493. pseudo: function(m) {
  2494. if (m[6]) m[6] = m[6].replace(/"/g, '\\"');
  2495. return new Template('n = h.pseudo(n, "#{1}", "#{6}", r, c); c = false;').evaluate(m);
  2496. },
  2497. descendant: 'c = "descendant";',
  2498. child: 'c = "child";',
  2499. adjacent: 'c = "adjacent";',
  2500. laterSibling: 'c = "laterSibling";'
  2501. },
  2502. patterns: {
  2503. // combinators must be listed first
  2504. // (and descendant needs to be last combinator)
  2505. laterSibling: /^\s*~\s*/,
  2506. child: /^\s*>\s*/,
  2507. adjacent: /^\s*\+\s*/,
  2508. descendant: /^\s/,
  2509. // selectors follow
  2510. tagName: /^\s*(\*|[\w\-]+)(\b|$)?/,
  2511. id: /^#([\w\-\*]+)(\b|$)/,
  2512. className: /^\.([\w\-\*]+)(\b|$)/,
  2513. pseudo:
  2514. /^:((first|last|nth|nth-last|only)(-child|-of-type)|empty|checked|(en|dis)abled|not)(\((.*?)\))?(\b|$|(?=\s|[:+~>]))/,
  2515. attrPresence: /^\[([\w]+)\]/,
  2516. attr: /\[((?:[\w-]*:)?[\w-]+)\s*(?:([!^$*~|]?=)\s*((['"])([^\4]*?)\4|([^'"][^\]]*?)))?\]/
  2517. },
  2518. // for Selector.match and Element#match
  2519. assertions: {
  2520. tagName: function(element, matches) {
  2521. return matches[1].toUpperCase() == element.tagName.toUpperCase();
  2522. },
  2523. className: function(element, matches) {
  2524. return Element.hasClassName(element, matches[1]);
  2525. },
  2526. id: function(element, matches) {
  2527. return element.id === matches[1];
  2528. },
  2529. attrPresence: function(element, matches) {
  2530. return Element.hasAttribute(element, matches[1]);
  2531. },
  2532. attr: function(element, matches) {
  2533. var nodeValue = Element.readAttribute(element, matches[1]);
  2534. return nodeValue && Selector.operators[matches[2]](nodeValue, matches[5] || matches[6]);
  2535. }
  2536. },
  2537. handlers: {
  2538. // UTILITY FUNCTIONS
  2539. // joins two collections
  2540. concat: function(a, b) {
  2541. for (var i = 0, node; node = b[i]; i++)
  2542. a.push(node);
  2543. return a;
  2544. },
  2545. // marks an array of nodes for counting
  2546. mark: function(nodes) {
  2547. var _true = Prototype.emptyFunction;
  2548. for (var i = 0, node; node = nodes[i]; i++)
  2549. node._countedByPrototype = _true;
  2550. return nodes;
  2551. },
  2552. unmark: function(nodes) {
  2553. for (var i = 0, node; node = nodes[i]; i++)
  2554. node._countedByPrototype = undefined;
  2555. return nodes;
  2556. },
  2557. // mark each child node with its position (for nth calls)
  2558. // "ofType" flag indicates whether we're indexing for nth-of-type
  2559. // rather than nth-child
  2560. index: function(parentNode, reverse, ofType) {
  2561. parentNode._countedByPrototype = Prototype.emptyFunction;
  2562. if (reverse) {
  2563. for (var nodes = parentNode.childNodes, i = nodes.length - 1, j = 1; i >= 0; i--) {
  2564. var node = nodes[i];
  2565. if (node.nodeType == 1 && (!ofType || node._countedByPrototype)) node.nodeIndex = j++;
  2566. }
  2567. } else {
  2568. for (var i = 0, j = 1, nodes = parentNode.childNodes; node = nodes[i]; i++)
  2569. if (node.nodeType == 1 && (!ofType || node._countedByPrototype)) node.nodeIndex = j++;
  2570. }
  2571. },
  2572. // filters out duplicates and extends all nodes
  2573. unique: function(nodes) {
  2574. if (nodes.length == 0) return nodes;
  2575. var results = [], n;
  2576. for (var i = 0, l = nodes.length; i < l; i++)
  2577. if (!(n = nodes[i])._countedByPrototype) {
  2578. n._countedByPrototype = Prototype.emptyFunction;
  2579. results.push(Element.extend(n));
  2580. }
  2581. return Selector.handlers.unmark(results);
  2582. },
  2583. // COMBINATOR FUNCTIONS
  2584. descendant: function(nodes) {
  2585. var h = Selector.handlers;
  2586. for (var i = 0, results = [], node; node = nodes[i]; i++)
  2587. h.concat(results, node.getElementsByTagName('*'));
  2588. return results;
  2589. },
  2590. child: function(nodes) {
  2591. var h = Selector.handlers;
  2592. for (var i = 0, results = [], node; node = nodes[i]; i++) {
  2593. for (var j = 0, child; child = node.childNodes[j]; j++)
  2594. if (child.nodeType == 1 && child.tagName != '!') results.push(child);
  2595. }
  2596. return results;
  2597. },
  2598. adjacent: function(nodes) {
  2599. for (var i = 0, results = [], node; node = nodes[i]; i++) {
  2600. var next = this.nextElementSibling(node);
  2601. if (next) results.push(next);
  2602. }
  2603. return results;
  2604. },
  2605. laterSibling: function(nodes) {
  2606. var h = Selector.handlers;
  2607. for (var i = 0, results = [], node; node = nodes[i]; i++)
  2608. h.concat(results, Element.nextSiblings(node));
  2609. return results;
  2610. },
  2611. nextElementSibling: function(node) {
  2612. while (node = node.nextSibling)
  2613. if (node.nodeType == 1) return node;
  2614. return null;
  2615. },
  2616. previousElementSibling: function(node) {
  2617. while (node = node.previousSibling)
  2618. if (node.nodeType == 1) return node;
  2619. return null;
  2620. },
  2621. // TOKEN FUNCTIONS
  2622. tagName: function(nodes, root, tagName, combinator) {
  2623. var uTagName = tagName.toUpperCase();
  2624. var results = [], h = Selector.handlers;
  2625. if (nodes) {
  2626. if (combinator) {
  2627. // fastlane for ordinary descendant combinators
  2628. if (combinator == "descendant") {
  2629. for (var i = 0, node; node = nodes[i]; i++)
  2630. h.concat(results, node.getElementsByTagName(tagName));
  2631. return results;
  2632. } else nodes = this[combinator](nodes);
  2633. if (tagName == "*") return nodes;
  2634. }
  2635. for (var i = 0, node; node = nodes[i]; i++)
  2636. if (node.tagName.toUpperCase() === uTagName) results.push(node);
  2637. return results;
  2638. } else return root.getElementsByTagName(tagName);
  2639. },
  2640. id: function(nodes, root, id, combinator) {
  2641. var targetNode = $(id), h = Selector.handlers;
  2642. if (!targetNode) return [];
  2643. if (!nodes && root == document) return [targetNode];
  2644. if (nodes) {
  2645. if (combinator) {
  2646. if (combinator == 'child') {
  2647. for (var i = 0, node; node = nodes[i]; i++)
  2648. if (targetNode.parentNode == node) return [targetNode];
  2649. } else if (combinator == 'descendant') {
  2650. for (var i = 0, node; node = nodes[i]; i++)
  2651. if (Element.descendantOf(targetNode, node)) return [targetNode];
  2652. } else if (combinator == 'adjacent') {
  2653. for (var i = 0, node; node = nodes[i]; i++)
  2654. if (Selector.handlers.previousElementSibling(targetNode) == node)
  2655. return [targetNode];
  2656. } else nodes = h[combinator](nodes);
  2657. }
  2658. for (var i = 0, node; node = nodes[i]; i++)
  2659. if (node == targetNode) return [targetNode];
  2660. return [];
  2661. }
  2662. return (targetNode && Element.descendantOf(targetNode, root)) ? [targetNode] : [];
  2663. },
  2664. className: function(nodes, root, className, combinator) {
  2665. if (nodes && combinator) nodes = this[combinator](nodes);
  2666. return Selector.handlers.byClassName(nodes, root, className);
  2667. },
  2668. byClassName: function(nodes, root, className) {
  2669. if (!nodes) nodes = Selector.handlers.descendant([root]);
  2670. var needle = ' ' + className + ' ';
  2671. for (var i = 0, results = [], node, nodeClassName; node = nodes[i]; i++) {
  2672. nodeClassName = node.className;
  2673. if (nodeClassName.length == 0) continue;
  2674. if (nodeClassName == className || (' ' + nodeClassName + ' ').include(needle))
  2675. results.push(node);
  2676. }
  2677. return results;
  2678. },
  2679. attrPresence: function(nodes, root, attr, combinator) {
  2680. if (!nodes) nodes = root.getElementsByTagName("*");
  2681. if (nodes && combinator) nodes = this[combinator](nodes);
  2682. var results = [];
  2683. for (var i = 0, node; node = nodes[i]; i++)
  2684. if (Element.hasAttribute(node, attr)) results.push(node);
  2685. return results;
  2686. },
  2687. attr: function(nodes, root, attr, value, operator, combinator) {
  2688. if (!nodes) nodes = root.getElementsByTagName("*");
  2689. if (nodes && combinator) nodes = this[combinator](nodes);
  2690. var handler = Selector.operators[operator], results = [];
  2691. for (var i = 0, node; node = nodes[i]; i++) {
  2692. var nodeValue = Element.readAttribute(node, attr);
  2693. if (nodeValue === null) continue;
  2694. if (handler(nodeValue, value)) results.push(node);
  2695. }
  2696. return results;
  2697. },
  2698. pseudo: function(nodes, name, value, root, combinator) {
  2699. if (nodes && combinator) nodes = this[combinator](nodes);
  2700. if (!nodes) nodes = root.getElementsByTagName("*");
  2701. return Selector.pseudos[name](nodes, value, root);
  2702. }
  2703. },
  2704. pseudos: {
  2705. 'first-child': function(nodes, value, root) {
  2706. for (var i = 0, results = [], node; node = nodes[i]; i++) {
  2707. if (Selector.handlers.previousElementSibling(node)) continue;
  2708. results.push(node);
  2709. }
  2710. return results;
  2711. },
  2712. 'last-child': function(nodes, value, root) {
  2713. for (var i = 0, results = [], node; node = nodes[i]; i++) {
  2714. if (Selector.handlers.nextElementSibling(node)) continue;
  2715. results.push(node);
  2716. }
  2717. return results;
  2718. },
  2719. 'only-child': function(nodes, value, root) {
  2720. var h = Selector.handlers;
  2721. for (var i = 0, results = [], node; node = nodes[i]; i++)
  2722. if (!h.previousElementSibling(node) && !h.nextElementSibling(node))
  2723. results.push(node);
  2724. return results;
  2725. },
  2726. 'nth-child': function(nodes, formula, root) {
  2727. return Selector.pseudos.nth(nodes, formula, root);
  2728. },
  2729. 'nth-last-child': function(nodes, formula, root) {
  2730. return Selector.pseudos.nth(nodes, formula, root, true);
  2731. },
  2732. 'nth-of-type': function(nodes, formula, root) {
  2733. return Selector.pseudos.nth(nodes, formula, root, false, true);
  2734. },
  2735. 'nth-last-of-type': function(nodes, formula, root) {
  2736. return Selector.pseudos.nth(nodes, formula, root, true, true);
  2737. },
  2738. 'first-of-type': function(nodes, formula, root) {
  2739. return Selector.pseudos.nth(nodes, "1", root, false, true);
  2740. },
  2741. 'last-of-type': function(nodes, formula, root) {
  2742. return Selector.pseudos.nth(nodes, "1", root, true, true);
  2743. },
  2744. 'only-of-type': function(nodes, formula, root) {
  2745. var p = Selector.pseudos;
  2746. return p['last-of-type'](p['first-of-type'](nodes, formula, root), formula, root);
  2747. },
  2748. // handles the an+b logic
  2749. getIndices: function(a, b, total) {
  2750. if (a == 0) return b > 0 ? [b] : [];
  2751. return $R(1, total).inject([], function(memo, i) {
  2752. if (0 == (i - b) % a && (i - b) / a >= 0) memo.push(i);
  2753. return memo;
  2754. });
  2755. },
  2756. // handles nth(-last)-child, nth(-last)-of-type, and (first|last)-of-type
  2757. nth: function(nodes, formula, root, reverse, ofType) {
  2758. if (nodes.length == 0) return [];
  2759. if (formula == 'even') formula = '2n+0';
  2760. if (formula == 'odd') formula = '2n+1';
  2761. var h = Selector.handlers, results = [], indexed = [], m;
  2762. h.mark(nodes);
  2763. for (var i = 0, node; node = nodes[i]; i++) {
  2764. if (!node.parentNode._countedByPrototype) {
  2765. h.index(node.parentNode, reverse, ofType);
  2766. indexed.push(node.parentNode);
  2767. }
  2768. }
  2769. if (formula.match(/^\d+$/)) { // just a number
  2770. formula = Number(formula);
  2771. for (var i = 0, node; node = nodes[i]; i++)
  2772. if (node.nodeIndex == formula) results.push(node);
  2773. } else if (m = formula.match(/^(-?\d*)?n(([+-])(\d+))?/)) { // an+b
  2774. if (m[1] == "-") m[1] = -1;
  2775. var a = m[1] ? Number(m[1]) : 1;
  2776. var b = m[2] ? Number(m[2]) : 0;
  2777. var indices = Selector.pseudos.getIndices(a, b, nodes.length);
  2778. for (var i = 0, node, l = indices.length; node = nodes[i]; i++) {
  2779. for (var j = 0; j < l; j++)
  2780. if (node.nodeIndex == indices[j]) results.push(node);
  2781. }
  2782. }
  2783. h.unmark(nodes);
  2784. h.unmark(indexed);
  2785. return results;
  2786. },
  2787. 'empty': function(nodes, value, root) {
  2788. for (var i = 0, results = [], node; node = nodes[i]; i++) {
  2789. // IE treats comments as element nodes
  2790. if (node.tagName == '!' || (node.firstChild && !node.innerHTML.match(/^\s*$/))) continue;
  2791. results.push(node);
  2792. }
  2793. return results;
  2794. },
  2795. 'not': function(nodes, selector, root) {
  2796. var h = Selector.handlers, selectorType, m;
  2797. var exclusions = new Selector(selector).findElements(root);
  2798. h.mark(exclusions);
  2799. for (var i = 0, results = [], node; node = nodes[i]; i++)
  2800. if (!node._countedByPrototype) results.push(node);
  2801. h.unmark(exclusions);
  2802. return results;
  2803. },
  2804. 'enabled': function(nodes, value, root) {
  2805. for (var i = 0, results = [], node; node = nodes[i]; i++)
  2806. if (!node.disabled) results.push(node);
  2807. return results;
  2808. },
  2809. 'disabled': function(nodes, value, root) {
  2810. for (var i = 0, results = [], node; node = nodes[i]; i++)
  2811. if (node.disabled) results.push(node);
  2812. return results;
  2813. },
  2814. 'checked': function(nodes, value, root) {
  2815. for (var i = 0, results = [], node; node = nodes[i]; i++)
  2816. if (node.checked) results.push(node);
  2817. return results;
  2818. }
  2819. },
  2820. operators: {
  2821. '=': function(nv, v) { return nv == v; },
  2822. '!=': function(nv, v) { return nv != v; },
  2823. '^=': function(nv, v) { return nv.startsWith(v); },
  2824. '$=': function(nv, v) { return nv.endsWith(v); },
  2825. '*=': function(nv, v) { return nv.include(v); },
  2826. '~=': function(nv, v) { return (' ' + nv + ' ').include(' ' + v + ' '); },
  2827. '|=': function(nv, v) { return ('-' + nv.toUpperCase() + '-').include('-' + v.toUpperCase() + '-'); }
  2828. },
  2829. split: function(expression) {
  2830. var expressions = [];
  2831. expression.scan(/(([\w#:.~>+()\s-]+|\*|\[.*?\])+)\s*(,|$)/, function(m) {
  2832. expressions.push(m[1].strip());
  2833. });
  2834. return expressions;
  2835. },
  2836. matchElements: function(elements, expression) {
  2837. var matches = $$(expression), h = Selector.handlers;
  2838. h.mark(matches);
  2839. for (var i = 0, results = [], element; element = elements[i]; i++)
  2840. if (element._countedByPrototype) results.push(element);
  2841. h.unmark(matches);
  2842. return results;
  2843. },
  2844. findElement: function(elements, expression, index) {
  2845. if (Object.isNumber(expression)) {
  2846. index = expression; expression = false;
  2847. }
  2848. return Selector.matchElements(elements, expression || '*')[index || 0];
  2849. },
  2850. findChildElements: function(element, expressions) {
  2851. expressions = Selector.split(expressions.join(','));
  2852. var results = [], h = Selector.handlers;
  2853. for (var i = 0, l = expressions.length, selector; i < l; i++) {
  2854. selector = new Selector(expressions[i].strip());
  2855. h.concat(results, selector.findElements(element));
  2856. }
  2857. return (l > 1) ? h.unique(results) : results;
  2858. }
  2859. });
  2860. if (Prototype.Browser.IE) {
  2861. Object.extend(Selector.handlers, {
  2862. // IE returns comment nodes on getElementsByTagName("*").
  2863. // Filter them out.
  2864. concat: function(a, b) {
  2865. for (var i = 0, node; node = b[i]; i++)
  2866. if (node.tagName !== "!") a.push(node);
  2867. return a;
  2868. },
  2869. // IE improperly serializes _countedByPrototype in (inner|outer)HTML.
  2870. unmark: function(nodes) {
  2871. for (var i = 0, node; node = nodes[i]; i++)
  2872. node.removeAttribute('_countedByPrototype');
  2873. return nodes;
  2874. }
  2875. });
  2876. }
  2877. function $$() {
  2878. return Selector.findChildElements(document, $A(arguments));
  2879. }
  2880. var Form = {
  2881. reset: function(form) {
  2882. $(form).reset();
  2883. return form;
  2884. },
  2885. serializeElements: function(elements, options) {
  2886. if (typeof options != 'object') options = { hash: !!options };
  2887. else if (Object.isUndefined(options.hash)) options.hash = true;
  2888. var key, value, submitted = false, submit = options.submit;
  2889. var data = elements.inject({ }, function(result, element) {
  2890. if (!element.disabled && element.name) {
  2891. key = element.name; value = $(element).getValue();
  2892. if (value != null && (element.type != 'submit' || (!submitted &&
  2893. submit !== false && (!submit || key == submit) && (submitted = true)))) {
  2894. if (key in result) {
  2895. // a key is already present; construct an array of values
  2896. if (!Object.isArray(result[key])) result[key] = [result[key]];
  2897. result[key].push(value);
  2898. }
  2899. else result[key] = value;
  2900. }
  2901. }
  2902. return result;
  2903. });
  2904. return options.hash ? data : Object.toQueryString(data);
  2905. }
  2906. };
  2907. Form.Methods = {
  2908. serialize: function(form, options) {
  2909. return Form.serializeElements(Form.getElements(form), options);
  2910. },
  2911. getElements: function(form) {
  2912. return $A($(form).getElementsByTagName('*')).inject([],
  2913. function(elements, child) {
  2914. if (Form.Element.Serializers[child.tagName.toLowerCase()])
  2915. elements.push(Element.extend(child));
  2916. return elements;
  2917. }
  2918. );
  2919. },
  2920. getInputs: function(form, typeName, name) {
  2921. form = $(form);
  2922. var inputs = form.getElementsByTagName('input');
  2923. if (!typeName && !name) return $A(inputs).map(Element.extend);
  2924. for (var i = 0, matchingInputs = [], length = inputs.length; i < length; i++) {
  2925. var input = inputs[i];
  2926. if ((typeName && input.type != typeName) || (name && input.name != name))
  2927. continue;
  2928. matchingInputs.push(Element.extend(input));
  2929. }
  2930. return matchingInputs;
  2931. },
  2932. disable: function(form) {
  2933. form = $(form);
  2934. Form.getElements(form).invoke('disable');
  2935. return form;
  2936. },
  2937. enable: function(form) {
  2938. form = $(form);
  2939. Form.getElements(form).invoke('enable');
  2940. return form;
  2941. },
  2942. findFirstElement: function(form) {
  2943. var elements = $(form).getElements().findAll(function(element) {
  2944. return 'hidden' != element.type && !element.disabled;
  2945. });
  2946. var firstByIndex = elements.findAll(function(element) {
  2947. return element.hasAttribute('tabIndex') && element.tabIndex >= 0;
  2948. }).sortBy(function(element) { return element.tabIndex }).first();
  2949. return firstByIndex ? firstByIndex : elements.find(function(element) {
  2950. return ['input', 'select', 'textarea'].include(element.tagName.toLowerCase());
  2951. });
  2952. },
  2953. focusFirstElement: function(form) {
  2954. form = $(form);
  2955. form.findFirstElement().activate();
  2956. return form;
  2957. },
  2958. request: function(form, options) {
  2959. form = $(form), options = Object.clone(options || { });
  2960. var params = options.parameters, action = form.readAttribute('action') || '';
  2961. if (action.blank()) action = window.location.href;
  2962. options.parameters = form.serialize(true);
  2963. if (params) {
  2964. if (Object.isString(params)) params = params.toQueryParams();
  2965. Object.extend(options.parameters, params);
  2966. }
  2967. if (form.hasAttribute('method') && !options.method)
  2968. options.method = form.method;
  2969. return new Ajax.Request(action, options);
  2970. }
  2971. };
  2972. /*--------------------------------------------------------------------------*/
  2973. Form.Element = {
  2974. focus: function(element) {
  2975. $(element).focus();
  2976. return element;
  2977. },
  2978. select: function(element) {
  2979. $(element).select();
  2980. return element;
  2981. }
  2982. };
  2983. Form.Element.Methods = {
  2984. serialize: function(element) {
  2985. element = $(element);
  2986. if (!element.disabled && element.name) {
  2987. var value = element.getValue();
  2988. if (value != undefined) {
  2989. var pair = { };
  2990. pair[element.name] = value;
  2991. return Object.toQueryString(pair);
  2992. }
  2993. }
  2994. return '';
  2995. },
  2996. getValue: function(element) {
  2997. element = $(element);
  2998. var method = element.tagName.toLowerCase();
  2999. return Form.Element.Serializers[method](element);
  3000. },
  3001. setValue: function(element, value) {
  3002. element = $(element);
  3003. var method = element.tagName.toLowerCase();
  3004. Form.Element.Serializers[method](element, value);
  3005. return element;
  3006. },
  3007. clear: function(element) {
  3008. $(element).value = '';
  3009. return element;
  3010. },
  3011. present: function(element) {
  3012. return $(element).value != '';
  3013. },
  3014. activate: function(element) {
  3015. element = $(element);
  3016. try {
  3017. element.focus();
  3018. if (element.select && (element.tagName.toLowerCase() != 'input' ||
  3019. !['button', 'reset', 'submit'].include(element.type)))
  3020. element.select();
  3021. } catch (e) { }
  3022. return element;
  3023. },
  3024. disable: function(element) {
  3025. element = $(element);
  3026. element.blur();
  3027. element.disabled = true;
  3028. return element;
  3029. },
  3030. enable: function(element) {
  3031. element = $(element);
  3032. element.disabled = false;
  3033. return element;
  3034. }
  3035. };
  3036. /*--------------------------------------------------------------------------*/
  3037. var Field = Form.Element;
  3038. var $F = Form.Element.Methods.getValue;
  3039. /*--------------------------------------------------------------------------*/
  3040. Form.Element.Serializers = {
  3041. input: function(element, value) {
  3042. switch (element.type.toLowerCase()) {
  3043. case 'checkbox':
  3044. case 'radio':
  3045. return Form.Element.Serializers.inputSelector(element, value);
  3046. default:
  3047. return Form.Element.Serializers.textarea(element, value);
  3048. }
  3049. },
  3050. inputSelector: function(element, value) {
  3051. if (Object.isUndefined(value)) return element.checked ? element.value : null;
  3052. else element.checked = !!value;
  3053. },
  3054. textarea: function(element, value) {
  3055. if (Object.isUndefined(value)) return element.value;
  3056. else element.value = value;
  3057. },
  3058. select: function(element, index) {
  3059. if (Object.isUndefined(index))
  3060. return this[element.type == 'select-one' ?
  3061. 'selectOne' : 'selectMany'](element);
  3062. else {
  3063. var opt, value, single = !Object.isArray(index);
  3064. for (var i = 0, length = element.length; i < length; i++) {
  3065. opt = element.options[i];
  3066. value = this.optionValue(opt);
  3067. if (single) {
  3068. if (value == index) {
  3069. opt.selected = true;
  3070. return;
  3071. }
  3072. }
  3073. else opt.selected = index.include(value);
  3074. }
  3075. }
  3076. },
  3077. selectOne: function(element) {
  3078. var index = element.selectedIndex;
  3079. return index >= 0 ? this.optionValue(element.options[index]) : null;
  3080. },
  3081. selectMany: function(element) {
  3082. var values, length = element.length;
  3083. if (!length) return null;
  3084. for (var i = 0, values = []; i < length; i++) {
  3085. var opt = element.options[i];
  3086. if (opt.selected) values.push(this.optionValue(opt));
  3087. }
  3088. return values;
  3089. },
  3090. optionValue: function(opt) {
  3091. // extend element because hasAttribute may not be native
  3092. return Element.extend(opt).hasAttribute('value') ? opt.value : opt.text;
  3093. }
  3094. };
  3095. /*--------------------------------------------------------------------------*/
  3096. Abstract.TimedObserver = Class.create(PeriodicalExecuter, {
  3097. initialize: function($super, element, frequency, callback) {
  3098. $super(callback, frequency);
  3099. this.element = $(element);
  3100. this.lastValue = this.getValue();
  3101. },
  3102. execute: function() {
  3103. var value = this.getValue();
  3104. if (Object.isString(this.lastValue) && Object.isString(value) ?
  3105. this.lastValue != value : String(this.lastValue) != String(value)) {
  3106. this.callback(this.element, value);
  3107. this.lastValue = value;
  3108. }
  3109. }
  3110. });
  3111. Form.Element.Observer = Class.create(Abstract.TimedObserver, {
  3112. getValue: function() {
  3113. return Form.Element.getValue(this.element);
  3114. }
  3115. });
  3116. Form.Observer = Class.create(Abstract.TimedObserver, {
  3117. getValue: function() {
  3118. return Form.serialize(this.element);
  3119. }
  3120. });
  3121. /*--------------------------------------------------------------------------*/
  3122. Abstract.EventObserver = Class.create({
  3123. initialize: function(element, callback) {
  3124. this.element = $(element);
  3125. this.callback = callback;
  3126. this.lastValue = this.getValue();
  3127. if (this.element.tagName.toLowerCase() == 'form')
  3128. this.registerFormCallbacks();
  3129. else
  3130. this.registerCallback(this.element);
  3131. },
  3132. onElementEvent: function() {
  3133. var value = this.getValue();
  3134. if (this.lastValue != value) {
  3135. this.callback(this.element, value);
  3136. this.lastValue = value;
  3137. }
  3138. },
  3139. registerFormCallbacks: function() {
  3140. Form.getElements(this.element).each(this.registerCallback, this);
  3141. },
  3142. registerCallback: function(element) {
  3143. if (element.type) {
  3144. switch (element.type.toLowerCase()) {
  3145. case 'checkbox':
  3146. case 'radio':
  3147. Event.observe(element, 'click', this.onElementEvent.bind(this));
  3148. break;
  3149. default:
  3150. Event.observe(element, 'change', this.onElementEvent.bind(this));
  3151. break;
  3152. }
  3153. }
  3154. }
  3155. });
  3156. Form.Element.EventObserver = Class.create(Abstract.EventObserver, {
  3157. getValue: function() {
  3158. return Form.Element.getValue(this.element);
  3159. }
  3160. });
  3161. Form.EventObserver = Class.create(Abstract.EventObserver, {
  3162. getValue: function() {
  3163. return Form.serialize(this.element);
  3164. }
  3165. });
  3166. if (!window.Event) var Event = { };
  3167. Object.extend(Event, {
  3168. KEY_BACKSPACE: 8,
  3169. KEY_TAB: 9,
  3170. KEY_RETURN: 13,
  3171. KEY_ESC: 27,
  3172. KEY_LEFT: 37,
  3173. KEY_UP: 38,
  3174. KEY_RIGHT: 39,
  3175. KEY_DOWN: 40,
  3176. KEY_DELETE: 46,
  3177. KEY_HOME: 36,
  3178. KEY_END: 35,
  3179. KEY_PAGEUP: 33,
  3180. KEY_PAGEDOWN: 34,
  3181. KEY_INSERT: 45,
  3182. cache: { },
  3183. relatedTarget: function(event) {
  3184. var element;
  3185. switch(event.type) {
  3186. case 'mouseover': element = event.fromElement; break;
  3187. case 'mouseout': element = event.toElement; break;
  3188. default: return null;
  3189. }
  3190. return Element.extend(element);
  3191. }
  3192. });
  3193. Event.Methods = (function() {
  3194. var isButton;
  3195. if (Prototype.Browser.IE) {
  3196. var buttonMap = { 0: 1, 1: 4, 2: 2 };
  3197. isButton = function(event, code) {
  3198. return event.button == buttonMap[code];
  3199. };
  3200. } else if (Prototype.Browser.WebKit) {
  3201. isButton = function(event, code) {
  3202. switch (code) {
  3203. case 0: return event.which == 1 && !event.metaKey;
  3204. case 1: return event.which == 1 && event.metaKey;
  3205. default: return false;
  3206. }
  3207. };
  3208. } else {
  3209. isButton = function(event, code) {
  3210. return event.which ? (event.which === code + 1) : (event.button === code);
  3211. };
  3212. }
  3213. return {
  3214. isLeftClick: function(event) { return isButton(event, 0) },
  3215. isMiddleClick: function(event) { return isButton(event, 1) },
  3216. isRightClick: function(event) { return isButton(event, 2) },
  3217. element: function(event) {
  3218. var node = Event.extend(event).target;
  3219. return Element.extend(node.nodeType == Node.TEXT_NODE ? node.parentNode : node);
  3220. },
  3221. findElement: function(event, expression) {
  3222. var element = Event.element(event);
  3223. if (!expression) return element;
  3224. var elements = [element].concat(element.ancestors());
  3225. return Selector.findElement(elements, expression, 0);
  3226. },
  3227. pointer: function(event) {
  3228. return {
  3229. x: event.pageX || (event.clientX +
  3230. (document.documentElement.scrollLeft || document.body.scrollLeft)),
  3231. y: event.pageY || (event.clientY +
  3232. (document.documentElement.scrollTop || document.body.scrollTop))
  3233. };
  3234. },
  3235. pointerX: function(event) { return Event.pointer(event).x },
  3236. pointerY: function(event) { return Event.pointer(event).y },
  3237. stop: function(event) {
  3238. Event.extend(event);
  3239. event.preventDefault();
  3240. event.stopPropagation();
  3241. event.stopped = true;
  3242. }
  3243. };
  3244. })();
  3245. Event.extend = (function() {
  3246. var methods = Object.keys(Event.Methods).inject({ }, function(m, name) {
  3247. m[name] = Event.Methods[name].methodize();
  3248. return m;
  3249. });
  3250. if (Prototype.Browser.IE) {
  3251. Object.extend(methods, {
  3252. stopPropagation: function() { this.cancelBubble = true },
  3253. preventDefault: function() { this.returnValue = false },
  3254. inspect: function() { return "[object Event]" }
  3255. });
  3256. return function(event) {
  3257. if (!event) return false;
  3258. if (event._extendedByPrototype) return event;
  3259. event._extendedByPrototype = Prototype.emptyFunction;
  3260. var pointer = Event.pointer(event);
  3261. Object.extend(event, {
  3262. target: event.srcElement,
  3263. relatedTarget: Event.relatedTarget(event),
  3264. pageX: pointer.x,
  3265. pageY: pointer.y
  3266. });
  3267. return Object.extend(event, methods);
  3268. };
  3269. } else {
  3270. Event.prototype = Event.prototype || document.createEvent("HTMLEvents").__proto__;
  3271. Object.extend(Event.prototype, methods);
  3272. return Prototype.K;
  3273. }
  3274. })();
  3275. Object.extend(Event, (function() {
  3276. var cache = Event.cache;
  3277. function getEventID(element) {
  3278. if (element._prototypeEventID) return element._prototypeEventID[0];
  3279. arguments.callee.id = arguments.callee.id || 1;
  3280. return element._prototypeEventID = [++arguments.callee.id];
  3281. }
  3282. function getDOMEventName(eventName) {
  3283. if (eventName && eventName.include(':')) return "dataavailable";
  3284. return eventName;
  3285. }
  3286. function getCacheForID(id) {
  3287. return cache[id] = cache[id] || { };
  3288. }
  3289. function getWrappersForEventName(id, eventName) {
  3290. var c = getCacheForID(id);
  3291. return c[eventName] = c[eventName] || [];
  3292. }
  3293. function createWrapper(element, eventName, handler) {
  3294. var id = getEventID(element);
  3295. var c = getWrappersForEventName(id, eventName);
  3296. if (c.pluck("handler").include(handler)) return false;
  3297. var wrapper = function(event) {
  3298. if (!Event || !Event.extend ||
  3299. (event.eventName && event.eventName != eventName))
  3300. return false;
  3301. Event.extend(event);
  3302. handler.call(element, event);
  3303. };
  3304. wrapper.handler = handler;
  3305. c.push(wrapper);
  3306. return wrapper;
  3307. }
  3308. function findWrapper(id, eventName, handler) {
  3309. var c = getWrappersForEventName(id, eventName);
  3310. return c.find(function(wrapper) { return wrapper.handler == handler });
  3311. }
  3312. function destroyWrapper(id, eventName, handler) {
  3313. var c = getCacheForID(id);
  3314. if (!c[eventName]) return false;
  3315. c[eventName] = c[eventName].without(findWrapper(id, eventName, handler));
  3316. }
  3317. function destroyCache() {
  3318. for (var id in cache)
  3319. for (var eventName in cache[id])
  3320. cache[id][eventName] = null;
  3321. }
  3322. if (window.attachEvent) {
  3323. window.attachEvent("onunload", destroyCache);
  3324. }
  3325. return {
  3326. observe: function(element, eventName, handler) {
  3327. element = $(element);
  3328. var name = getDOMEventName(eventName);
  3329. var wrapper = createWrapper(element, eventName, handler);
  3330. if (!wrapper) return element;
  3331. if (element.addEventListener) {
  3332. element.addEventListener(name, wrapper, false);
  3333. } else {
  3334. element.attachEvent("on" + name, wrapper);
  3335. }
  3336. return element;
  3337. },
  3338. stopObserving: function(element, eventName, handler) {
  3339. element = $(element);
  3340. var id = getEventID(element), name = getDOMEventName(eventName);
  3341. if (!handler && eventName) {
  3342. getWrappersForEventName(id, eventName).each(function(wrapper) {
  3343. element.stopObserving(eventName, wrapper.handler);
  3344. });
  3345. return element;
  3346. } else if (!eventName) {
  3347. Object.keys(getCacheForID(id)).each(function(eventName) {
  3348. element.stopObserving(eventName);
  3349. });
  3350. return element;
  3351. }
  3352. var wrapper = findWrapper(id, eventName, handler);
  3353. if (!wrapper) return element;
  3354. if (element.removeEventListener) {
  3355. element.removeEventListener(name, wrapper, false);
  3356. } else {
  3357. element.detachEvent("on" + name, wrapper);
  3358. }
  3359. destroyWrapper(id, eventName, handler);
  3360. return element;
  3361. },
  3362. fire: function(element, eventName, memo) {
  3363. element = $(element);
  3364. if (element == document && document.createEvent && !element.dispatchEvent)
  3365. element = document.documentElement;
  3366. var event;
  3367. if (document.createEvent) {
  3368. event = document.createEvent("HTMLEvents");
  3369. event.initEvent("dataavailable", true, true);
  3370. } else {
  3371. event = document.createEventObject();
  3372. event.eventType = "ondataavailable";
  3373. }
  3374. event.eventName = eventName;
  3375. event.memo = memo || { };
  3376. if (document.createEvent) {
  3377. element.dispatchEvent(event);
  3378. } else {
  3379. element.fireEvent(event.eventType, event);
  3380. }
  3381. return Event.extend(event);
  3382. }
  3383. };
  3384. })());
  3385. Object.extend(Event, Event.Methods);
  3386. Element.addMethods({
  3387. fire: Event.fire,
  3388. observe: Event.observe,
  3389. stopObserving: Event.stopObserving
  3390. });
  3391. Object.extend(document, {
  3392. fire: Element.Methods.fire.methodize(),
  3393. observe: Element.Methods.observe.methodize(),
  3394. stopObserving: Element.Methods.stopObserving.methodize(),
  3395. loaded: false
  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;
  3401. function fireContentLoadedEvent() {
  3402. if (document.loaded) return;
  3403. if (timer) window.clearInterval(timer);
  3404. document.fire("dom:loaded");
  3405. document.loaded = 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();// script.aculo.us effects.js v1.8.2, Tue Nov 18 18:30:58 +0100 2008
  3575. // Copyright (c) 2005-2008 Thomas Fuchs (http://script.aculo.us, http://mir.aculo.us)
  3576. // Contributors:
  3577. // Justin Palmer (http://encytemedia.com/)
  3578. // Mark Pilgrim (http://diveintomark.org/)
  3579. // Martin Bialasinki
  3580. //
  3581. // script.aculo.us is freely distributable under the terms of an MIT-style license.
  3582. // For details, see the script.aculo.us web site: http://script.aculo.us/
  3583. // converts rgb() and #xxx to #xxxxxx format,
  3584. // returns self (or first argument) if not convertable
  3585. String.prototype.parseColor = function() {
  3586. var color = '#';
  3587. if (this.slice(0,4) == 'rgb(') {
  3588. var cols = this.slice(4,this.length-1).split(',');
  3589. var i=0; do { color += parseInt(cols[i]).toColorPart() } while (++i<3);
  3590. } else {
  3591. if (this.slice(0,1) == '#') {
  3592. if (this.length==4) for(var i=1;i<4;i++) color += (this.charAt(i) + this.charAt(i)).toLowerCase();
  3593. if (this.length==7) color = this.toLowerCase();
  3594. }
  3595. }
  3596. return (color.length==7 ? color : (arguments[0] || this));
  3597. };
  3598. /*--------------------------------------------------------------------------*/
  3599. Element.collectTextNodes = function(element) {
  3600. return $A($(element).childNodes).collect( function(node) {
  3601. return (node.nodeType==3 ? node.nodeValue :
  3602. (node.hasChildNodes() ? Element.collectTextNodes(node) : ''));
  3603. }).flatten().join('');
  3604. };
  3605. Element.collectTextNodesIgnoreClass = function(element, className) {
  3606. return $A($(element).childNodes).collect( function(node) {
  3607. return (node.nodeType==3 ? node.nodeValue :
  3608. ((node.hasChildNodes() && !Element.hasClassName(node,className)) ?
  3609. Element.collectTextNodesIgnoreClass(node, className) : ''));
  3610. }).flatten().join('');
  3611. };
  3612. Element.setContentZoom = function(element, percent) {
  3613. element = $(element);
  3614. element.setStyle({fontSize: (percent/100) + 'em'});
  3615. if (Prototype.Browser.WebKit) window.scrollBy(0,0);
  3616. return element;
  3617. };
  3618. Element.getInlineOpacity = function(element){
  3619. return $(element).style.opacity || '';
  3620. };
  3621. Element.forceRerendering = function(element) {
  3622. try {
  3623. element = $(element);
  3624. var n = document.createTextNode(' ');
  3625. element.appendChild(n);
  3626. element.removeChild(n);
  3627. } catch(e) { }
  3628. };
  3629. /*--------------------------------------------------------------------------*/
  3630. var Effect = {
  3631. _elementDoesNotExistError: {
  3632. name: 'ElementDoesNotExistError',
  3633. message: 'The specified DOM element does not exist, but is required for this effect to operate'
  3634. },
  3635. Transitions: {
  3636. linear: Prototype.K,
  3637. sinoidal: function(pos) {
  3638. return (-Math.cos(pos*Math.PI)/2) + .5;
  3639. },
  3640. reverse: function(pos) {
  3641. return 1-pos;
  3642. },
  3643. flicker: function(pos) {
  3644. var pos = ((-Math.cos(pos*Math.PI)/4) + .75) + Math.random()/4;
  3645. return pos > 1 ? 1 : pos;
  3646. },
  3647. wobble: function(pos) {
  3648. return (-Math.cos(pos*Math.PI*(9*pos))/2) + .5;
  3649. },
  3650. pulse: function(pos, pulses) {
  3651. return (-Math.cos((pos*((pulses||5)-.5)*2)*Math.PI)/2) + .5;
  3652. },
  3653. spring: function(pos) {
  3654. return 1 - (Math.cos(pos * 4.5 * Math.PI) * Math.exp(-pos * 6));
  3655. },
  3656. none: function(pos) {
  3657. return 0;
  3658. },
  3659. full: function(pos) {
  3660. return 1;
  3661. }
  3662. },
  3663. DefaultOptions: {
  3664. duration: 1.0, // seconds
  3665. fps: 100, // 100= assume 66fps max.
  3666. sync: false, // true for combining
  3667. from: 0.0,
  3668. to: 1.0,
  3669. delay: 0.0,
  3670. queue: 'parallel'
  3671. },
  3672. tagifyText: function(element) {
  3673. var tagifyStyle = 'position:relative';
  3674. if (Prototype.Browser.IE) tagifyStyle += ';zoom:1';
  3675. element = $(element);
  3676. $A(element.childNodes).each( function(child) {
  3677. if (child.nodeType==3) {
  3678. child.nodeValue.toArray().each( function(character) {
  3679. element.insertBefore(
  3680. new Element('span', {style: tagifyStyle}).update(
  3681. character == ' ' ? String.fromCharCode(160) : character),
  3682. child);
  3683. });
  3684. Element.remove(child);
  3685. }
  3686. });
  3687. },
  3688. multiple: function(element, effect) {
  3689. var elements;
  3690. if (((typeof element == 'object') ||
  3691. Object.isFunction(element)) &&
  3692. (element.length))
  3693. elements = element;
  3694. else
  3695. elements = $(element).childNodes;
  3696. var options = Object.extend({
  3697. speed: 0.1,
  3698. delay: 0.0
  3699. }, arguments[2] || { });
  3700. var masterDelay = options.delay;
  3701. $A(elements).each( function(element, index) {
  3702. new effect(element, Object.extend(options, { delay: index * options.speed + masterDelay }));
  3703. });
  3704. },
  3705. PAIRS: {
  3706. 'slide': ['SlideDown','SlideUp'],
  3707. 'blind': ['BlindDown','BlindUp'],
  3708. 'appear': ['Appear','Fade']
  3709. },
  3710. toggle: function(element, effect) {
  3711. element = $(element);
  3712. effect = (effect || 'appear').toLowerCase();
  3713. var options = Object.extend({
  3714. queue: { position:'end', scope:(element.id || 'global'), limit: 1 }
  3715. }, arguments[2] || { });
  3716. Effect[element.visible() ?
  3717. Effect.PAIRS[effect][1] : Effect.PAIRS[effect][0]](element, options);
  3718. }
  3719. };
  3720. Effect.DefaultOptions.transition = Effect.Transitions.sinoidal;
  3721. /* ------------- core effects ------------- */
  3722. Effect.ScopedQueue = Class.create(Enumerable, {
  3723. initialize: function() {
  3724. this.effects = [];
  3725. this.interval = null;
  3726. },
  3727. _each: function(iterator) {
  3728. this.effects._each(iterator);
  3729. },
  3730. add: function(effect) {
  3731. var timestamp = new Date().getTime();
  3732. var position = Object.isString(effect.options.queue) ?
  3733. effect.options.queue : effect.options.queue.position;
  3734. switch(position) {
  3735. case 'front':
  3736. // move unstarted effects after this effect
  3737. this.effects.findAll(function(e){ return e.state=='idle' }).each( function(e) {
  3738. e.startOn += effect.finishOn;
  3739. e.finishOn += effect.finishOn;
  3740. });
  3741. break;
  3742. case 'with-last':
  3743. timestamp = this.effects.pluck('startOn').max() || timestamp;
  3744. break;
  3745. case 'end':
  3746. // start effect after last queued effect has finished
  3747. timestamp = this.effects.pluck('finishOn').max() || timestamp;
  3748. break;
  3749. }
  3750. effect.startOn += timestamp;
  3751. effect.finishOn += timestamp;
  3752. if (!effect.options.queue.limit || (this.effects.length < effect.options.queue.limit))
  3753. this.effects.push(effect);
  3754. if (!this.interval)
  3755. this.interval = setInterval(this.loop.bind(this), 15);
  3756. },
  3757. remove: function(effect) {
  3758. this.effects = this.effects.reject(function(e) { return e==effect });
  3759. if (this.effects.length == 0) {
  3760. clearInterval(this.interval);
  3761. this.interval = null;
  3762. }
  3763. },
  3764. loop: function() {
  3765. var timePos = new Date().getTime();
  3766. for(var i=0, len=this.effects.length;i<len;i++)
  3767. this.effects[i] && this.effects[i].loop(timePos);
  3768. }
  3769. });
  3770. Effect.Queues = {
  3771. instances: $H(),
  3772. get: function(queueName) {
  3773. if (!Object.isString(queueName)) return queueName;
  3774. return this.instances.get(queueName) ||
  3775. this.instances.set(queueName, new Effect.ScopedQueue());
  3776. }
  3777. };
  3778. Effect.Queue = Effect.Queues.get('global');
  3779. Effect.Base = Class.create({
  3780. position: null,
  3781. start: function(options) {
  3782. function codeForEvent(options,eventName){
  3783. return (
  3784. (options[eventName+'Internal'] ? 'this.options.'+eventName+'Internal(this);' : '') +
  3785. (options[eventName] ? 'this.options.'+eventName+'(this);' : '')
  3786. );
  3787. }
  3788. if (options && options.transition === false) options.transition = Effect.Transitions.linear;
  3789. this.options = Object.extend(Object.extend({ },Effect.DefaultOptions), options || { });
  3790. this.currentFrame = 0;
  3791. this.state = 'idle';
  3792. this.startOn = this.options.delay*1000;
  3793. this.finishOn = this.startOn+(this.options.duration*1000);
  3794. this.fromToDelta = this.options.to-this.options.from;
  3795. this.totalTime = this.finishOn-this.startOn;
  3796. this.totalFrames = this.options.fps*this.options.duration;
  3797. this.render = (function() {
  3798. function dispatch(effect, eventName) {
  3799. if (effect.options[eventName + 'Internal'])
  3800. effect.options[eventName + 'Internal'](effect);
  3801. if (effect.options[eventName])
  3802. effect.options[eventName](effect);
  3803. }
  3804. return function(pos) {
  3805. if (this.state === "idle") {
  3806. this.state = "running";
  3807. dispatch(this, 'beforeSetup');
  3808. if (this.setup) this.setup();
  3809. dispatch(this, 'afterSetup');
  3810. }
  3811. if (this.state === "running") {
  3812. pos = (this.options.transition(pos) * this.fromToDelta) + this.options.from;
  3813. this.position = pos;
  3814. dispatch(this, 'beforeUpdate');
  3815. if (this.update) this.update(pos);
  3816. dispatch(this, 'afterUpdate');
  3817. }
  3818. };
  3819. })();
  3820. this.event('beforeStart');
  3821. if (!this.options.sync)
  3822. Effect.Queues.get(Object.isString(this.options.queue) ?
  3823. 'global' : this.options.queue.scope).add(this);
  3824. },
  3825. loop: function(timePos) {
  3826. if (timePos >= this.startOn) {
  3827. if (timePos >= this.finishOn) {
  3828. this.render(1.0);
  3829. this.cancel();
  3830. this.event('beforeFinish');
  3831. if (this.finish) this.finish();
  3832. this.event('afterFinish');
  3833. return;
  3834. }
  3835. var pos = (timePos - this.startOn) / this.totalTime,
  3836. frame = (pos * this.totalFrames).round();
  3837. if (frame > this.currentFrame) {
  3838. this.render(pos);
  3839. this.currentFrame = frame;
  3840. }
  3841. }
  3842. },
  3843. cancel: function() {
  3844. if (!this.options.sync)
  3845. Effect.Queues.get(Object.isString(this.options.queue) ?
  3846. 'global' : this.options.queue.scope).remove(this);
  3847. this.state = 'finished';
  3848. },
  3849. event: function(eventName) {
  3850. if (this.options[eventName + 'Internal']) this.options[eventName + 'Internal'](this);
  3851. if (this.options[eventName]) this.options[eventName](this);
  3852. },
  3853. inspect: function() {
  3854. var data = $H();
  3855. for(property in this)
  3856. if (!Object.isFunction(this[property])) data.set(property, this[property]);
  3857. return '#<Effect:' + data.inspect() + ',options:' + $H(this.options).inspect() + '>';
  3858. }
  3859. });
  3860. Effect.Parallel = Class.create(Effect.Base, {
  3861. initialize: function(effects) {
  3862. this.effects = effects || [];
  3863. this.start(arguments[1]);
  3864. },
  3865. update: function(position) {
  3866. this.effects.invoke('render', position);
  3867. },
  3868. finish: function(position) {
  3869. this.effects.each( function(effect) {
  3870. effect.render(1.0);
  3871. effect.cancel();
  3872. effect.event('beforeFinish');
  3873. if (effect.finish) effect.finish(position);
  3874. effect.event('afterFinish');
  3875. });
  3876. }
  3877. });
  3878. Effect.Tween = Class.create(Effect.Base, {
  3879. initialize: function(object, from, to) {
  3880. object = Object.isString(object) ? $(object) : object;
  3881. var args = $A(arguments), method = args.last(),
  3882. options = args.length == 5 ? args[3] : null;
  3883. this.method = Object.isFunction(method) ? method.bind(object) :
  3884. Object.isFunction(object[method]) ? object[method].bind(object) :
  3885. function(value) { object[method] = value };
  3886. this.start(Object.extend({ from: from, to: to }, options || { }));
  3887. },
  3888. update: function(position) {
  3889. this.method(position);
  3890. }
  3891. });
  3892. Effect.Event = Class.create(Effect.Base, {
  3893. initialize: function() {
  3894. this.start(Object.extend({ duration: 0 }, arguments[0] || { }));
  3895. },
  3896. update: Prototype.emptyFunction
  3897. });
  3898. Effect.Opacity = Class.create(Effect.Base, {
  3899. initialize: function(element) {
  3900. this.element = $(element);
  3901. if (!this.element) throw(Effect._elementDoesNotExistError);
  3902. // make this work on IE on elements without 'layout'
  3903. if (Prototype.Browser.IE && (!this.element.currentStyle.hasLayout))
  3904. this.element.setStyle({zoom: 1});
  3905. var options = Object.extend({
  3906. from: this.element.getOpacity() || 0.0,
  3907. to: 1.0
  3908. }, arguments[1] || { });
  3909. this.start(options);
  3910. },
  3911. update: function(position) {
  3912. this.element.setOpacity(position);
  3913. }
  3914. });
  3915. Effect.Move = Class.create(Effect.Base, {
  3916. initialize: function(element) {
  3917. this.element = $(element);
  3918. if (!this.element) throw(Effect._elementDoesNotExistError);
  3919. var options = Object.extend({
  3920. x: 0,
  3921. y: 0,
  3922. mode: 'relative'
  3923. }, arguments[1] || { });
  3924. this.start(options);
  3925. },
  3926. setup: function() {
  3927. this.element.makePositioned();
  3928. this.originalLeft = parseFloat(this.element.getStyle('left') || '0');
  3929. this.originalTop = parseFloat(this.element.getStyle('top') || '0');
  3930. if (this.options.mode == 'absolute') {
  3931. this.options.x = this.options.x - this.originalLeft;
  3932. this.options.y = this.options.y - this.originalTop;
  3933. }
  3934. },
  3935. update: function(position) {
  3936. this.element.setStyle({
  3937. left: (this.options.x * position + this.originalLeft).round() + 'px',
  3938. top: (this.options.y * position + this.originalTop).round() + 'px'
  3939. });
  3940. }
  3941. });
  3942. // for backwards compatibility
  3943. Effect.MoveBy = function(element, toTop, toLeft) {
  3944. return new Effect.Move(element,
  3945. Object.extend({ x: toLeft, y: toTop }, arguments[3] || { }));
  3946. };
  3947. Effect.Scale = Class.create(Effect.Base, {
  3948. initialize: function(element, percent) {
  3949. this.element = $(element);
  3950. if (!this.element) throw(Effect._elementDoesNotExistError);
  3951. var options = Object.extend({
  3952. scaleX: true,
  3953. scaleY: true,
  3954. scaleContent: true,
  3955. scaleFromCenter: false,
  3956. scaleMode: 'box', // 'box' or 'contents' or { } with provided values
  3957. scaleFrom: 100.0,
  3958. scaleTo: percent
  3959. }, arguments[2] || { });
  3960. this.start(options);
  3961. },
  3962. setup: function() {
  3963. this.restoreAfterFinish = this.options.restoreAfterFinish || false;
  3964. this.elementPositioning = this.element.getStyle('position');
  3965. this.originalStyle = { };
  3966. ['top','left','width','height','fontSize'].each( function(k) {
  3967. this.originalStyle[k] = this.element.style[k];
  3968. }.bind(this));
  3969. this.originalTop = this.element.offsetTop;
  3970. this.originalLeft = this.element.offsetLeft;
  3971. var fontSize = this.element.getStyle('font-size') || '100%';
  3972. ['em','px','%','pt'].each( function(fontSizeType) {
  3973. if (fontSize.indexOf(fontSizeType)>0) {
  3974. this.fontSize = parseFloat(fontSize);
  3975. this.fontSizeType = fontSizeType;
  3976. }
  3977. }.bind(this));
  3978. this.factor = (this.options.scaleTo - this.options.scaleFrom)/100;
  3979. this.dims = null;
  3980. if (this.options.scaleMode=='box')
  3981. this.dims = [this.element.offsetHeight, this.element.offsetWidth];
  3982. if (/^content/.test(this.options.scaleMode))
  3983. this.dims = [this.element.scrollHeight, this.element.scrollWidth];
  3984. if (!this.dims)
  3985. this.dims = [this.options.scaleMode.originalHeight,
  3986. this.options.scaleMode.originalWidth];
  3987. },
  3988. update: function(position) {
  3989. var currentScale = (this.options.scaleFrom/100.0) + (this.factor * position);
  3990. if (this.options.scaleContent && this.fontSize)
  3991. this.element.setStyle({fontSize: this.fontSize * currentScale + this.fontSizeType });
  3992. this.setDimensions(this.dims[0] * currentScale, this.dims[1] * currentScale);
  3993. },
  3994. finish: function(position) {
  3995. if (this.restoreAfterFinish) this.element.setStyle(this.originalStyle);
  3996. },
  3997. setDimensions: function(height, width) {
  3998. var d = { };
  3999. if (this.options.scaleX) d.width = width.round() + 'px';
  4000. if (this.options.scaleY) d.height = height.round() + 'px';
  4001. if (this.options.scaleFromCenter) {
  4002. var topd = (height - this.dims[0])/2;
  4003. var leftd = (width - this.dims[1])/2;
  4004. if (this.elementPositioning == 'absolute') {
  4005. if (this.options.scaleY) d.top = this.originalTop-topd + 'px';
  4006. if (this.options.scaleX) d.left = this.originalLeft-leftd + 'px';
  4007. } else {
  4008. if (this.options.scaleY) d.top = -topd + 'px';
  4009. if (this.options.scaleX) d.left = -leftd + 'px';
  4010. }
  4011. }
  4012. this.element.setStyle(d);
  4013. }
  4014. });
  4015. Effect.Highlight = Class.create(Effect.Base, {
  4016. initialize: function(element) {
  4017. this.element = $(element);
  4018. if (!this.element) throw(Effect._elementDoesNotExistError);
  4019. var options = Object.extend({ startcolor: '#ffff99' }, arguments[1] || { });
  4020. this.start(options);
  4021. },
  4022. setup: function() {
  4023. // Prevent executing on elements not in the layout flow
  4024. if (this.element.getStyle('display')=='none') { this.cancel(); return; }
  4025. // Disable background image during the effect
  4026. this.oldStyle = { };
  4027. if (!this.options.keepBackgroundImage) {
  4028. this.oldStyle.backgroundImage = this.element.getStyle('background-image');
  4029. this.element.setStyle({backgroundImage: 'none'});
  4030. }
  4031. if (!this.options.endcolor)
  4032. this.options.endcolor = this.element.getStyle('background-color').parseColor('#ffffff');
  4033. if (!this.options.restorecolor)
  4034. this.options.restorecolor = this.element.getStyle('background-color');
  4035. // init color calculations
  4036. this._base = $R(0,2).map(function(i){ return parseInt(this.options.startcolor.slice(i*2+1,i*2+3),16) }.bind(this));
  4037. this._delta = $R(0,2).map(function(i){ return parseInt(this.options.endcolor.slice(i*2+1,i*2+3),16)-this._base[i] }.bind(this));
  4038. },
  4039. update: function(position) {
  4040. this.element.setStyle({backgroundColor: $R(0,2).inject('#',function(m,v,i){
  4041. return m+((this._base[i]+(this._delta[i]*position)).round().toColorPart()); }.bind(this)) });
  4042. },
  4043. finish: function() {
  4044. this.element.setStyle(Object.extend(this.oldStyle, {
  4045. backgroundColor: this.options.restorecolor
  4046. }));
  4047. }
  4048. });
  4049. Effect.ScrollTo = function(element) {
  4050. var options = arguments[1] || { },
  4051. scrollOffsets = document.viewport.getScrollOffsets(),
  4052. elementOffsets = $(element).cumulativeOffset();
  4053. if (options.offset) elementOffsets[1] += options.offset;
  4054. return new Effect.Tween(null,
  4055. scrollOffsets.top,
  4056. elementOffsets[1],
  4057. options,
  4058. function(p){ scrollTo(scrollOffsets.left, p.round()); }
  4059. );
  4060. };
  4061. /* ------------- combination effects ------------- */
  4062. Effect.Fade = function(element) {
  4063. element = $(element);
  4064. var oldOpacity = element.getInlineOpacity();
  4065. var options = Object.extend({
  4066. from: element.getOpacity() || 1.0,
  4067. to: 0.0,
  4068. afterFinishInternal: function(effect) {
  4069. if (effect.options.to!=0) return;
  4070. effect.element.hide().setStyle({opacity: oldOpacity});
  4071. }
  4072. }, arguments[1] || { });
  4073. return new Effect.Opacity(element,options);
  4074. };
  4075. Effect.Appear = function(element) {
  4076. element = $(element);
  4077. var options = Object.extend({
  4078. from: (element.getStyle('display') == 'none' ? 0.0 : element.getOpacity() || 0.0),
  4079. to: 1.0,
  4080. // force Safari to render floated elements properly
  4081. afterFinishInternal: function(effect) {
  4082. effect.element.forceRerendering();
  4083. },
  4084. beforeSetup: function(effect) {
  4085. effect.element.setOpacity(effect.options.from).show();
  4086. }}, arguments[1] || { });
  4087. return new Effect.Opacity(element,options);
  4088. };
  4089. Effect.Puff = function(element) {
  4090. element = $(element);
  4091. var oldStyle = {
  4092. opacity: element.getInlineOpacity(),
  4093. position: element.getStyle('position'),
  4094. top: element.style.top,
  4095. left: element.style.left,
  4096. width: element.style.width,
  4097. height: element.style.height
  4098. };
  4099. return new Effect.Parallel(
  4100. [ new Effect.Scale(element, 200,
  4101. { sync: true, scaleFromCenter: true, scaleContent: true, restoreAfterFinish: true }),
  4102. new Effect.Opacity(element, { sync: true, to: 0.0 } ) ],
  4103. Object.extend({ duration: 1.0,
  4104. beforeSetupInternal: function(effect) {
  4105. Position.absolutize(effect.effects[0].element);
  4106. },
  4107. afterFinishInternal: function(effect) {
  4108. effect.effects[0].element.hide().setStyle(oldStyle); }
  4109. }, arguments[1] || { })
  4110. );
  4111. };
  4112. Effect.BlindUp = function(element) {
  4113. element = $(element);
  4114. element.makeClipping();
  4115. return new Effect.Scale(element, 0,
  4116. Object.extend({ scaleContent: false,
  4117. scaleX: false,
  4118. restoreAfterFinish: true,
  4119. afterFinishInternal: function(effect) {
  4120. effect.element.hide().undoClipping();
  4121. }
  4122. }, arguments[1] || { })
  4123. );
  4124. };
  4125. Effect.BlindDown = function(element) {
  4126. element = $(element);
  4127. var elementDimensions = element.getDimensions();
  4128. return new Effect.Scale(element, 100, Object.extend({
  4129. scaleContent: false,
  4130. scaleX: false,
  4131. scaleFrom: 0,
  4132. scaleMode: {originalHeight: elementDimensions.height, originalWidth: elementDimensions.width},
  4133. restoreAfterFinish: true,
  4134. afterSetup: function(effect) {
  4135. effect.element.makeClipping().setStyle({height: '0px'}).show();
  4136. },
  4137. afterFinishInternal: function(effect) {
  4138. effect.element.undoClipping();
  4139. }
  4140. }, arguments[1] || { }));
  4141. };
  4142. Effect.SwitchOff = function(element) {
  4143. element = $(element);
  4144. var oldOpacity = element.getInlineOpacity();
  4145. return new Effect.Appear(element, Object.extend({
  4146. duration: 0.4,
  4147. from: 0,
  4148. transition: Effect.Transitions.flicker,
  4149. afterFinishInternal: function(effect) {
  4150. new Effect.Scale(effect.element, 1, {
  4151. duration: 0.3, scaleFromCenter: true,
  4152. scaleX: false, scaleContent: false, restoreAfterFinish: true,
  4153. beforeSetup: function(effect) {
  4154. effect.element.makePositioned().makeClipping();
  4155. },
  4156. afterFinishInternal: function(effect) {
  4157. effect.element.hide().undoClipping().undoPositioned().setStyle({opacity: oldOpacity});
  4158. }
  4159. });
  4160. }
  4161. }, arguments[1] || { }));
  4162. };
  4163. Effect.DropOut = function(element) {
  4164. element = $(element);
  4165. var oldStyle = {
  4166. top: element.getStyle('top'),
  4167. left: element.getStyle('left'),
  4168. opacity: element.getInlineOpacity() };
  4169. return new Effect.Parallel(
  4170. [ new Effect.Move(element, {x: 0, y: 100, sync: true }),
  4171. new Effect.Opacity(element, { sync: true, to: 0.0 }) ],
  4172. Object.extend(
  4173. { duration: 0.5,
  4174. beforeSetup: function(effect) {
  4175. effect.effects[0].element.makePositioned();
  4176. },
  4177. afterFinishInternal: function(effect) {
  4178. effect.effects[0].element.hide().undoPositioned().setStyle(oldStyle);
  4179. }
  4180. }, arguments[1] || { }));
  4181. };
  4182. Effect.Shake = function(element) {
  4183. element = $(element);
  4184. var options = Object.extend({
  4185. distance: 20,
  4186. duration: 0.5
  4187. }, arguments[1] || {});
  4188. var distance = parseFloat(options.distance);
  4189. var split = parseFloat(options.duration) / 10.0;
  4190. var oldStyle = {
  4191. top: element.getStyle('top'),
  4192. left: element.getStyle('left') };
  4193. return new Effect.Move(element,
  4194. { x: distance, y: 0, duration: split, afterFinishInternal: function(effect) {
  4195. new Effect.Move(effect.element,
  4196. { x: -distance*2, y: 0, duration: split*2, afterFinishInternal: function(effect) {
  4197. new Effect.Move(effect.element,
  4198. { x: distance*2, y: 0, duration: split*2, afterFinishInternal: function(effect) {
  4199. new Effect.Move(effect.element,
  4200. { x: -distance*2, y: 0, duration: split*2, afterFinishInternal: function(effect) {
  4201. new Effect.Move(effect.element,
  4202. { x: distance*2, y: 0, duration: split*2, afterFinishInternal: function(effect) {
  4203. new Effect.Move(effect.element,
  4204. { x: -distance, y: 0, duration: split, afterFinishInternal: function(effect) {
  4205. effect.element.undoPositioned().setStyle(oldStyle);
  4206. }}); }}); }}); }}); }}); }});
  4207. };
  4208. Effect.SlideDown = function(element) {
  4209. element = $(element).cleanWhitespace();
  4210. // SlideDown need to have the content of the element wrapped in a container element with fixed height!
  4211. var oldInnerBottom = element.down().getStyle('bottom');
  4212. var elementDimensions = element.getDimensions();
  4213. return new Effect.Scale(element, 100, Object.extend({
  4214. scaleContent: false,
  4215. scaleX: false,
  4216. scaleFrom: window.opera ? 0 : 1,
  4217. scaleMode: {originalHeight: elementDimensions.height, originalWidth: elementDimensions.width},
  4218. restoreAfterFinish: true,
  4219. afterSetup: function(effect) {
  4220. effect.element.makePositioned();
  4221. effect.element.down().makePositioned();
  4222. if (window.opera) effect.element.setStyle({top: ''});
  4223. effect.element.makeClipping().setStyle({height: '0px'}).show();
  4224. },
  4225. afterUpdateInternal: function(effect) {
  4226. effect.element.down().setStyle({bottom:
  4227. (effect.dims[0] - effect.element.clientHeight) + 'px' });
  4228. },
  4229. afterFinishInternal: function(effect) {
  4230. effect.element.undoClipping().undoPositioned();
  4231. effect.element.down().undoPositioned().setStyle({bottom: oldInnerBottom}); }
  4232. }, arguments[1] || { })
  4233. );
  4234. };
  4235. Effect.SlideUp = function(element) {
  4236. element = $(element).cleanWhitespace();
  4237. var oldInnerBottom = element.down().getStyle('bottom');
  4238. var elementDimensions = element.getDimensions();
  4239. return new Effect.Scale(element, window.opera ? 0 : 1,
  4240. Object.extend({ scaleContent: false,
  4241. scaleX: false,
  4242. scaleMode: 'box',
  4243. scaleFrom: 100,
  4244. scaleMode: {originalHeight: elementDimensions.height, originalWidth: elementDimensions.width},
  4245. restoreAfterFinish: true,
  4246. afterSetup: function(effect) {
  4247. effect.element.makePositioned();
  4248. effect.element.down().makePositioned();
  4249. if (window.opera) effect.element.setStyle({top: ''});
  4250. effect.element.makeClipping().show();
  4251. },
  4252. afterUpdateInternal: function(effect) {
  4253. effect.element.down().setStyle({bottom:
  4254. (effect.dims[0] - effect.element.clientHeight) + 'px' });
  4255. },
  4256. afterFinishInternal: function(effect) {
  4257. effect.element.hide().undoClipping().undoPositioned();
  4258. effect.element.down().undoPositioned().setStyle({bottom: oldInnerBottom});
  4259. }
  4260. }, arguments[1] || { })
  4261. );
  4262. };
  4263. // Bug in opera makes the TD containing this element expand for a instance after finish
  4264. Effect.Squish = function(element) {
  4265. return new Effect.Scale(element, window.opera ? 1 : 0, {
  4266. restoreAfterFinish: true,
  4267. beforeSetup: function(effect) {
  4268. effect.element.makeClipping();
  4269. },
  4270. afterFinishInternal: function(effect) {
  4271. effect.element.hide().undoClipping();
  4272. }
  4273. });
  4274. };
  4275. Effect.Grow = function(element) {
  4276. element = $(element);
  4277. var options = Object.extend({
  4278. direction: 'center',
  4279. moveTransition: Effect.Transitions.sinoidal,
  4280. scaleTransition: Effect.Transitions.sinoidal,
  4281. opacityTransition: Effect.Transitions.full
  4282. }, arguments[1] || { });
  4283. var oldStyle = {
  4284. top: element.style.top,
  4285. left: element.style.left,
  4286. height: element.style.height,
  4287. width: element.style.width,
  4288. opacity: element.getInlineOpacity() };
  4289. var dims = element.getDimensions();
  4290. var initialMoveX, initialMoveY;
  4291. var moveX, moveY;
  4292. switch (options.direction) {
  4293. case 'top-left':
  4294. initialMoveX = initialMoveY = moveX = moveY = 0;
  4295. break;
  4296. case 'top-right':
  4297. initialMoveX = dims.width;
  4298. initialMoveY = moveY = 0;
  4299. moveX = -dims.width;
  4300. break;
  4301. case 'bottom-left':
  4302. initialMoveX = moveX = 0;
  4303. initialMoveY = dims.height;
  4304. moveY = -dims.height;
  4305. break;
  4306. case 'bottom-right':
  4307. initialMoveX = dims.width;
  4308. initialMoveY = dims.height;
  4309. moveX = -dims.width;
  4310. moveY = -dims.height;
  4311. break;
  4312. case 'center':
  4313. initialMoveX = dims.width / 2;
  4314. initialMoveY = dims.height / 2;
  4315. moveX = -dims.width / 2;
  4316. moveY = -dims.height / 2;
  4317. break;
  4318. }
  4319. return new Effect.Move(element, {
  4320. x: initialMoveX,
  4321. y: initialMoveY,
  4322. duration: 0.01,
  4323. beforeSetup: function(effect) {
  4324. effect.element.hide().makeClipping().makePositioned();
  4325. },
  4326. afterFinishInternal: function(effect) {
  4327. new Effect.Parallel(
  4328. [ new Effect.Opacity(effect.element, { sync: true, to: 1.0, from: 0.0, transition: options.opacityTransition }),
  4329. new Effect.Move(effect.element, { x: moveX, y: moveY, sync: true, transition: options.moveTransition }),
  4330. new Effect.Scale(effect.element, 100, {
  4331. scaleMode: { originalHeight: dims.height, originalWidth: dims.width },
  4332. sync: true, scaleFrom: window.opera ? 1 : 0, transition: options.scaleTransition, restoreAfterFinish: true})
  4333. ], Object.extend({
  4334. beforeSetup: function(effect) {
  4335. effect.effects[0].element.setStyle({height: '0px'}).show();
  4336. },
  4337. afterFinishInternal: function(effect) {
  4338. effect.effects[0].element.undoClipping().undoPositioned().setStyle(oldStyle);
  4339. }
  4340. }, options)
  4341. );
  4342. }
  4343. });
  4344. };
  4345. Effect.Shrink = function(element) {
  4346. element = $(element);
  4347. var options = Object.extend({
  4348. direction: 'center',
  4349. moveTransition: Effect.Transitions.sinoidal,
  4350. scaleTransition: Effect.Transitions.sinoidal,
  4351. opacityTransition: Effect.Transitions.none
  4352. }, arguments[1] || { });
  4353. var oldStyle = {
  4354. top: element.style.top,
  4355. left: element.style.left,
  4356. height: element.style.height,
  4357. width: element.style.width,
  4358. opacity: element.getInlineOpacity() };
  4359. var dims = element.getDimensions();
  4360. var moveX, moveY;
  4361. switch (options.direction) {
  4362. case 'top-left':
  4363. moveX = moveY = 0;
  4364. break;
  4365. case 'top-right':
  4366. moveX = dims.width;
  4367. moveY = 0;
  4368. break;
  4369. case 'bottom-left':
  4370. moveX = 0;
  4371. moveY = dims.height;
  4372. break;
  4373. case 'bottom-right':
  4374. moveX = dims.width;
  4375. moveY = dims.height;
  4376. break;
  4377. case 'center':
  4378. moveX = dims.width / 2;
  4379. moveY = dims.height / 2;
  4380. break;
  4381. }
  4382. return new Effect.Parallel(
  4383. [ new Effect.Opacity(element, { sync: true, to: 0.0, from: 1.0, transition: options.opacityTransition }),
  4384. new Effect.Scale(element, window.opera ? 1 : 0, { sync: true, transition: options.scaleTransition, restoreAfterFinish: true}),
  4385. new Effect.Move(element, { x: moveX, y: moveY, sync: true, transition: options.moveTransition })
  4386. ], Object.extend({
  4387. beforeStartInternal: function(effect) {
  4388. effect.effects[0].element.makePositioned().makeClipping();
  4389. },
  4390. afterFinishInternal: function(effect) {
  4391. effect.effects[0].element.hide().undoClipping().undoPositioned().setStyle(oldStyle); }
  4392. }, options)
  4393. );
  4394. };
  4395. Effect.Pulsate = function(element) {
  4396. element = $(element);
  4397. var options = arguments[1] || { },
  4398. oldOpacity = element.getInlineOpacity(),
  4399. transition = options.transition || Effect.Transitions.linear,
  4400. reverser = function(pos){
  4401. return 1 - transition((-Math.cos((pos*(options.pulses||5)*2)*Math.PI)/2) + .5);
  4402. };
  4403. return new Effect.Opacity(element,
  4404. Object.extend(Object.extend({ duration: 2.0, from: 0,
  4405. afterFinishInternal: function(effect) { effect.element.setStyle({opacity: oldOpacity}); }
  4406. }, options), {transition: reverser}));
  4407. };
  4408. Effect.Fold = function(element) {
  4409. element = $(element);
  4410. var oldStyle = {
  4411. top: element.style.top,
  4412. left: element.style.left,
  4413. width: element.style.width,
  4414. height: element.style.height };
  4415. element.makeClipping();
  4416. return new Effect.Scale(element, 5, Object.extend({
  4417. scaleContent: false,
  4418. scaleX: false,
  4419. afterFinishInternal: function(effect) {
  4420. new Effect.Scale(element, 1, {
  4421. scaleContent: false,
  4422. scaleY: false,
  4423. afterFinishInternal: function(effect) {
  4424. effect.element.hide().undoClipping().setStyle(oldStyle);
  4425. } });
  4426. }}, arguments[1] || { }));
  4427. };
  4428. Effect.Morph = Class.create(Effect.Base, {
  4429. initialize: function(element) {
  4430. this.element = $(element);
  4431. if (!this.element) throw(Effect._elementDoesNotExistError);
  4432. var options = Object.extend({
  4433. style: { }
  4434. }, arguments[1] || { });
  4435. if (!Object.isString(options.style)) this.style = $H(options.style);
  4436. else {
  4437. if (options.style.include(':'))
  4438. this.style = options.style.parseStyle();
  4439. else {
  4440. this.element.addClassName(options.style);
  4441. this.style = $H(this.element.getStyles());
  4442. this.element.removeClassName(options.style);
  4443. var css = this.element.getStyles();
  4444. this.style = this.style.reject(function(style) {
  4445. return style.value == css[style.key];
  4446. });
  4447. options.afterFinishInternal = function(effect) {
  4448. effect.element.addClassName(effect.options.style);
  4449. effect.transforms.each(function(transform) {
  4450. effect.element.style[transform.style] = '';
  4451. });
  4452. };
  4453. }
  4454. }
  4455. this.start(options);
  4456. },
  4457. setup: function(){
  4458. function parseColor(color){
  4459. if (!color || ['rgba(0, 0, 0, 0)','transparent'].include(color)) color = '#ffffff';
  4460. color = color.parseColor();
  4461. return $R(0,2).map(function(i){
  4462. return parseInt( color.slice(i*2+1,i*2+3), 16 );
  4463. });
  4464. }
  4465. this.transforms = this.style.map(function(pair){
  4466. var property = pair[0], value = pair[1], unit = null;
  4467. if (value.parseColor('#zzzzzz') != '#zzzzzz') {
  4468. value = value.parseColor();
  4469. unit = 'color';
  4470. } else if (property == 'opacity') {
  4471. value = parseFloat(value);
  4472. if (Prototype.Browser.IE && (!this.element.currentStyle.hasLayout))
  4473. this.element.setStyle({zoom: 1});
  4474. } else if (Element.CSS_LENGTH.test(value)) {
  4475. var components = value.match(/^([\+\-]?[0-9\.]+)(.*)$/);
  4476. value = parseFloat(components[1]);
  4477. unit = (components.length == 3) ? components[2] : null;
  4478. }
  4479. var originalValue = this.element.getStyle(property);
  4480. return {
  4481. style: property.camelize(),
  4482. originalValue: unit=='color' ? parseColor(originalValue) : parseFloat(originalValue || 0),
  4483. targetValue: unit=='color' ? parseColor(value) : value,
  4484. unit: unit
  4485. };
  4486. }.bind(this)).reject(function(transform){
  4487. return (
  4488. (transform.originalValue == transform.targetValue) ||
  4489. (
  4490. transform.unit != 'color' &&
  4491. (isNaN(transform.originalValue) || isNaN(transform.targetValue))
  4492. )
  4493. );
  4494. });
  4495. },
  4496. update: function(position) {
  4497. var style = { }, transform, i = this.transforms.length;
  4498. while(i--)
  4499. style[(transform = this.transforms[i]).style] =
  4500. transform.unit=='color' ? '#'+
  4501. (Math.round(transform.originalValue[0]+
  4502. (transform.targetValue[0]-transform.originalValue[0])*position)).toColorPart() +
  4503. (Math.round(transform.originalValue[1]+
  4504. (transform.targetValue[1]-transform.originalValue[1])*position)).toColorPart() +
  4505. (Math.round(transform.originalValue[2]+
  4506. (transform.targetValue[2]-transform.originalValue[2])*position)).toColorPart() :
  4507. (transform.originalValue +
  4508. (transform.targetValue - transform.originalValue) * position).toFixed(3) +
  4509. (transform.unit === null ? '' : transform.unit);
  4510. this.element.setStyle(style, true);
  4511. }
  4512. });
  4513. Effect.Transform = Class.create({
  4514. initialize: function(tracks){
  4515. this.tracks = [];
  4516. this.options = arguments[1] || { };
  4517. this.addTracks(tracks);
  4518. },
  4519. addTracks: function(tracks){
  4520. tracks.each(function(track){
  4521. track = $H(track);
  4522. var data = track.values().first();
  4523. this.tracks.push($H({
  4524. ids: track.keys().first(),
  4525. effect: Effect.Morph,
  4526. options: { style: data }
  4527. }));
  4528. }.bind(this));
  4529. return this;
  4530. },
  4531. play: function(){
  4532. return new Effect.Parallel(
  4533. this.tracks.map(function(track){
  4534. var ids = track.get('ids'), effect = track.get('effect'), options = track.get('options');
  4535. var elements = [$(ids) || $$(ids)].flatten();
  4536. return elements.map(function(e){ return new effect(e, Object.extend({ sync:true }, options)) });
  4537. }).flatten(),
  4538. this.options
  4539. );
  4540. }
  4541. });
  4542. Element.CSS_PROPERTIES = $w(
  4543. 'backgroundColor backgroundPosition borderBottomColor borderBottomStyle ' +
  4544. 'borderBottomWidth borderLeftColor borderLeftStyle borderLeftWidth ' +
  4545. 'borderRightColor borderRightStyle borderRightWidth borderSpacing ' +
  4546. 'borderTopColor borderTopStyle borderTopWidth bottom clip color ' +
  4547. 'fontSize fontWeight height left letterSpacing lineHeight ' +
  4548. 'marginBottom marginLeft marginRight marginTop markerOffset maxHeight '+
  4549. 'maxWidth minHeight minWidth opacity outlineColor outlineOffset ' +
  4550. 'outlineWidth paddingBottom paddingLeft paddingRight paddingTop ' +
  4551. 'right textIndent top width wordSpacing zIndex');
  4552. Element.CSS_LENGTH = /^(([\+\-]?[0-9\.]+)(em|ex|px|in|cm|mm|pt|pc|\%))|0$/;
  4553. String.__parseStyleElement = document.createElement('div');
  4554. String.prototype.parseStyle = function(){
  4555. var style, styleRules = $H();
  4556. if (Prototype.Browser.WebKit)
  4557. style = new Element('div',{style:this}).style;
  4558. else {
  4559. String.__parseStyleElement.innerHTML = '<div style="' + this + '"></div>';
  4560. style = String.__parseStyleElement.childNodes[0].style;
  4561. }
  4562. Element.CSS_PROPERTIES.each(function(property){
  4563. if (style[property]) styleRules.set(property, style[property]);
  4564. });
  4565. if (Prototype.Browser.IE && this.include('opacity'))
  4566. styleRules.set('opacity', this.match(/opacity:\s*((?:0|1)?(?:\.\d*)?)/)[1]);
  4567. return styleRules;
  4568. };
  4569. if (document.defaultView && document.defaultView.getComputedStyle) {
  4570. Element.getStyles = function(element) {
  4571. var css = document.defaultView.getComputedStyle($(element), null);
  4572. return Element.CSS_PROPERTIES.inject({ }, function(styles, property) {
  4573. styles[property] = css[property];
  4574. return styles;
  4575. });
  4576. };
  4577. } else {
  4578. Element.getStyles = function(element) {
  4579. element = $(element);
  4580. var css = element.currentStyle, styles;
  4581. styles = Element.CSS_PROPERTIES.inject({ }, function(results, property) {
  4582. results[property] = css[property];
  4583. return results;
  4584. });
  4585. if (!styles.opacity) styles.opacity = element.getOpacity();
  4586. return styles;
  4587. };
  4588. }
  4589. Effect.Methods = {
  4590. morph: function(element, style) {
  4591. element = $(element);
  4592. new Effect.Morph(element, Object.extend({ style: style }, arguments[2] || { }));
  4593. return element;
  4594. },
  4595. visualEffect: function(element, effect, options) {
  4596. element = $(element);
  4597. var s = effect.dasherize().camelize(), klass = s.charAt(0).toUpperCase() + s.substring(1);
  4598. new Effect[klass](element, options);
  4599. return element;
  4600. },
  4601. highlight: function(element, options) {
  4602. element = $(element);
  4603. new Effect.Highlight(element, options);
  4604. return element;
  4605. }
  4606. };
  4607. $w('fade appear grow shrink fold blindUp blindDown slideUp slideDown '+
  4608. 'pulsate shake puff squish switchOff dropOut').each(
  4609. function(effect) {
  4610. Effect.Methods[effect] = function(element, options){
  4611. element = $(element);
  4612. Effect[effect.charAt(0).toUpperCase() + effect.substring(1)](element, options);
  4613. return element;
  4614. };
  4615. }
  4616. );
  4617. $w('getInlineOpacity forceRerendering setContentZoom collectTextNodes collectTextNodesIgnoreClass getStyles').each(
  4618. function(f) { Effect.Methods[f] = Element[f]; }
  4619. );
  4620. Element.addMethods(Effect.Methods);// script.aculo.us dragdrop.js v1.8.2, Tue Nov 18 18:30:58 +0100 2008
  4621. // Copyright (c) 2005-2008 Thomas Fuchs (http://script.aculo.us, http://mir.aculo.us)
  4622. // (c) 2005-2008 Sammi Williams (http://www.oriontransfer.co.nz, sammi@oriontransfer.co.nz)
  4623. //
  4624. // script.aculo.us is freely distributable under the terms of an MIT-style license.
  4625. // For details, see the script.aculo.us web site: http://script.aculo.us/
  4626. if(Object.isUndefined(Effect))
  4627. throw("dragdrop.js requires including script.aculo.us' effects.js library");
  4628. var Droppables = {
  4629. drops: [],
  4630. remove: function(element) {
  4631. this.drops = this.drops.reject(function(d) { return d.element==$(element) });
  4632. },
  4633. add: function(element) {
  4634. element = $(element);
  4635. var options = Object.extend({
  4636. greedy: true,
  4637. hoverclass: null,
  4638. tree: false
  4639. }, arguments[1] || { });
  4640. // cache containers
  4641. if(options.containment) {
  4642. options._containers = [];
  4643. var containment = options.containment;
  4644. if(Object.isArray(containment)) {
  4645. containment.each( function(c) { options._containers.push($(c)) });
  4646. } else {
  4647. options._containers.push($(containment));
  4648. }
  4649. }
  4650. if(options.accept) options.accept = [options.accept].flatten();
  4651. Element.makePositioned(element); // fix IE
  4652. options.element = element;
  4653. this.drops.push(options);
  4654. },
  4655. findDeepestChild: function(drops) {
  4656. deepest = drops[0];
  4657. for (i = 1; i < drops.length; ++i)
  4658. if (Element.isParent(drops[i].element, deepest.element))
  4659. deepest = drops[i];
  4660. return deepest;
  4661. },
  4662. isContained: function(element, drop) {
  4663. var containmentNode;
  4664. if(drop.tree) {
  4665. containmentNode = element.treeNode;
  4666. } else {
  4667. containmentNode = element.parentNode;
  4668. }
  4669. return drop._containers.detect(function(c) { return containmentNode == c });
  4670. },
  4671. isAffected: function(point, element, drop) {
  4672. return (
  4673. (drop.element!=element) &&
  4674. ((!drop._containers) ||
  4675. this.isContained(element, drop)) &&
  4676. ((!drop.accept) ||
  4677. (Element.classNames(element).detect(
  4678. function(v) { return drop.accept.include(v) } ) )) &&
  4679. Position.within(drop.element, point[0], point[1]) );
  4680. },
  4681. deactivate: function(drop) {
  4682. if(drop.hoverclass)
  4683. Element.removeClassName(drop.element, drop.hoverclass);
  4684. this.last_active = null;
  4685. },
  4686. activate: function(drop) {
  4687. if(drop.hoverclass)
  4688. Element.addClassName(drop.element, drop.hoverclass);
  4689. this.last_active = drop;
  4690. },
  4691. show: function(point, element) {
  4692. if(!this.drops.length) return;
  4693. var drop, affected = [];
  4694. this.drops.each( function(drop) {
  4695. if(Droppables.isAffected(point, element, drop))
  4696. affected.push(drop);
  4697. });
  4698. if(affected.length>0)
  4699. drop = Droppables.findDeepestChild(affected);
  4700. if(this.last_active && this.last_active != drop) this.deactivate(this.last_active);
  4701. if (drop) {
  4702. Position.within(drop.element, point[0], point[1]);
  4703. if(drop.onHover)
  4704. drop.onHover(element, drop.element, Position.overlap(drop.overlap, drop.element));
  4705. if (drop != this.last_active) Droppables.activate(drop);
  4706. }
  4707. },
  4708. fire: function(event, element) {
  4709. if(!this.last_active) return;
  4710. Position.prepare();
  4711. if (this.isAffected([Event.pointerX(event), Event.pointerY(event)], element, this.last_active))
  4712. if (this.last_active.onDrop) {
  4713. this.last_active.onDrop(element, this.last_active.element, event);
  4714. return true;
  4715. }
  4716. },
  4717. reset: function() {
  4718. if(this.last_active)
  4719. this.deactivate(this.last_active);
  4720. }
  4721. };
  4722. var Draggables = {
  4723. drags: [],
  4724. observers: [],
  4725. register: function(draggable) {
  4726. if(this.drags.length == 0) {
  4727. this.eventMouseUp = this.endDrag.bindAsEventListener(this);
  4728. this.eventMouseMove = this.updateDrag.bindAsEventListener(this);
  4729. this.eventKeypress = this.keyPress.bindAsEventListener(this);
  4730. Event.observe(document, "mouseup", this.eventMouseUp);
  4731. Event.observe(document, "mousemove", this.eventMouseMove);
  4732. Event.observe(document, "keypress", this.eventKeypress);
  4733. }
  4734. this.drags.push(draggable);
  4735. },
  4736. unregister: function(draggable) {
  4737. this.drags = this.drags.reject(function(d) { return d==draggable });
  4738. if(this.drags.length == 0) {
  4739. Event.stopObserving(document, "mouseup", this.eventMouseUp);
  4740. Event.stopObserving(document, "mousemove", this.eventMouseMove);
  4741. Event.stopObserving(document, "keypress", this.eventKeypress);
  4742. }
  4743. },
  4744. activate: function(draggable) {
  4745. if(draggable.options.delay) {
  4746. this._timeout = setTimeout(function() {
  4747. Draggables._timeout = null;
  4748. window.focus();
  4749. Draggables.activeDraggable = draggable;
  4750. }.bind(this), draggable.options.delay);
  4751. } else {
  4752. window.focus(); // allows keypress events if window isn't currently focused, fails for Safari
  4753. this.activeDraggable = draggable;
  4754. }
  4755. },
  4756. deactivate: function() {
  4757. this.activeDraggable = null;
  4758. },
  4759. updateDrag: function(event) {
  4760. if(!this.activeDraggable) return;
  4761. var pointer = [Event.pointerX(event), Event.pointerY(event)];
  4762. // Mozilla-based browsers fire successive mousemove events with
  4763. // the same coordinates, prevent needless redrawing (moz bug?)
  4764. if(this._lastPointer && (this._lastPointer.inspect() == pointer.inspect())) return;
  4765. this._lastPointer = pointer;
  4766. this.activeDraggable.updateDrag(event, pointer);
  4767. },
  4768. endDrag: function(event) {
  4769. if(this._timeout) {
  4770. clearTimeout(this._timeout);
  4771. this._timeout = null;
  4772. }
  4773. if(!this.activeDraggable) return;
  4774. this._lastPointer = null;
  4775. this.activeDraggable.endDrag(event);
  4776. this.activeDraggable = null;
  4777. },
  4778. keyPress: function(event) {
  4779. if(this.activeDraggable)
  4780. this.activeDraggable.keyPress(event);
  4781. },
  4782. addObserver: function(observer) {
  4783. this.observers.push(observer);
  4784. this._cacheObserverCallbacks();
  4785. },
  4786. removeObserver: function(element) { // element instead of observer fixes mem leaks
  4787. this.observers = this.observers.reject( function(o) { return o.element==element });
  4788. this._cacheObserverCallbacks();
  4789. },
  4790. notify: function(eventName, draggable, event) { // 'onStart', 'onEnd', 'onDrag'
  4791. if(this[eventName+'Count'] > 0)
  4792. this.observers.each( function(o) {
  4793. if(o[eventName]) o[eventName](eventName, draggable, event);
  4794. });
  4795. if(draggable.options[eventName]) draggable.options[eventName](draggable, event);
  4796. },
  4797. _cacheObserverCallbacks: function() {
  4798. ['onStart','onEnd','onDrag'].each( function(eventName) {
  4799. Draggables[eventName+'Count'] = Draggables.observers.select(
  4800. function(o) { return o[eventName]; }
  4801. ).length;
  4802. });
  4803. }
  4804. };
  4805. /*--------------------------------------------------------------------------*/
  4806. var Draggable = Class.create({
  4807. initialize: function(element) {
  4808. var defaults = {
  4809. handle: false,
  4810. reverteffect: function(element, top_offset, left_offset) {
  4811. var dur = Math.sqrt(Math.abs(top_offset^2)+Math.abs(left_offset^2))*0.02;
  4812. new Effect.Move(element, { x: -left_offset, y: -top_offset, duration: dur,
  4813. queue: {scope:'_draggable', position:'end'}
  4814. });
  4815. },
  4816. endeffect: function(element) {
  4817. var toOpacity = Object.isNumber(element._opacity) ? element._opacity : 1.0;
  4818. new Effect.Opacity(element, {duration:0.2, from:0.7, to:toOpacity,
  4819. queue: {scope:'_draggable', position:'end'},
  4820. afterFinish: function(){
  4821. Draggable._dragging[element] = false
  4822. }
  4823. });
  4824. },
  4825. zindex: 1000,
  4826. revert: false,
  4827. quiet: false,
  4828. scroll: false,
  4829. scrollSensitivity: 20,
  4830. scrollSpeed: 15,
  4831. snap: false, // false, or xy or [x,y] or function(x,y){ return [x,y] }
  4832. delay: 0
  4833. };
  4834. if(!arguments[1] || Object.isUndefined(arguments[1].endeffect))
  4835. Object.extend(defaults, {
  4836. starteffect: function(element) {
  4837. element._opacity = Element.getOpacity(element);
  4838. Draggable._dragging[element] = true;
  4839. new Effect.Opacity(element, {duration:0.2, from:element._opacity, to:0.7});
  4840. }
  4841. });
  4842. var options = Object.extend(defaults, arguments[1] || { });
  4843. this.element = $(element);
  4844. if(options.handle && Object.isString(options.handle))
  4845. this.handle = this.element.down('.'+options.handle, 0);
  4846. if(!this.handle) this.handle = $(options.handle);
  4847. if(!this.handle) this.handle = this.element;
  4848. if(options.scroll && !options.scroll.scrollTo && !options.scroll.outerHTML) {
  4849. options.scroll = $(options.scroll);
  4850. this._isScrollChild = Element.childOf(this.element, options.scroll);
  4851. }
  4852. Element.makePositioned(this.element); // fix IE
  4853. this.options = options;
  4854. this.dragging = false;
  4855. this.eventMouseDown = this.initDrag.bindAsEventListener(this);
  4856. Event.observe(this.handle, "mousedown", this.eventMouseDown);
  4857. Draggables.register(this);
  4858. },
  4859. destroy: function() {
  4860. Event.stopObserving(this.handle, "mousedown", this.eventMouseDown);
  4861. Draggables.unregister(this);
  4862. },
  4863. currentDelta: function() {
  4864. return([
  4865. parseInt(Element.getStyle(this.element,'left') || '0'),
  4866. parseInt(Element.getStyle(this.element,'top') || '0')]);
  4867. },
  4868. initDrag: function(event) {
  4869. if(!Object.isUndefined(Draggable._dragging[this.element]) &&
  4870. Draggable._dragging[this.element]) return;
  4871. if(Event.isLeftClick(event)) {
  4872. // abort on form elements, fixes a Firefox issue
  4873. var src = Event.element(event);
  4874. if((tag_name = src.tagName.toUpperCase()) && (
  4875. tag_name=='INPUT' ||
  4876. tag_name=='SELECT' ||
  4877. tag_name=='OPTION' ||
  4878. tag_name=='BUTTON' ||
  4879. tag_name=='TEXTAREA')) return;
  4880. var pointer = [Event.pointerX(event), Event.pointerY(event)];
  4881. var pos = Position.cumulativeOffset(this.element);
  4882. this.offset = [0,1].map( function(i) { return (pointer[i] - pos[i]) });
  4883. Draggables.activate(this);
  4884. Event.stop(event);
  4885. }
  4886. },
  4887. startDrag: function(event) {
  4888. this.dragging = true;
  4889. if(!this.delta)
  4890. this.delta = this.currentDelta();
  4891. if(this.options.zindex) {
  4892. this.originalZ = parseInt(Element.getStyle(this.element,'z-index') || 0);
  4893. this.element.style.zIndex = this.options.zindex;
  4894. }
  4895. if(this.options.ghosting) {
  4896. this._clone = this.element.cloneNode(true);
  4897. this._originallyAbsolute = (this.element.getStyle('position') == 'absolute');
  4898. if (!this._originallyAbsolute)
  4899. Position.absolutize(this.element);
  4900. this.element.parentNode.insertBefore(this._clone, this.element);
  4901. }
  4902. if(this.options.scroll) {
  4903. if (this.options.scroll == window) {
  4904. var where = this._getWindowScroll(this.options.scroll);
  4905. this.originalScrollLeft = where.left;
  4906. this.originalScrollTop = where.top;
  4907. } else {
  4908. this.originalScrollLeft = this.options.scroll.scrollLeft;
  4909. this.originalScrollTop = this.options.scroll.scrollTop;
  4910. }
  4911. }
  4912. Draggables.notify('onStart', this, event);
  4913. if(this.options.starteffect) this.options.starteffect(this.element);
  4914. },
  4915. updateDrag: function(event, pointer) {
  4916. if(!this.dragging) this.startDrag(event);
  4917. if(!this.options.quiet){
  4918. Position.prepare();
  4919. Droppables.show(pointer, this.element);
  4920. }
  4921. Draggables.notify('onDrag', this, event);
  4922. this.draw(pointer);
  4923. if(this.options.change) this.options.change(this);
  4924. if(this.options.scroll) {
  4925. this.stopScrolling();
  4926. var p;
  4927. if (this.options.scroll == window) {
  4928. with(this._getWindowScroll(this.options.scroll)) { p = [ left, top, left+width, top+height ]; }
  4929. } else {
  4930. p = Position.page(this.options.scroll);
  4931. p[0] += this.options.scroll.scrollLeft + Position.deltaX;
  4932. p[1] += this.options.scroll.scrollTop + Position.deltaY;
  4933. p.push(p[0]+this.options.scroll.offsetWidth);
  4934. p.push(p[1]+this.options.scroll.offsetHeight);
  4935. }
  4936. var speed = [0,0];
  4937. if(pointer[0] < (p[0]+this.options.scrollSensitivity)) speed[0] = pointer[0]-(p[0]+this.options.scrollSensitivity);
  4938. if(pointer[1] < (p[1]+this.options.scrollSensitivity)) speed[1] = pointer[1]-(p[1]+this.options.scrollSensitivity);
  4939. if(pointer[0] > (p[2]-this.options.scrollSensitivity)) speed[0] = pointer[0]-(p[2]-this.options.scrollSensitivity);
  4940. if(pointer[1] > (p[3]-this.options.scrollSensitivity)) speed[1] = pointer[1]-(p[3]-this.options.scrollSensitivity);
  4941. this.startScrolling(speed);
  4942. }
  4943. // fix AppleWebKit rendering
  4944. if(Prototype.Browser.WebKit) window.scrollBy(0,0);
  4945. Event.stop(event);
  4946. },
  4947. finishDrag: function(event, success) {
  4948. this.dragging = false;
  4949. if(this.options.quiet){
  4950. Position.prepare();
  4951. var pointer = [Event.pointerX(event), Event.pointerY(event)];
  4952. Droppables.show(pointer, this.element);
  4953. }
  4954. if(this.options.ghosting) {
  4955. if (!this._originallyAbsolute)
  4956. Position.relativize(this.element);
  4957. delete this._originallyAbsolute;
  4958. Element.remove(this._clone);
  4959. this._clone = null;
  4960. }
  4961. var dropped = false;
  4962. if(success) {
  4963. dropped = Droppables.fire(event, this.element);
  4964. if (!dropped) dropped = false;
  4965. }
  4966. if(dropped && this.options.onDropped) this.options.onDropped(this.element);
  4967. Draggables.notify('onEnd', this, event);
  4968. var revert = this.options.revert;
  4969. if(revert && Object.isFunction(revert)) revert = revert(this.element);
  4970. var d = this.currentDelta();
  4971. if(revert && this.options.reverteffect) {
  4972. if (dropped == 0 || revert != 'failure')
  4973. this.options.reverteffect(this.element,
  4974. d[1]-this.delta[1], d[0]-this.delta[0]);
  4975. } else {
  4976. this.delta = d;
  4977. }
  4978. if(this.options.zindex)
  4979. this.element.style.zIndex = this.originalZ;
  4980. if(this.options.endeffect)
  4981. this.options.endeffect(this.element);
  4982. Draggables.deactivate(this);
  4983. Droppables.reset();
  4984. },
  4985. keyPress: function(event) {
  4986. if(event.keyCode!=Event.KEY_ESC) return;
  4987. this.finishDrag(event, false);
  4988. Event.stop(event);
  4989. },
  4990. endDrag: function(event) {
  4991. if(!this.dragging) return;
  4992. this.stopScrolling();
  4993. this.finishDrag(event, true);
  4994. Event.stop(event);
  4995. },
  4996. draw: function(point) {
  4997. var pos = Position.cumulativeOffset(this.element);
  4998. if(this.options.ghosting) {
  4999. var r = Position.realOffset(this.element);
  5000. pos[0] += r[0] - Position.deltaX; pos[1] += r[1] - Position.deltaY;
  5001. }
  5002. var d = this.currentDelta();
  5003. pos[0] -= d[0]; pos[1] -= d[1];
  5004. if(this.options.scroll && (this.options.scroll != window && this._isScrollChild)) {
  5005. pos[0] -= this.options.scroll.scrollLeft-this.originalScrollLeft;
  5006. pos[1] -= this.options.scroll.scrollTop-this.originalScrollTop;
  5007. }
  5008. var p = [0,1].map(function(i){
  5009. return (point[i]-pos[i]-this.offset[i])
  5010. }.bind(this));
  5011. if(this.options.snap) {
  5012. if(Object.isFunction(this.options.snap)) {
  5013. p = this.options.snap(p[0],p[1],this);
  5014. } else {
  5015. if(Object.isArray(this.options.snap)) {
  5016. p = p.map( function(v, i) {
  5017. return (v/this.options.snap[i]).round()*this.options.snap[i] }.bind(this));
  5018. } else {
  5019. p = p.map( function(v) {
  5020. return (v/this.options.snap).round()*this.options.snap }.bind(this));
  5021. }
  5022. }}
  5023. var style = this.element.style;
  5024. if((!this.options.constraint) || (this.options.constraint=='horizontal'))
  5025. style.left = p[0] + "px";
  5026. if((!this.options.constraint) || (this.options.constraint=='vertical'))
  5027. style.top = p[1] + "px";
  5028. if(style.visibility=="hidden") style.visibility = ""; // fix gecko rendering
  5029. },
  5030. stopScrolling: function() {
  5031. if(this.scrollInterval) {
  5032. clearInterval(this.scrollInterval);
  5033. this.scrollInterval = null;
  5034. Draggables._lastScrollPointer = null;
  5035. }
  5036. },
  5037. startScrolling: function(speed) {
  5038. if(!(speed[0] || speed[1])) return;
  5039. this.scrollSpeed = [speed[0]*this.options.scrollSpeed,speed[1]*this.options.scrollSpeed];
  5040. this.lastScrolled = new Date();
  5041. this.scrollInterval = setInterval(this.scroll.bind(this), 10);
  5042. },
  5043. scroll: function() {
  5044. var current = new Date();
  5045. var delta = current - this.lastScrolled;
  5046. this.lastScrolled = current;
  5047. if(this.options.scroll == window) {
  5048. with (this._getWindowScroll(this.options.scroll)) {
  5049. if (this.scrollSpeed[0] || this.scrollSpeed[1]) {
  5050. var d = delta / 1000;
  5051. this.options.scroll.scrollTo( left + d*this.scrollSpeed[0], top + d*this.scrollSpeed[1] );
  5052. }
  5053. }
  5054. } else {
  5055. this.options.scroll.scrollLeft += this.scrollSpeed[0] * delta / 1000;
  5056. this.options.scroll.scrollTop += this.scrollSpeed[1] * delta / 1000;
  5057. }
  5058. Position.prepare();
  5059. Droppables.show(Draggables._lastPointer, this.element);
  5060. Draggables.notify('onDrag', this);
  5061. if (this._isScrollChild) {
  5062. Draggables._lastScrollPointer = Draggables._lastScrollPointer || $A(Draggables._lastPointer);
  5063. Draggables._lastScrollPointer[0] += this.scrollSpeed[0] * delta / 1000;
  5064. Draggables._lastScrollPointer[1] += this.scrollSpeed[1] * delta / 1000;
  5065. if (Draggables._lastScrollPointer[0] < 0)
  5066. Draggables._lastScrollPointer[0] = 0;
  5067. if (Draggables._lastScrollPointer[1] < 0)
  5068. Draggables._lastScrollPointer[1] = 0;
  5069. this.draw(Draggables._lastScrollPointer);
  5070. }
  5071. if(this.options.change) this.options.change(this);
  5072. },
  5073. _getWindowScroll: function(w) {
  5074. var T, L, W, H;
  5075. with (w.document) {
  5076. if (w.document.documentElement && documentElement.scrollTop) {
  5077. T = documentElement.scrollTop;
  5078. L = documentElement.scrollLeft;
  5079. } else if (w.document.body) {
  5080. T = body.scrollTop;
  5081. L = body.scrollLeft;
  5082. }
  5083. if (w.innerWidth) {
  5084. W = w.innerWidth;
  5085. H = w.innerHeight;
  5086. } else if (w.document.documentElement && documentElement.clientWidth) {
  5087. W = documentElement.clientWidth;
  5088. H = documentElement.clientHeight;
  5089. } else {
  5090. W = body.offsetWidth;
  5091. H = body.offsetHeight;
  5092. }
  5093. }
  5094. return { top: T, left: L, width: W, height: H };
  5095. }
  5096. });
  5097. Draggable._dragging = { };
  5098. /*--------------------------------------------------------------------------*/
  5099. var SortableObserver = Class.create({
  5100. initialize: function(element, observer) {
  5101. this.element = $(element);
  5102. this.observer = observer;
  5103. this.lastValue = Sortable.serialize(this.element);
  5104. },
  5105. onStart: function() {
  5106. this.lastValue = Sortable.serialize(this.element);
  5107. },
  5108. onEnd: function() {
  5109. Sortable.unmark();
  5110. if(this.lastValue != Sortable.serialize(this.element))
  5111. this.observer(this.element)
  5112. }
  5113. });
  5114. var Sortable = {
  5115. SERIALIZE_RULE: /^[^_\-](?:[A-Za-z0-9\-\_]*)[_](.*)$/,
  5116. sortables: { },
  5117. _findRootElement: function(element) {
  5118. while (element.tagName.toUpperCase() != "BODY") {
  5119. if(element.id && Sortable.sortables[element.id]) return element;
  5120. element = element.parentNode;
  5121. }
  5122. },
  5123. options: function(element) {
  5124. element = Sortable._findRootElement($(element));
  5125. if(!element) return;
  5126. return Sortable.sortables[element.id];
  5127. },
  5128. destroy: function(element){
  5129. element = $(element);
  5130. var s = Sortable.sortables[element.id];
  5131. if(s) {
  5132. Draggables.removeObserver(s.element);
  5133. s.droppables.each(function(d){ Droppables.remove(d) });
  5134. s.draggables.invoke('destroy');
  5135. delete Sortable.sortables[s.element.id];
  5136. }
  5137. },
  5138. create: function(element) {
  5139. element = $(element);
  5140. var options = Object.extend({
  5141. element: element,
  5142. tag: 'li', // assumes li children, override with tag: 'tagname'
  5143. dropOnEmpty: false,
  5144. tree: false,
  5145. treeTag: 'ul',
  5146. overlap: 'vertical', // one of 'vertical', 'horizontal'
  5147. constraint: 'vertical', // one of 'vertical', 'horizontal', false
  5148. containment: element, // also takes array of elements (or id's); or false
  5149. handle: false, // or a CSS class
  5150. only: false,
  5151. delay: 0,
  5152. hoverclass: null,
  5153. ghosting: false,
  5154. quiet: false,
  5155. scroll: false,
  5156. scrollSensitivity: 20,
  5157. scrollSpeed: 15,
  5158. format: this.SERIALIZE_RULE,
  5159. // these take arrays of elements or ids and can be
  5160. // used for better initialization performance
  5161. elements: false,
  5162. handles: false,
  5163. onChange: Prototype.emptyFunction,
  5164. onUpdate: Prototype.emptyFunction
  5165. }, arguments[1] || { });
  5166. // clear any old sortable with same element
  5167. this.destroy(element);
  5168. // build options for the draggables
  5169. var options_for_draggable = {
  5170. revert: true,
  5171. quiet: options.quiet,
  5172. scroll: options.scroll,
  5173. scrollSpeed: options.scrollSpeed,
  5174. scrollSensitivity: options.scrollSensitivity,
  5175. delay: options.delay,
  5176. ghosting: options.ghosting,
  5177. constraint: options.constraint,
  5178. handle: options.handle };
  5179. if(options.starteffect)
  5180. options_for_draggable.starteffect = options.starteffect;
  5181. if(options.reverteffect)
  5182. options_for_draggable.reverteffect = options.reverteffect;
  5183. else
  5184. if(options.ghosting) options_for_draggable.reverteffect = function(element) {
  5185. element.style.top = 0;
  5186. element.style.left = 0;
  5187. };
  5188. if(options.endeffect)
  5189. options_for_draggable.endeffect = options.endeffect;
  5190. if(options.zindex)
  5191. options_for_draggable.zindex = options.zindex;
  5192. // build options for the droppables
  5193. var options_for_droppable = {
  5194. overlap: options.overlap,
  5195. containment: options.containment,
  5196. tree: options.tree,
  5197. hoverclass: options.hoverclass,
  5198. onHover: Sortable.onHover
  5199. };
  5200. var options_for_tree = {
  5201. onHover: Sortable.onEmptyHover,
  5202. overlap: options.overlap,
  5203. containment: options.containment,
  5204. hoverclass: options.hoverclass
  5205. };
  5206. // fix for gecko engine
  5207. Element.cleanWhitespace(element);
  5208. options.draggables = [];
  5209. options.droppables = [];
  5210. // drop on empty handling
  5211. if(options.dropOnEmpty || options.tree) {
  5212. Droppables.add(element, options_for_tree);
  5213. options.droppables.push(element);
  5214. }
  5215. (options.elements || this.findElements(element, options) || []).each( function(e,i) {
  5216. var handle = options.handles ? $(options.handles[i]) :
  5217. (options.handle ? $(e).select('.' + options.handle)[0] : e);
  5218. options.draggables.push(
  5219. new Draggable(e, Object.extend(options_for_draggable, { handle: handle })));
  5220. Droppables.add(e, options_for_droppable);
  5221. if(options.tree) e.treeNode = element;
  5222. options.droppables.push(e);
  5223. });
  5224. if(options.tree) {
  5225. (Sortable.findTreeElements(element, options) || []).each( function(e) {
  5226. Droppables.add(e, options_for_tree);
  5227. e.treeNode = element;
  5228. options.droppables.push(e);
  5229. });
  5230. }
  5231. // keep reference
  5232. this.sortables[element.id] = options;
  5233. // for onupdate
  5234. Draggables.addObserver(new SortableObserver(element, options.onUpdate));
  5235. },
  5236. // return all suitable-for-sortable elements in a guaranteed order
  5237. findElements: function(element, options) {
  5238. return Element.findChildren(
  5239. element, options.only, options.tree ? true : false, options.tag);
  5240. },
  5241. findTreeElements: function(element, options) {
  5242. return Element.findChildren(
  5243. element, options.only, options.tree ? true : false, options.treeTag);
  5244. },
  5245. onHover: function(element, dropon, overlap) {
  5246. if(Element.isParent(dropon, element)) return;
  5247. if(overlap > .33 && overlap < .66 && Sortable.options(dropon).tree) {
  5248. return;
  5249. } else if(overlap>0.5) {
  5250. Sortable.mark(dropon, 'before');
  5251. if(dropon.previousSibling != element) {
  5252. var oldParentNode = element.parentNode;
  5253. element.style.visibility = "hidden"; // fix gecko rendering
  5254. dropon.parentNode.insertBefore(element, dropon);
  5255. if(dropon.parentNode!=oldParentNode)
  5256. Sortable.options(oldParentNode).onChange(element);
  5257. Sortable.options(dropon.parentNode).onChange(element);
  5258. }
  5259. } else {
  5260. Sortable.mark(dropon, 'after');
  5261. var nextElement = dropon.nextSibling || null;
  5262. if(nextElement != element) {
  5263. var oldParentNode = element.parentNode;
  5264. element.style.visibility = "hidden"; // fix gecko rendering
  5265. dropon.parentNode.insertBefore(element, nextElement);
  5266. if(dropon.parentNode!=oldParentNode)
  5267. Sortable.options(oldParentNode).onChange(element);
  5268. Sortable.options(dropon.parentNode).onChange(element);
  5269. }
  5270. }
  5271. },
  5272. onEmptyHover: function(element, dropon, overlap) {
  5273. var oldParentNode = element.parentNode;
  5274. var droponOptions = Sortable.options(dropon);
  5275. if(!Element.isParent(dropon, element)) {
  5276. var index;
  5277. var children = Sortable.findElements(dropon, {tag: droponOptions.tag, only: droponOptions.only});
  5278. var child = null;
  5279. if(children) {
  5280. var offset = Element.offsetSize(dropon, droponOptions.overlap) * (1.0 - overlap);
  5281. for (index = 0; index < children.length; index += 1) {
  5282. if (offset - Element.offsetSize (children[index], droponOptions.overlap) >= 0) {
  5283. offset -= Element.offsetSize (children[index], droponOptions.overlap);
  5284. } else if (offset - (Element.offsetSize (children[index], droponOptions.overlap) / 2) >= 0) {
  5285. child = index + 1 < children.length ? children[index + 1] : null;
  5286. break;
  5287. } else {
  5288. child = children[index];
  5289. break;
  5290. }
  5291. }
  5292. }
  5293. dropon.insertBefore(element, child);
  5294. Sortable.options(oldParentNode).onChange(element);
  5295. droponOptions.onChange(element);
  5296. }
  5297. },
  5298. unmark: function() {
  5299. if(Sortable._marker) Sortable._marker.hide();
  5300. },
  5301. mark: function(dropon, position) {
  5302. // mark on ghosting only
  5303. var sortable = Sortable.options(dropon.parentNode);
  5304. if(sortable && !sortable.ghosting) return;
  5305. if(!Sortable._marker) {
  5306. Sortable._marker =
  5307. ($('dropmarker') || Element.extend(document.createElement('DIV'))).
  5308. hide().addClassName('dropmarker').setStyle({position:'absolute'});
  5309. document.getElementsByTagName("body").item(0).appendChild(Sortable._marker);
  5310. }
  5311. var offsets = Position.cumulativeOffset(dropon);
  5312. Sortable._marker.setStyle({left: offsets[0]+'px', top: offsets[1] + 'px'});
  5313. if(position=='after')
  5314. if(sortable.overlap == 'horizontal')
  5315. Sortable._marker.setStyle({left: (offsets[0]+dropon.clientWidth) + 'px'});
  5316. else
  5317. Sortable._marker.setStyle({top: (offsets[1]+dropon.clientHeight) + 'px'});
  5318. Sortable._marker.show();
  5319. },
  5320. _tree: function(element, options, parent) {
  5321. var children = Sortable.findElements(element, options) || [];
  5322. for (var i = 0; i < children.length; ++i) {
  5323. var match = children[i].id.match(options.format);
  5324. if (!match) continue;
  5325. var child = {
  5326. id: encodeURIComponent(match ? match[1] : null),
  5327. element: element,
  5328. parent: parent,
  5329. children: [],
  5330. position: parent.children.length,
  5331. container: $(children[i]).down(options.treeTag)
  5332. };
  5333. /* Get the element containing the children and recurse over it */
  5334. if (child.container)
  5335. this._tree(child.container, options, child);
  5336. parent.children.push (child);
  5337. }
  5338. return parent;
  5339. },
  5340. tree: function(element) {
  5341. element = $(element);
  5342. var sortableOptions = this.options(element);
  5343. var options = Object.extend({
  5344. tag: sortableOptions.tag,
  5345. treeTag: sortableOptions.treeTag,
  5346. only: sortableOptions.only,
  5347. name: element.id,
  5348. format: sortableOptions.format
  5349. }, arguments[1] || { });
  5350. var root = {
  5351. id: null,
  5352. parent: null,
  5353. children: [],
  5354. container: element,
  5355. position: 0
  5356. };
  5357. return Sortable._tree(element, options, root);
  5358. },
  5359. /* Construct a [i] index for a particular node */
  5360. _constructIndex: function(node) {
  5361. var index = '';
  5362. do {
  5363. if (node.id) index = '[' + node.position + ']' + index;
  5364. } while ((node = node.parent) != null);
  5365. return index;
  5366. },
  5367. sequence: function(element) {
  5368. element = $(element);
  5369. var options = Object.extend(this.options(element), arguments[1] || { });
  5370. return $(this.findElements(element, options) || []).map( function(item) {
  5371. return item.id.match(options.format) ? item.id.match(options.format)[1] : '';
  5372. });
  5373. },
  5374. setSequence: function(element, new_sequence) {
  5375. element = $(element);
  5376. var options = Object.extend(this.options(element), arguments[2] || { });
  5377. var nodeMap = { };
  5378. this.findElements(element, options).each( function(n) {
  5379. if (n.id.match(options.format))
  5380. nodeMap[n.id.match(options.format)[1]] = [n, n.parentNode];
  5381. n.parentNode.removeChild(n);
  5382. });
  5383. new_sequence.each(function(ident) {
  5384. var n = nodeMap[ident];
  5385. if (n) {
  5386. n[1].appendChild(n[0]);
  5387. delete nodeMap[ident];
  5388. }
  5389. });
  5390. },
  5391. serialize: function(element) {
  5392. element = $(element);
  5393. var options = Object.extend(Sortable.options(element), arguments[1] || { });
  5394. var name = encodeURIComponent(
  5395. (arguments[1] && arguments[1].name) ? arguments[1].name : element.id);
  5396. if (options.tree) {
  5397. return Sortable.tree(element, arguments[1]).children.map( function (item) {
  5398. return [name + Sortable._constructIndex(item) + "[id]=" +
  5399. encodeURIComponent(item.id)].concat(item.children.map(arguments.callee));
  5400. }).flatten().join('&');
  5401. } else {
  5402. return Sortable.sequence(element, arguments[1]).map( function(item) {
  5403. return name + "[]=" + encodeURIComponent(item);
  5404. }).join('&');
  5405. }
  5406. }
  5407. };
  5408. // Returns true if child is contained within element
  5409. Element.isParent = function(child, element) {
  5410. if (!child.parentNode || child == element) return false;
  5411. if (child.parentNode == element) return true;
  5412. return Element.isParent(child.parentNode, element);
  5413. };
  5414. Element.findChildren = function(element, only, recursive, tagName) {
  5415. if(!element.hasChildNodes()) return null;
  5416. tagName = tagName.toUpperCase();
  5417. if(only) only = [only].flatten();
  5418. var elements = [];
  5419. $A(element.childNodes).each( function(e) {
  5420. if(e.tagName && e.tagName.toUpperCase()==tagName &&
  5421. (!only || (Element.classNames(e).detect(function(v) { return only.include(v) }))))
  5422. elements.push(e);
  5423. if(recursive) {
  5424. var grandchildren = Element.findChildren(e, only, recursive, tagName);
  5425. if(grandchildren) elements.push(grandchildren);
  5426. }
  5427. });
  5428. return (elements.length>0 ? elements.flatten() : []);
  5429. };
  5430. Element.offsetSize = function (element, type) {
  5431. return element['offset' + ((type=='vertical' || type=='height') ? 'Height' : 'Width')];
  5432. };// script.aculo.us controls.js v1.8.2, Tue Nov 18 18:30:58 +0100 2008
  5433. // Copyright (c) 2005-2008 Thomas Fuchs (http://script.aculo.us, http://mir.aculo.us)
  5434. // (c) 2005-2008 Ivan Krstic (http://blogs.law.harvard.edu/ivan)
  5435. // (c) 2005-2008 Jon Tirsen (http://www.tirsen.com)
  5436. // Contributors:
  5437. // Richard Livsey
  5438. // Rahul Bhargava
  5439. // Rob Wills
  5440. //
  5441. // script.aculo.us is freely distributable under the terms of an MIT-style license.
  5442. // For details, see the script.aculo.us web site: http://script.aculo.us/
  5443. // Autocompleter.Base handles all the autocompletion functionality
  5444. // that's independent of the data source for autocompletion. This
  5445. // includes drawing the autocompletion menu, observing keyboard
  5446. // and mouse events, and similar.
  5447. //
  5448. // Specific autocompleters need to provide, at the very least,
  5449. // a getUpdatedChoices function that will be invoked every time
  5450. // the text inside the monitored textbox changes. This method
  5451. // should get the text for which to provide autocompletion by
  5452. // invoking this.getToken(), NOT by directly accessing
  5453. // this.element.value. This is to allow incremental tokenized
  5454. // autocompletion. Specific auto-completion logic (AJAX, etc)
  5455. // belongs in getUpdatedChoices.
  5456. //
  5457. // Tokenized incremental autocompletion is enabled automatically
  5458. // when an autocompleter is instantiated with the 'tokens' option
  5459. // in the options parameter, e.g.:
  5460. // new Ajax.Autocompleter('id','upd', '/url/', { tokens: ',' });
  5461. // will incrementally autocomplete with a comma as the token.
  5462. // Additionally, ',' in the above example can be replaced with
  5463. // a token array, e.g. { tokens: [',', '\n'] } which
  5464. // enables autocompletion on multiple tokens. This is most
  5465. // useful when one of the tokens is \n (a newline), as it
  5466. // allows smart autocompletion after linebreaks.
  5467. if(typeof Effect == 'undefined')
  5468. throw("controls.js requires including script.aculo.us' effects.js library");
  5469. var Autocompleter = { };
  5470. Autocompleter.Base = Class.create({
  5471. baseInitialize: function(element, update, options) {
  5472. element = $(element);
  5473. this.element = element;
  5474. this.update = $(update);
  5475. this.hasFocus = false;
  5476. this.changed = false;
  5477. this.active = false;
  5478. this.index = 0;
  5479. this.entryCount = 0;
  5480. this.oldElementValue = this.element.value;
  5481. if(this.setOptions)
  5482. this.setOptions(options);
  5483. else
  5484. this.options = options || { };
  5485. this.options.paramName = this.options.paramName || this.element.name;
  5486. this.options.tokens = this.options.tokens || [];
  5487. this.options.frequency = this.options.frequency || 0.4;
  5488. this.options.minChars = this.options.minChars || 1;
  5489. this.options.onShow = this.options.onShow ||
  5490. function(element, update){
  5491. if(!update.style.position || update.style.position=='absolute') {
  5492. update.style.position = 'absolute';
  5493. Position.clone(element, update, {
  5494. setHeight: false,
  5495. offsetTop: element.offsetHeight
  5496. });
  5497. }
  5498. Effect.Appear(update,{duration:0.15});
  5499. };
  5500. this.options.onHide = this.options.onHide ||
  5501. function(element, update){ new Effect.Fade(update,{duration:0.15}) };
  5502. if(typeof(this.options.tokens) == 'string')
  5503. this.options.tokens = new Array(this.options.tokens);
  5504. // Force carriage returns as token delimiters anyway
  5505. if (!this.options.tokens.include('\n'))
  5506. this.options.tokens.push('\n');
  5507. this.observer = null;
  5508. this.element.setAttribute('autocomplete','off');
  5509. Element.hide(this.update);
  5510. Event.observe(this.element, 'blur', this.onBlur.bindAsEventListener(this));
  5511. Event.observe(this.element, 'keydown', this.onKeyPress.bindAsEventListener(this));
  5512. },
  5513. show: function() {
  5514. if(Element.getStyle(this.update, 'display')=='none') this.options.onShow(this.element, this.update);
  5515. if(!this.iefix &&
  5516. (Prototype.Browser.IE) &&
  5517. (Element.getStyle(this.update, 'position')=='absolute')) {
  5518. new Insertion.After(this.update,
  5519. '<iframe id="' + this.update.id + '_iefix" '+
  5520. 'style="display:none;position:absolute;filter:progid:DXImageTransform.Microsoft.Alpha(opacity=0);" ' +
  5521. 'src="javascript:false;" frameborder="0" scrolling="no"></iframe>');
  5522. this.iefix = $(this.update.id+'_iefix');
  5523. }
  5524. if(this.iefix) setTimeout(this.fixIEOverlapping.bind(this), 50);
  5525. },
  5526. fixIEOverlapping: function() {
  5527. Position.clone(this.update, this.iefix, {setTop:(!this.update.style.height)});
  5528. this.iefix.style.zIndex = 1;
  5529. this.update.style.zIndex = 2;
  5530. Element.show(this.iefix);
  5531. },
  5532. hide: function() {
  5533. this.stopIndicator();
  5534. if(Element.getStyle(this.update, 'display')!='none') this.options.onHide(this.element, this.update);
  5535. if(this.iefix) Element.hide(this.iefix);
  5536. },
  5537. startIndicator: function() {
  5538. if(this.options.indicator) Element.show(this.options.indicator);
  5539. },
  5540. stopIndicator: function() {
  5541. if(this.options.indicator) Element.hide(this.options.indicator);
  5542. },
  5543. onKeyPress: function(event) {
  5544. if(this.active)
  5545. switch(event.keyCode) {
  5546. case Event.KEY_TAB:
  5547. case Event.KEY_RETURN:
  5548. this.selectEntry();
  5549. Event.stop(event);
  5550. case Event.KEY_ESC:
  5551. this.hide();
  5552. this.active = false;
  5553. Event.stop(event);
  5554. return;
  5555. case Event.KEY_LEFT:
  5556. case Event.KEY_RIGHT:
  5557. return;
  5558. case Event.KEY_UP:
  5559. this.markPrevious();
  5560. this.render();
  5561. Event.stop(event);
  5562. return;
  5563. case Event.KEY_DOWN:
  5564. this.markNext();
  5565. this.render();
  5566. Event.stop(event);
  5567. return;
  5568. }
  5569. else
  5570. if(event.keyCode==Event.KEY_TAB || event.keyCode==Event.KEY_RETURN ||
  5571. (Prototype.Browser.WebKit > 0 && event.keyCode == 0)) return;
  5572. this.changed = true;
  5573. this.hasFocus = true;
  5574. if(this.observer) clearTimeout(this.observer);
  5575. this.observer =
  5576. setTimeout(this.onObserverEvent.bind(this), this.options.frequency*1000);
  5577. },
  5578. activate: function() {
  5579. this.changed = false;
  5580. this.hasFocus = true;
  5581. this.getUpdatedChoices();
  5582. },
  5583. onHover: function(event) {
  5584. var element = Event.findElement(event, 'LI');
  5585. if(this.index != element.autocompleteIndex)
  5586. {
  5587. this.index = element.autocompleteIndex;
  5588. this.render();
  5589. }
  5590. Event.stop(event);
  5591. },
  5592. onClick: function(event) {
  5593. var element = Event.findElement(event, 'LI');
  5594. this.index = element.autocompleteIndex;
  5595. this.selectEntry();
  5596. this.hide();
  5597. },
  5598. onBlur: function(event) {
  5599. // needed to make click events working
  5600. setTimeout(this.hide.bind(this), 250);
  5601. this.hasFocus = false;
  5602. this.active = false;
  5603. },
  5604. render: function() {
  5605. if(this.entryCount > 0) {
  5606. for (var i = 0; i < this.entryCount; i++)
  5607. this.index==i ?
  5608. Element.addClassName(this.getEntry(i),"selected") :
  5609. Element.removeClassName(this.getEntry(i),"selected");
  5610. if(this.hasFocus) {
  5611. this.show();
  5612. this.active = true;
  5613. }
  5614. } else {
  5615. this.active = false;
  5616. this.hide();
  5617. }
  5618. },
  5619. markPrevious: function() {
  5620. if(this.index > 0) this.index--;
  5621. else this.index = this.entryCount-1;
  5622. this.getEntry(this.index).scrollIntoView(true);
  5623. },
  5624. markNext: function() {
  5625. if(this.index < this.entryCount-1) this.index++;
  5626. else this.index = 0;
  5627. this.getEntry(this.index).scrollIntoView(false);
  5628. },
  5629. getEntry: function(index) {
  5630. return this.update.firstChild.childNodes[index];
  5631. },
  5632. getCurrentEntry: function() {
  5633. return this.getEntry(this.index);
  5634. },
  5635. selectEntry: function() {
  5636. this.active = false;
  5637. this.updateElement(this.getCurrentEntry());
  5638. },
  5639. updateElement: function(selectedElement) {
  5640. if (this.options.updateElement) {
  5641. this.options.updateElement(selectedElement);
  5642. return;
  5643. }
  5644. var value = '';
  5645. if (this.options.select) {
  5646. var nodes = $(selectedElement).select('.' + this.options.select) || [];
  5647. if(nodes.length>0) value = Element.collectTextNodes(nodes[0], this.options.select);
  5648. } else
  5649. value = Element.collectTextNodesIgnoreClass(selectedElement, 'informal');
  5650. var bounds = this.getTokenBounds();
  5651. if (bounds[0] != -1) {
  5652. var newValue = this.element.value.substr(0, bounds[0]);
  5653. var whitespace = this.element.value.substr(bounds[0]).match(/^\s+/);
  5654. if (whitespace)
  5655. newValue += whitespace[0];
  5656. this.element.value = newValue + value + this.element.value.substr(bounds[1]);
  5657. } else {
  5658. this.element.value = value;
  5659. }
  5660. this.oldElementValue = this.element.value;
  5661. this.element.focus();
  5662. if (this.options.afterUpdateElement)
  5663. this.options.afterUpdateElement(this.element, selectedElement);
  5664. },
  5665. updateChoices: function(choices) {
  5666. if(!this.changed && this.hasFocus) {
  5667. this.update.innerHTML = choices;
  5668. Element.cleanWhitespace(this.update);
  5669. Element.cleanWhitespace(this.update.down());
  5670. if(this.update.firstChild && this.update.down().childNodes) {
  5671. this.entryCount =
  5672. this.update.down().childNodes.length;
  5673. for (var i = 0; i < this.entryCount; i++) {
  5674. var entry = this.getEntry(i);
  5675. entry.autocompleteIndex = i;
  5676. this.addObservers(entry);
  5677. }
  5678. } else {
  5679. this.entryCount = 0;
  5680. }
  5681. this.stopIndicator();
  5682. this.index = 0;
  5683. if(this.entryCount==1 && this.options.autoSelect) {
  5684. this.selectEntry();
  5685. this.hide();
  5686. } else {
  5687. this.render();
  5688. }
  5689. }
  5690. },
  5691. addObservers: function(element) {
  5692. Event.observe(element, "mouseover", this.onHover.bindAsEventListener(this));
  5693. Event.observe(element, "click", this.onClick.bindAsEventListener(this));
  5694. },
  5695. onObserverEvent: function() {
  5696. this.changed = false;
  5697. this.tokenBounds = null;
  5698. if(this.getToken().length>=this.options.minChars) {
  5699. this.getUpdatedChoices();
  5700. } else {
  5701. this.active = false;
  5702. this.hide();
  5703. }
  5704. this.oldElementValue = this.element.value;
  5705. },
  5706. getToken: function() {
  5707. var bounds = this.getTokenBounds();
  5708. return this.element.value.substring(bounds[0], bounds[1]).strip();
  5709. },
  5710. getTokenBounds: function() {
  5711. if (null != this.tokenBounds) return this.tokenBounds;
  5712. var value = this.element.value;
  5713. if (value.strip().empty()) return [-1, 0];
  5714. var diff = arguments.callee.getFirstDifferencePos(value, this.oldElementValue);
  5715. var offset = (diff == this.oldElementValue.length ? 1 : 0);
  5716. var prevTokenPos = -1, nextTokenPos = value.length;
  5717. var tp;
  5718. for (var index = 0, l = this.options.tokens.length; index < l; ++index) {
  5719. tp = value.lastIndexOf(this.options.tokens[index], diff + offset - 1);
  5720. if (tp > prevTokenPos) prevTokenPos = tp;
  5721. tp = value.indexOf(this.options.tokens[index], diff + offset);
  5722. if (-1 != tp && tp < nextTokenPos) nextTokenPos = tp;
  5723. }
  5724. return (this.tokenBounds = [prevTokenPos + 1, nextTokenPos]);
  5725. }
  5726. });
  5727. Autocompleter.Base.prototype.getTokenBounds.getFirstDifferencePos = function(newS, oldS) {
  5728. var boundary = Math.min(newS.length, oldS.length);
  5729. for (var index = 0; index < boundary; ++index)
  5730. if (newS[index] != oldS[index])
  5731. return index;
  5732. return boundary;
  5733. };
  5734. Ajax.Autocompleter = Class.create(Autocompleter.Base, {
  5735. initialize: function(element, update, url, options) {
  5736. this.baseInitialize(element, update, options);
  5737. this.options.asynchronous = true;
  5738. this.options.onComplete = this.onComplete.bind(this);
  5739. this.options.defaultParams = this.options.parameters || null;
  5740. this.url = url;
  5741. },
  5742. getUpdatedChoices: function() {
  5743. this.startIndicator();
  5744. var entry = encodeURIComponent(this.options.paramName) + '=' +
  5745. encodeURIComponent(this.getToken());
  5746. this.options.parameters = this.options.callback ?
  5747. this.options.callback(this.element, entry) : entry;
  5748. if(this.options.defaultParams)
  5749. this.options.parameters += '&' + this.options.defaultParams;
  5750. new Ajax.Request(this.url, this.options);
  5751. },
  5752. onComplete: function(request) {
  5753. this.updateChoices(request.responseText);
  5754. }
  5755. });
  5756. // The local array autocompleter. Used when you'd prefer to
  5757. // inject an array of autocompletion options into the page, rather
  5758. // than sending out Ajax queries, which can be quite slow sometimes.
  5759. //
  5760. // The constructor takes four parameters. The first two are, as usual,
  5761. // the id of the monitored textbox, and id of the autocompletion menu.
  5762. // The third is the array you want to autocomplete from, and the fourth
  5763. // is the options block.
  5764. //
  5765. // Extra local autocompletion options:
  5766. // - choices - How many autocompletion choices to offer
  5767. //
  5768. // - partialSearch - If false, the autocompleter will match entered
  5769. // text only at the beginning of strings in the
  5770. // autocomplete array. Defaults to true, which will
  5771. // match text at the beginning of any *word* in the
  5772. // strings in the autocomplete array. If you want to
  5773. // search anywhere in the string, additionally set
  5774. // the option fullSearch to true (default: off).
  5775. //
  5776. // - fullSsearch - Search anywhere in autocomplete array strings.
  5777. //
  5778. // - partialChars - How many characters to enter before triggering
  5779. // a partial match (unlike minChars, which defines
  5780. // how many characters are required to do any match
  5781. // at all). Defaults to 2.
  5782. //
  5783. // - ignoreCase - Whether to ignore case when autocompleting.
  5784. // Defaults to true.
  5785. //
  5786. // It's possible to pass in a custom function as the 'selector'
  5787. // option, if you prefer to write your own autocompletion logic.
  5788. // In that case, the other options above will not apply unless
  5789. // you support them.
  5790. Autocompleter.Local = Class.create(Autocompleter.Base, {
  5791. initialize: function(element, update, array, options) {
  5792. this.baseInitialize(element, update, options);
  5793. this.options.array = array;
  5794. },
  5795. getUpdatedChoices: function() {
  5796. this.updateChoices(this.options.selector(this));
  5797. },
  5798. setOptions: function(options) {
  5799. this.options = Object.extend({
  5800. choices: 10,
  5801. partialSearch: true,
  5802. partialChars: 2,
  5803. ignoreCase: true,
  5804. fullSearch: false,
  5805. selector: function(instance) {
  5806. var ret = []; // Beginning matches
  5807. var partial = []; // Inside matches
  5808. var entry = instance.getToken();
  5809. var count = 0;
  5810. for (var i = 0; i < instance.options.array.length &&
  5811. ret.length < instance.options.choices ; i++) {
  5812. var elem = instance.options.array[i];
  5813. var foundPos = instance.options.ignoreCase ?
  5814. elem.toLowerCase().indexOf(entry.toLowerCase()) :
  5815. elem.indexOf(entry);
  5816. while (foundPos != -1) {
  5817. if (foundPos == 0 && elem.length != entry.length) {
  5818. ret.push("<li><strong>" + elem.substr(0, entry.length) + "</strong>" +
  5819. elem.substr(entry.length) + "</li>");
  5820. break;
  5821. } else if (entry.length >= instance.options.partialChars &&
  5822. instance.options.partialSearch && foundPos != -1) {
  5823. if (instance.options.fullSearch || /\s/.test(elem.substr(foundPos-1,1))) {
  5824. partial.push("<li>" + elem.substr(0, foundPos) + "<strong>" +
  5825. elem.substr(foundPos, entry.length) + "</strong>" + elem.substr(
  5826. foundPos + entry.length) + "</li>");
  5827. break;
  5828. }
  5829. }
  5830. foundPos = instance.options.ignoreCase ?
  5831. elem.toLowerCase().indexOf(entry.toLowerCase(), foundPos + 1) :
  5832. elem.indexOf(entry, foundPos + 1);
  5833. }
  5834. }
  5835. if (partial.length)
  5836. ret = ret.concat(partial.slice(0, instance.options.choices - ret.length));
  5837. return "<ul>" + ret.join('') + "</ul>";
  5838. }
  5839. }, options || { });
  5840. }
  5841. });
  5842. // AJAX in-place editor and collection editor
  5843. // Full rewrite by Christophe Porteneuve <tdd@tddsworld.com> (April 2007).
  5844. // Use this if you notice weird scrolling problems on some browsers,
  5845. // the DOM might be a bit confused when this gets called so do this
  5846. // waits 1 ms (with setTimeout) until it does the activation
  5847. Field.scrollFreeActivate = function(field) {
  5848. setTimeout(function() {
  5849. Field.activate(field);
  5850. }, 1);
  5851. };
  5852. Ajax.InPlaceEditor = Class.create({
  5853. initialize: function(element, url, options) {
  5854. this.url = url;
  5855. this.element = element = $(element);
  5856. this.prepareOptions();
  5857. this._controls = { };
  5858. arguments.callee.dealWithDeprecatedOptions(options); // DEPRECATION LAYER!!!
  5859. Object.extend(this.options, options || { });
  5860. if (!this.options.formId && this.element.id) {
  5861. this.options.formId = this.element.id + '-inplaceeditor';
  5862. if ($(this.options.formId))
  5863. this.options.formId = '';
  5864. }
  5865. if (this.options.externalControl)
  5866. this.options.externalControl = $(this.options.externalControl);
  5867. if (!this.options.externalControl)
  5868. this.options.externalControlOnly = false;
  5869. this._originalBackground = this.element.getStyle('background-color') || 'transparent';
  5870. this.element.title = this.options.clickToEditText;
  5871. this._boundCancelHandler = this.handleFormCancellation.bind(this);
  5872. this._boundComplete = (this.options.onComplete || Prototype.emptyFunction).bind(this);
  5873. this._boundFailureHandler = this.handleAJAXFailure.bind(this);
  5874. this._boundSubmitHandler = this.handleFormSubmission.bind(this);
  5875. this._boundWrapperHandler = this.wrapUp.bind(this);
  5876. this.registerListeners();
  5877. },
  5878. checkForEscapeOrReturn: function(e) {
  5879. if (!this._editing || e.ctrlKey || e.altKey || e.shiftKey) return;
  5880. if (Event.KEY_ESC == e.keyCode)
  5881. this.handleFormCancellation(e);
  5882. else if (Event.KEY_RETURN == e.keyCode)
  5883. this.handleFormSubmission(e);
  5884. },
  5885. createControl: function(mode, handler, extraClasses) {
  5886. var control = this.options[mode + 'Control'];
  5887. var text = this.options[mode + 'Text'];
  5888. if ('button' == control) {
  5889. var btn = document.createElement('input');
  5890. btn.type = 'submit';
  5891. btn.value = text;
  5892. btn.className = 'editor_' + mode + '_button';
  5893. if ('cancel' == mode)
  5894. btn.onclick = this._boundCancelHandler;
  5895. this._form.appendChild(btn);
  5896. this._controls[mode] = btn;
  5897. } else if ('link' == control) {
  5898. var link = document.createElement('a');
  5899. link.href = '#';
  5900. link.appendChild(document.createTextNode(text));
  5901. link.onclick = 'cancel' == mode ? this._boundCancelHandler : this._boundSubmitHandler;
  5902. link.className = 'editor_' + mode + '_link';
  5903. if (extraClasses)
  5904. link.className += ' ' + extraClasses;
  5905. this._form.appendChild(link);
  5906. this._controls[mode] = link;
  5907. }
  5908. },
  5909. createEditField: function() {
  5910. var text = (this.options.loadTextURL ? this.options.loadingText : this.getText());
  5911. var fld;
  5912. if (1 >= this.options.rows && !/\r|\n/.test(this.getText())) {
  5913. fld = document.createElement('input');
  5914. fld.type = 'text';
  5915. var size = this.options.size || this.options.cols || 0;
  5916. if (0 < size) fld.size = size;
  5917. } else {
  5918. fld = document.createElement('textarea');
  5919. fld.rows = (1 >= this.options.rows ? this.options.autoRows : this.options.rows);
  5920. fld.cols = this.options.cols || 40;
  5921. }
  5922. fld.name = this.options.paramName;
  5923. fld.value = text; // No HTML breaks conversion anymore
  5924. fld.className = 'editor_field';
  5925. if (this.options.submitOnBlur)
  5926. fld.onblur = this._boundSubmitHandler;
  5927. this._controls.editor = fld;
  5928. if (this.options.loadTextURL)
  5929. this.loadExternalText();
  5930. this._form.appendChild(this._controls.editor);
  5931. },
  5932. createForm: function() {
  5933. var ipe = this;
  5934. function addText(mode, condition) {
  5935. var text = ipe.options['text' + mode + 'Controls'];
  5936. if (!text || condition === false) return;
  5937. ipe._form.appendChild(document.createTextNode(text));
  5938. };
  5939. this._form = $(document.createElement('form'));
  5940. this._form.id = this.options.formId;
  5941. this._form.addClassName(this.options.formClassName);
  5942. this._form.onsubmit = this._boundSubmitHandler;
  5943. this.createEditField();
  5944. if ('textarea' == this._controls.editor.tagName.toLowerCase())
  5945. this._form.appendChild(document.createElement('br'));
  5946. if (this.options.onFormCustomization)
  5947. this.options.onFormCustomization(this, this._form);
  5948. addText('Before', this.options.okControl || this.options.cancelControl);
  5949. this.createControl('ok', this._boundSubmitHandler);
  5950. addText('Between', this.options.okControl && this.options.cancelControl);
  5951. this.createControl('cancel', this._boundCancelHandler, 'editor_cancel');
  5952. addText('After', this.options.okControl || this.options.cancelControl);
  5953. },
  5954. destroy: function() {
  5955. if (this._oldInnerHTML)
  5956. this.element.innerHTML = this._oldInnerHTML;
  5957. this.leaveEditMode();
  5958. this.unregisterListeners();
  5959. },
  5960. enterEditMode: function(e) {
  5961. if (this._saving || this._editing) return;
  5962. this._editing = true;
  5963. this.triggerCallback('onEnterEditMode');
  5964. if (this.options.externalControl)
  5965. this.options.externalControl.hide();
  5966. this.element.hide();
  5967. this.createForm();
  5968. this.element.parentNode.insertBefore(this._form, this.element);
  5969. if (!this.options.loadTextURL)
  5970. this.postProcessEditField();
  5971. if (e) Event.stop(e);
  5972. },
  5973. enterHover: function(e) {
  5974. if (this.options.hoverClassName)
  5975. this.element.addClassName(this.options.hoverClassName);
  5976. if (this._saving) return;
  5977. this.triggerCallback('onEnterHover');
  5978. },
  5979. getText: function() {
  5980. return this.element.innerHTML.unescapeHTML();
  5981. },
  5982. handleAJAXFailure: function(transport) {
  5983. this.triggerCallback('onFailure', transport);
  5984. if (this._oldInnerHTML) {
  5985. this.element.innerHTML = this._oldInnerHTML;
  5986. this._oldInnerHTML = null;
  5987. }
  5988. },
  5989. handleFormCancellation: function(e) {
  5990. this.wrapUp();
  5991. if (e) Event.stop(e);
  5992. },
  5993. handleFormSubmission: function(e) {
  5994. var form = this._form;
  5995. var value = $F(this._controls.editor);
  5996. this.prepareSubmission();
  5997. var params = this.options.callback(form, value) || '';
  5998. if (Object.isString(params))
  5999. params = params.toQueryParams();
  6000. params.editorId = this.element.id;
  6001. if (this.options.htmlResponse) {
  6002. var options = Object.extend({ evalScripts: true }, this.options.ajaxOptions);
  6003. Object.extend(options, {
  6004. parameters: params,
  6005. onComplete: this._boundWrapperHandler,
  6006. onFailure: this._boundFailureHandler
  6007. });
  6008. new Ajax.Updater({ success: this.element }, this.url, options);
  6009. } else {
  6010. var options = Object.extend({ method: 'get' }, this.options.ajaxOptions);
  6011. Object.extend(options, {
  6012. parameters: params,
  6013. onComplete: this._boundWrapperHandler,
  6014. onFailure: this._boundFailureHandler
  6015. });
  6016. new Ajax.Request(this.url, options);
  6017. }
  6018. if (e) Event.stop(e);
  6019. },
  6020. leaveEditMode: function() {
  6021. this.element.removeClassName(this.options.savingClassName);
  6022. this.removeForm();
  6023. this.leaveHover();
  6024. this.element.style.backgroundColor = this._originalBackground;
  6025. this.element.show();
  6026. if (this.options.externalControl)
  6027. this.options.externalControl.show();
  6028. this._saving = false;
  6029. this._editing = false;
  6030. this._oldInnerHTML = null;
  6031. this.triggerCallback('onLeaveEditMode');
  6032. },
  6033. leaveHover: function(e) {
  6034. if (this.options.hoverClassName)
  6035. this.element.removeClassName(this.options.hoverClassName);
  6036. if (this._saving) return;
  6037. this.triggerCallback('onLeaveHover');
  6038. },
  6039. loadExternalText: function() {
  6040. this._form.addClassName(this.options.loadingClassName);
  6041. this._controls.editor.disabled = true;
  6042. var options = Object.extend({ method: 'get' }, this.options.ajaxOptions);
  6043. Object.extend(options, {
  6044. parameters: 'editorId=' + encodeURIComponent(this.element.id),
  6045. onComplete: Prototype.emptyFunction,
  6046. onSuccess: function(transport) {
  6047. this._form.removeClassName(this.options.loadingClassName);
  6048. var text = transport.responseText;
  6049. if (this.options.stripLoadedTextTags)
  6050. text = text.stripTags();
  6051. this._controls.editor.value = text;
  6052. this._controls.editor.disabled = false;
  6053. this.postProcessEditField();
  6054. }.bind(this),
  6055. onFailure: this._boundFailureHandler
  6056. });
  6057. new Ajax.Request(this.options.loadTextURL, options);
  6058. },
  6059. postProcessEditField: function() {
  6060. var fpc = this.options.fieldPostCreation;
  6061. if (fpc)
  6062. $(this._controls.editor)['focus' == fpc ? 'focus' : 'activate']();
  6063. },
  6064. prepareOptions: function() {
  6065. this.options = Object.clone(Ajax.InPlaceEditor.DefaultOptions);
  6066. Object.extend(this.options, Ajax.InPlaceEditor.DefaultCallbacks);
  6067. [this._extraDefaultOptions].flatten().compact().each(function(defs) {
  6068. Object.extend(this.options, defs);
  6069. }.bind(this));
  6070. },
  6071. prepareSubmission: function() {
  6072. this._saving = true;
  6073. this.removeForm();
  6074. this.leaveHover();
  6075. this.showSaving();
  6076. },
  6077. registerListeners: function() {
  6078. this._listeners = { };
  6079. var listener;
  6080. $H(Ajax.InPlaceEditor.Listeners).each(function(pair) {
  6081. listener = this[pair.value].bind(this);
  6082. this._listeners[pair.key] = listener;
  6083. if (!this.options.externalControlOnly)
  6084. this.element.observe(pair.key, listener);
  6085. if (this.options.externalControl)
  6086. this.options.externalControl.observe(pair.key, listener);
  6087. }.bind(this));
  6088. },
  6089. removeForm: function() {
  6090. if (!this._form) return;
  6091. this._form.remove();
  6092. this._form = null;
  6093. this._controls = { };
  6094. },
  6095. showSaving: function() {
  6096. this._oldInnerHTML = this.element.innerHTML;
  6097. this.element.innerHTML = this.options.savingText;
  6098. this.element.addClassName(this.options.savingClassName);
  6099. this.element.style.backgroundColor = this._originalBackground;
  6100. this.element.show();
  6101. },
  6102. triggerCallback: function(cbName, arg) {
  6103. if ('function' == typeof this.options[cbName]) {
  6104. this.options[cbName](this, arg);
  6105. }
  6106. },
  6107. unregisterListeners: function() {
  6108. $H(this._listeners).each(function(pair) {
  6109. if (!this.options.externalControlOnly)
  6110. this.element.stopObserving(pair.key, pair.value);
  6111. if (this.options.externalControl)
  6112. this.options.externalControl.stopObserving(pair.key, pair.value);
  6113. }.bind(this));
  6114. },
  6115. wrapUp: function(transport) {
  6116. this.leaveEditMode();
  6117. // Can't use triggerCallback due to backward compatibility: requires
  6118. // binding + direct element
  6119. this._boundComplete(transport, this.element);
  6120. }
  6121. });
  6122. Object.extend(Ajax.InPlaceEditor.prototype, {
  6123. dispose: Ajax.InPlaceEditor.prototype.destroy
  6124. });
  6125. Ajax.InPlaceCollectionEditor = Class.create(Ajax.InPlaceEditor, {
  6126. initialize: function($super, element, url, options) {
  6127. this._extraDefaultOptions = Ajax.InPlaceCollectionEditor.DefaultOptions;
  6128. $super(element, url, options);
  6129. },
  6130. createEditField: function() {
  6131. var list = document.createElement('select');
  6132. list.name = this.options.paramName;
  6133. list.size = 1;
  6134. this._controls.editor = list;
  6135. this._collection = this.options.collection || [];
  6136. if (this.options.loadCollectionURL)
  6137. this.loadCollection();
  6138. else
  6139. this.checkForExternalText();
  6140. this._form.appendChild(this._controls.editor);
  6141. },
  6142. loadCollection: function() {
  6143. this._form.addClassName(this.options.loadingClassName);
  6144. this.showLoadingText(this.options.loadingCollectionText);
  6145. var options = Object.extend({ method: 'get' }, this.options.ajaxOptions);
  6146. Object.extend(options, {
  6147. parameters: 'editorId=' + encodeURIComponent(this.element.id),
  6148. onComplete: Prototype.emptyFunction,
  6149. onSuccess: function(transport) {
  6150. var js = transport.responseText.strip();
  6151. if (!/^\[.*\]$/.test(js)) // TODO: improve sanity check
  6152. throw('Server returned an invalid collection representation.');
  6153. this._collection = eval(js);
  6154. this.checkForExternalText();
  6155. }.bind(this),
  6156. onFailure: this.onFailure
  6157. });
  6158. new Ajax.Request(this.options.loadCollectionURL, options);
  6159. },
  6160. showLoadingText: function(text) {
  6161. this._controls.editor.disabled = true;
  6162. var tempOption = this._controls.editor.firstChild;
  6163. if (!tempOption) {
  6164. tempOption = document.createElement('option');
  6165. tempOption.value = '';
  6166. this._controls.editor.appendChild(tempOption);
  6167. tempOption.selected = true;
  6168. }
  6169. tempOption.update((text || '').stripScripts().stripTags());
  6170. },
  6171. checkForExternalText: function() {
  6172. this._text = this.getText();
  6173. if (this.options.loadTextURL)
  6174. this.loadExternalText();
  6175. else
  6176. this.buildOptionList();
  6177. },
  6178. loadExternalText: function() {
  6179. this.showLoadingText(this.options.loadingText);
  6180. var options = Object.extend({ method: 'get' }, this.options.ajaxOptions);
  6181. Object.extend(options, {
  6182. parameters: 'editorId=' + encodeURIComponent(this.element.id),
  6183. onComplete: Prototype.emptyFunction,
  6184. onSuccess: function(transport) {
  6185. this._text = transport.responseText.strip();
  6186. this.buildOptionList();
  6187. }.bind(this),
  6188. onFailure: this.onFailure
  6189. });
  6190. new Ajax.Request(this.options.loadTextURL, options);
  6191. },
  6192. buildOptionList: function() {
  6193. this._form.removeClassName(this.options.loadingClassName);
  6194. this._collection = this._collection.map(function(entry) {
  6195. return 2 === entry.length ? entry : [entry, entry].flatten();
  6196. });
  6197. var marker = ('value' in this.options) ? this.options.value : this._text;
  6198. var textFound = this._collection.any(function(entry) {
  6199. return entry[0] == marker;
  6200. }.bind(this));
  6201. this._controls.editor.update('');
  6202. var option;
  6203. this._collection.each(function(entry, index) {
  6204. option = document.createElement('option');
  6205. option.value = entry[0];
  6206. option.selected = textFound ? entry[0] == marker : 0 == index;
  6207. option.appendChild(document.createTextNode(entry[1]));
  6208. this._controls.editor.appendChild(option);
  6209. }.bind(this));
  6210. this._controls.editor.disabled = false;
  6211. Field.scrollFreeActivate(this._controls.editor);
  6212. }
  6213. });
  6214. //**** DEPRECATION LAYER FOR InPlace[Collection]Editor! ****
  6215. //**** This only exists for a while, in order to let ****
  6216. //**** users adapt to the new API. Read up on the new ****
  6217. //**** API and convert your code to it ASAP! ****
  6218. Ajax.InPlaceEditor.prototype.initialize.dealWithDeprecatedOptions = function(options) {
  6219. if (!options) return;
  6220. function fallback(name, expr) {
  6221. if (name in options || expr === undefined) return;
  6222. options[name] = expr;
  6223. };
  6224. fallback('cancelControl', (options.cancelLink ? 'link' : (options.cancelButton ? 'button' :
  6225. options.cancelLink == options.cancelButton == false ? false : undefined)));
  6226. fallback('okControl', (options.okLink ? 'link' : (options.okButton ? 'button' :
  6227. options.okLink == options.okButton == false ? false : undefined)));
  6228. fallback('highlightColor', options.highlightcolor);
  6229. fallback('highlightEndColor', options.highlightendcolor);
  6230. };
  6231. Object.extend(Ajax.InPlaceEditor, {
  6232. DefaultOptions: {
  6233. ajaxOptions: { },
  6234. autoRows: 3, // Use when multi-line w/ rows == 1
  6235. cancelControl: 'link', // 'link'|'button'|false
  6236. cancelText: 'cancel',
  6237. clickToEditText: 'Click to edit',
  6238. externalControl: null, // id|elt
  6239. externalControlOnly: false,
  6240. fieldPostCreation: 'activate', // 'activate'|'focus'|false
  6241. formClassName: 'inplaceeditor-form',
  6242. formId: null, // id|elt
  6243. highlightColor: '#ffff99',
  6244. highlightEndColor: '#ffffff',
  6245. hoverClassName: '',
  6246. htmlResponse: true,
  6247. loadingClassName: 'inplaceeditor-loading',
  6248. loadingText: 'Loading...',
  6249. okControl: 'button', // 'link'|'button'|false
  6250. okText: 'ok',
  6251. paramName: 'value',
  6252. rows: 1, // If 1 and multi-line, uses autoRows
  6253. savingClassName: 'inplaceeditor-saving',
  6254. savingText: 'Saving...',
  6255. size: 0,
  6256. stripLoadedTextTags: false,
  6257. submitOnBlur: false,
  6258. textAfterControls: '',
  6259. textBeforeControls: '',
  6260. textBetweenControls: ''
  6261. },
  6262. DefaultCallbacks: {
  6263. callback: function(form) {
  6264. return Form.serialize(form);
  6265. },
  6266. onComplete: function(transport, element) {
  6267. // For backward compatibility, this one is bound to the IPE, and passes
  6268. // the element directly. It was too often customized, so we don't break it.
  6269. new Effect.Highlight(element, {
  6270. startcolor: this.options.highlightColor, keepBackgroundImage: true });
  6271. },
  6272. onEnterEditMode: null,
  6273. onEnterHover: function(ipe) {
  6274. ipe.element.style.backgroundColor = ipe.options.highlightColor;
  6275. if (ipe._effect)
  6276. ipe._effect.cancel();
  6277. },
  6278. onFailure: function(transport, ipe) {
  6279. alert('Error communication with the server: ' + transport.responseText.stripTags());
  6280. },
  6281. onFormCustomization: null, // Takes the IPE and its generated form, after editor, before controls.
  6282. onLeaveEditMode: null,
  6283. onLeaveHover: function(ipe) {
  6284. ipe._effect = new Effect.Highlight(ipe.element, {
  6285. startcolor: ipe.options.highlightColor, endcolor: ipe.options.highlightEndColor,
  6286. restorecolor: ipe._originalBackground, keepBackgroundImage: true
  6287. });
  6288. }
  6289. },
  6290. Listeners: {
  6291. click: 'enterEditMode',
  6292. keydown: 'checkForEscapeOrReturn',
  6293. mouseover: 'enterHover',
  6294. mouseout: 'leaveHover'
  6295. }
  6296. });
  6297. Ajax.InPlaceCollectionEditor.DefaultOptions = {
  6298. loadingCollectionText: 'Loading options...'
  6299. };
  6300. // Delayed observer, like Form.Element.Observer,
  6301. // but waits for delay after last key input
  6302. // Ideal for live-search fields
  6303. Form.Element.DelayedObserver = Class.create({
  6304. initialize: function(element, delay, callback) {
  6305. this.delay = delay || 0.5;
  6306. this.element = $(element);
  6307. this.callback = callback;
  6308. this.timer = null;
  6309. this.lastValue = $F(this.element);
  6310. Event.observe(this.element,'keyup',this.delayedListener.bindAsEventListener(this));
  6311. },
  6312. delayedListener: function(event) {
  6313. if(this.lastValue == $F(this.element)) return;
  6314. if(this.timer) clearTimeout(this.timer);
  6315. this.timer = setTimeout(this.onTimerEvent.bind(this), this.delay * 1000);
  6316. this.lastValue = $F(this.element);
  6317. },
  6318. onTimerEvent: function() {
  6319. this.timer = null;
  6320. this.callback(this.element, $F(this.element));
  6321. }
  6322. });