PageRenderTime 103ms CodeModel.GetById 14ms RepoModel.GetById 1ms app.codeStats 1ms

/lib/src/weblocks-stable/pub/bundles/2.js

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