PageRenderTime 411ms CodeModel.GetById 31ms RepoModel.GetById 1ms app.codeStats 2ms

/public/javascripts/prototype.js

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