1 /* Prototype JavaScript framework, version 1.6.0.2
2 * (c) 2005-2008 Sam Stephenson
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/
7 *--------------------------------------------------------------------------*/
13 IE: !!(window.attachEvent && !window.opera),
14 Opera: !!window.opera,
15 WebKit: navigator.userAgent.indexOf('AppleWebKit/') > -1,
16 Gecko: navigator.userAgent.indexOf('Gecko') > -1 && navigator.userAgent.indexOf('KHTML') == -1,
17 MobileSafari: !!navigator.userAgent.match(/Apple.*Mobile.*Safari/)
21 XPath: !!document.evaluate,
22 ElementExtensions: !!window.HTMLElement,
23 SpecificElementExtensions:
24 document.createElement('div').__proto__ &&
25 document.createElement('div').__proto__ !==
26 document.createElement('form').__proto__
29 ScriptFragment: '<script[^>]*>([\\S\\s]*?)<\/script>',
30 JSONFilter: /^\/\*-secure-([\s\S]*)\*\/\s*$/,
32 emptyFunction: function() { },
33 K: function(x) { return x }
36 if (Prototype.Browser.MobileSafari)
37 Prototype.BrowserFeatures.SpecificElementExtensions = false;
40 /* Based on Alex Arnell's inheritance implementation. */
43 var parent = null, properties = $A(arguments);
44 if (Object.isFunction(properties[0]))
45 parent = properties.shift();
48 this.initialize.apply(this, arguments);
51 Object.extend(klass, Class.Methods);
52 klass.superclass = parent;
53 klass.subclasses = [];
56 var subclass = function() { };
57 subclass.prototype = parent.prototype;
58 klass.prototype = new subclass;
59 parent.subclasses.push(klass);
62 for (var i = 0; i < properties.length; i++)
63 klass.addMethods(properties[i]);
65 if (!klass.prototype.initialize)
66 klass.prototype.initialize = Prototype.emptyFunction;
68 klass.prototype.constructor = klass;
75 addMethods: function(source) {
76 var ancestor = this.superclass && this.superclass.prototype;
77 var properties = Object.keys(source);
79 if (!Object.keys({ toString: true }).length)
80 properties.push("toString", "valueOf");
82 for (var i = 0, length = properties.length; i < length; i++) {
83 var property = properties[i], value = source[property];
84 if (ancestor && Object.isFunction(value) &&
85 value.argumentNames().first() == "$super") {
86 var method = value, value = Object.extend((function(m) {
87 return function() { return ancestor[m].apply(this, arguments) };
88 })(property).wrap(method), {
89 valueOf: function() { return method },
90 toString: function() { return method.toString() }
93 this.prototype[property] = value;
102 Object.extend = function(destination, source) {
103 for (var property in source)
104 destination[property] = source[property];
108 Object.extend(Object, {
109 inspect: function(object) {
111 if (Object.isUndefined(object)) return 'undefined';
112 if (object === null) return 'null';
113 return object.inspect ? object.inspect() : String(object);
115 if (e instanceof RangeError) return '...';
120 toJSON: function(object) {
121 var type = typeof object;
125 case 'unknown': return;
126 case 'boolean': return object.toString();
129 if (object === null) return 'null';
130 if (object.toJSON) return object.toJSON();
131 if (Object.isElement(object)) return;
134 for (var property in object) {
135 var value = Object.toJSON(object[property]);
136 if (!Object.isUndefined(value))
137 results.push(property.toJSON() + ': ' + value);
140 return '{' + results.join(', ') + '}';
143 toQueryString: function(object) {
144 return $H(object).toQueryString();
147 toHTML: function(object) {
148 return object && object.toHTML ? object.toHTML() : String.interpret(object);
151 keys: function(object) {
153 for (var property in object)
158 values: function(object) {
160 for (var property in object)
161 values.push(object[property]);
165 clone: function(object) {
166 return Object.extend({ }, object);
169 isElement: function(object) {
170 return object && object.nodeType == 1;
173 isArray: function(object) {
174 return object != null && typeof object == "object" &&
175 'splice' in object && 'join' in object;
178 isHash: function(object) {
179 return object instanceof Hash;
182 isFunction: function(object) {
183 return typeof object == "function";
186 isString: function(object) {
187 return typeof object == "string";
190 isNumber: function(object) {
191 return typeof object == "number";
194 isUndefined: function(object) {
195 return typeof object == "undefined";
199 Object.extend(Function.prototype, {
200 argumentNames: function() {
201 var names = this.toString().match(/^[\s\(]*function[^(]*\((.*?)\)/)[1].split(",").invoke("strip");
202 return names.length == 1 && !names[0] ? [] : names;
206 if (arguments.length < 2 && Object.isUndefined(arguments[0])) return this;
207 var __method = this, args = $A(arguments), object = args.shift();
209 return __method.apply(object, args.concat($A(arguments)));
213 bindAsEventListener: function() {
214 var __method = this, args = $A(arguments), object = args.shift();
215 return function(event) {
216 return __method.apply(object, [event || window.event].concat(args));
221 if (!arguments.length) return this;
222 var __method = this, args = $A(arguments);
224 return __method.apply(this, args.concat($A(arguments)));
229 var __method = this, args = $A(arguments), timeout = args.shift() * 1000;
230 return window.setTimeout(function() {
231 return __method.apply(__method, args);
235 wrap: function(wrapper) {
238 return wrapper.apply(this, [__method.bind(this)].concat($A(arguments)));
242 methodize: function() {
243 if (this._methodized) return this._methodized;
245 return this._methodized = function() {
246 return __method.apply(null, [this].concat($A(arguments)));
251 Function.prototype.defer = Function.prototype.delay.curry(0.01);
253 Date.prototype.toJSON = function() {
254 return '"' + this.getUTCFullYear() + '-' +
255 (this.getUTCMonth() + 1).toPaddedString(2) + '-' +
256 this.getUTCDate().toPaddedString(2) + 'T' +
257 this.getUTCHours().toPaddedString(2) + ':' +
258 this.getUTCMinutes().toPaddedString(2) + ':' +
259 this.getUTCSeconds().toPaddedString(2) + 'Z"';
266 for (var i = 0, length = arguments.length; i < length; i++) {
267 var lambda = arguments[i];
269 returnValue = lambda();
278 RegExp.prototype.match = RegExp.prototype.test;
280 RegExp.escape = function(str) {
281 return String(str).replace(/([.*+?^=!:${}()|[\]\/\\])/g, '\\$1');
284 /*--------------------------------------------------------------------------*/
286 var PeriodicalExecuter = Class.create({
287 initialize: function(callback, frequency) {
288 this.callback = callback;
289 this.frequency = frequency;
290 this.currentlyExecuting = false;
292 this.registerCallback();
295 registerCallback: function() {
296 this.timer = setInterval(this.onTimerEvent.bind(this), this.frequency * 1000);
299 execute: function() {
304 if (!this.timer) return;
305 clearInterval(this.timer);
309 onTimerEvent: function() {
310 if (!this.currentlyExecuting) {
312 this.currentlyExecuting = true;
315 this.currentlyExecuting = false;
320 Object.extend(String, {
321 interpret: function(value) {
322 return value == null ? '' : String(value);
334 Object.extend(String.prototype, {
335 gsub: function(pattern, replacement) {
336 var result = '', source = this, match;
337 replacement = arguments.callee.prepareReplacement(replacement);
339 while (source.length > 0) {
340 if (match = source.match(pattern)) {
341 result += source.slice(0, match.index);
342 result += String.interpret(replacement(match));
343 source = source.slice(match.index + match[0].length);
345 result += source, source = '';
351 sub: function(pattern, replacement, count) {
352 replacement = this.gsub.prepareReplacement(replacement);
353 count = Object.isUndefined(count) ? 1 : count;
355 return this.gsub(pattern, function(match) {
356 if (--count < 0) return match[0];
357 return replacement(match);
361 scan: function(pattern, iterator) {
362 this.gsub(pattern, iterator);
366 truncate: function(length, truncation) {
367 length = length || 30;
368 truncation = Object.isUndefined(truncation) ? '...' : truncation;
369 return this.length > length ?
370 this.slice(0, length - truncation.length) + truncation : String(this);
374 return this.replace(/^\s+/, '').replace(/\s+$/, '');
377 stripTags: function() {
378 return this.replace(/<\/?[^>]+>/gi, '');
381 stripScripts: function() {
382 return this.replace(new RegExp(Prototype.ScriptFragment, 'img'), '');
385 extractScripts: function() {
386 var matchAll = new RegExp(Prototype.ScriptFragment, 'img');
387 var matchOne = new RegExp(Prototype.ScriptFragment, 'im');
388 return (this.match(matchAll) || []).map(function(scriptTag) {
389 return (scriptTag.match(matchOne) || ['', ''])[1];
393 evalScripts: function() {
394 return this.extractScripts().map(function(script) { return eval(script) });
397 escapeHTML: function() {
398 var self = arguments.callee;
399 self.text.data = this;
400 return self.div.innerHTML;
403 unescapeHTML: function() {
404 var div = new Element('div');
405 div.innerHTML = this.stripTags();
406 return div.childNodes[0] ? (div.childNodes.length > 1 ?
407 $A(div.childNodes).inject('', function(memo, node) { return memo+node.nodeValue }) :
408 div.childNodes[0].nodeValue) : '';
411 toQueryParams: function(separator) {
412 var match = this.strip().match(/([^?#]*)(#.*)?$/);
413 if (!match) return { };
415 return match[1].split(separator || '&').inject({ }, function(hash, pair) {
416 if ((pair = pair.split('='))[0]) {
417 var key = decodeURIComponent(pair.shift());
418 var value = pair.length > 1 ? pair.join('=') : pair[0];
419 if (value != undefined) value = decodeURIComponent(value);
422 if (!Object.isArray(hash[key])) hash[key] = [hash[key]];
423 hash[key].push(value);
425 else hash[key] = value;
431 toArray: function() {
432 return this.split('');
436 return this.slice(0, this.length - 1) +
437 String.fromCharCode(this.charCodeAt(this.length - 1) + 1);
440 times: function(count) {
441 return count < 1 ? '' : new Array(count + 1).join(this);
444 camelize: function() {
445 var parts = this.split('-'), len = parts.length;
446 if (len == 1) return parts[0];
448 var camelized = this.charAt(0) == '-'
449 ? parts[0].charAt(0).toUpperCase() + parts[0].substring(1)
452 for (var i = 1; i < len; i++)
453 camelized += parts[i].charAt(0).toUpperCase() + parts[i].substring(1);
458 capitalize: function() {
459 return this.charAt(0).toUpperCase() + this.substring(1).toLowerCase();
462 underscore: function() {
463 return this.gsub(/::/, '/').gsub(/([A-Z]+)([A-Z][a-z])/,'#{1}_#{2}').gsub(/([a-z\d])([A-Z])/,'#{1}_#{2}').gsub(/-/,'_').toLowerCase();
466 dasherize: function() {
467 return this.gsub(/_/,'-');
470 inspect: function(useDoubleQuotes) {
471 var escapedString = this.gsub(/[\x00-\x1f\\]/, function(match) {
472 var character = String.specialChar[match[0]];
473 return character ? character : '\\u00' + match[0].charCodeAt().toPaddedString(2, 16);
475 if (useDoubleQuotes) return '"' + escapedString.replace(/"/g, '\\"') + '"';
476 return "'" + escapedString.replace(/'/g, '\\\'') + "'";
480 return this.inspect(true);
483 unfilterJSON: function(filter) {
484 return this.sub(filter || Prototype.JSONFilter, '#{1}');
489 if (str.blank()) return false;
490 str = this.replace(/\\./g, '@').replace(/"[^"\\\n\r]*"/g, '');
491 return (/^[,:{}\[\]0-9.\-+Eaeflnr-u \n\r\t]*$/).test(str);
494 evalJSON: function(sanitize) {
495 var json = this.unfilterJSON();
497 if (!sanitize || json.isJSON()) return eval('(' + json + ')');
499 throw new SyntaxError('Badly formed JSON string: ' + this.inspect());
502 include: function(pattern) {
503 return this.indexOf(pattern) > -1;
506 startsWith: function(pattern) {
507 return this.indexOf(pattern) === 0;
510 endsWith: function(pattern) {
511 var d = this.length - pattern.length;
512 return d >= 0 && this.lastIndexOf(pattern) === d;
520 return /^\s*$/.test(this);
523 interpolate: function(object, pattern) {
524 return new Template(this, pattern).evaluate(object);
528 if (Prototype.Browser.WebKit || Prototype.Browser.IE) Object.extend(String.prototype, {
529 escapeHTML: function() {
530 return this.replace(/&/g,'&').replace(/</g,'<').replace(/>/g,'>');
532 unescapeHTML: function() {
533 return this.replace(/&/g,'&').replace(/</g,'<').replace(/>/g,'>');
537 String.prototype.gsub.prepareReplacement = function(replacement) {
538 if (Object.isFunction(replacement)) return replacement;
539 var template = new Template(replacement);
540 return function(match) { return template.evaluate(match) };
543 String.prototype.parseQuery = String.prototype.toQueryParams;
545 Object.extend(String.prototype.escapeHTML, {
546 div: document.createElement('div'),
547 text: document.createTextNode('')
550 with (String.prototype.escapeHTML) div.appendChild(text);
552 var Template = Class.create({
553 initialize: function(template, pattern) {
554 this.template = template.toString();
555 this.pattern = pattern || Template.Pattern;
558 evaluate: function(object) {
559 if (Object.isFunction(object.toTemplateReplacements))
560 object = object.toTemplateReplacements();
562 return this.template.gsub(this.pattern, function(match) {
563 if (object == null) return '';
565 var before = match[1] || '';
566 if (before == '\\') return match[2];
568 var ctx = object, expr = match[3];
569 var pattern = /^([^.[]+|\[((?:.*?[^\\])?)\])(\.|\[|$)/;
570 match = pattern.exec(expr);
571 if (match == null) return before;
573 while (match != null) {
574 var comp = match[1].startsWith('[') ? match[2].gsub('\\\\]', ']') : match[1];
576 if (null == ctx || '' == match[3]) break;
577 expr = expr.substring('[' == match[3] ? match[1].length : match[0].length);
578 match = pattern.exec(expr);
581 return before + String.interpret(ctx);
585 Template.Pattern = /(^|.|\r|\n)(#\{(.*?)\})/;
590 each: function(iterator, context) {
592 iterator = iterator.bind(context);
594 this._each(function(value) {
595 iterator(value, index++);
598 if (e != $break) throw e;
603 eachSlice: function(number, iterator, context) {
604 iterator = iterator ? iterator.bind(context) : Prototype.K;
605 var index = -number, slices = [], array = this.toArray();
606 while ((index += number) < array.length)
607 slices.push(array.slice(index, index+number));
608 return slices.collect(iterator, context);
611 all: function(iterator, context) {
612 iterator = iterator ? iterator.bind(context) : Prototype.K;
614 this.each(function(value, index) {
615 result = result && !!iterator(value, index);
616 if (!result) throw $break;
621 any: function(iterator, context) {
622 iterator = iterator ? iterator.bind(context) : Prototype.K;
624 this.each(function(value, index) {
625 if (result = !!iterator(value, index))
631 collect: function(iterator, context) {
632 iterator = iterator ? iterator.bind(context) : Prototype.K;
634 this.each(function(value, index) {
635 results.push(iterator(value, index));
640 detect: function(iterator, context) {
641 iterator = iterator.bind(context);
643 this.each(function(value, index) {
644 if (iterator(value, index)) {
652 findAll: function(iterator, context) {
653 iterator = iterator.bind(context);
655 this.each(function(value, index) {
656 if (iterator(value, index))
662 grep: function(filter, iterator, context) {
663 iterator = iterator ? iterator.bind(context) : Prototype.K;
666 if (Object.isString(filter))
667 filter = new RegExp(filter);
669 this.each(function(value, index) {
670 if (filter.match(value))
671 results.push(iterator(value, index));
676 include: function(object) {
677 if (Object.isFunction(this.indexOf))
678 if (this.indexOf(object) != -1) return true;
681 this.each(function(value) {
682 if (value == object) {
690 inGroupsOf: function(number, fillWith) {
691 fillWith = Object.isUndefined(fillWith) ? null : fillWith;
692 return this.eachSlice(number, function(slice) {
693 while(slice.length < number) slice.push(fillWith);
698 inject: function(memo, iterator, context) {
699 iterator = iterator.bind(context);
700 this.each(function(value, index) {
701 memo = iterator(memo, value, index);
706 invoke: function(method) {
707 var args = $A(arguments).slice(1);
708 return this.map(function(value) {
709 return value[method].apply(value, args);
713 max: function(iterator, context) {
714 iterator = iterator ? iterator.bind(context) : Prototype.K;
716 this.each(function(value, index) {
717 value = iterator(value, index);
718 if (result == null || value >= result)
724 min: function(iterator, context) {
725 iterator = iterator ? iterator.bind(context) : Prototype.K;
727 this.each(function(value, index) {
728 value = iterator(value, index);
729 if (result == null || value < result)
735 partition: function(iterator, context) {
736 iterator = iterator ? iterator.bind(context) : Prototype.K;
737 var trues = [], falses = [];
738 this.each(function(value, index) {
739 (iterator(value, index) ?
740 trues : falses).push(value);
742 return [trues, falses];
745 pluck: function(property) {
747 this.each(function(value) {
748 results.push(value[property]);
753 reject: function(iterator, context) {
754 iterator = iterator.bind(context);
756 this.each(function(value, index) {
757 if (!iterator(value, index))
763 sortBy: function(iterator, context) {
764 iterator = iterator.bind(context);
765 return this.map(function(value, index) {
766 return {value: value, criteria: iterator(value, index)};
767 }).sort(function(left, right) {
768 var a = left.criteria, b = right.criteria;
769 return a < b ? -1 : a > b ? 1 : 0;
773 toArray: function() {
778 var iterator = Prototype.K, args = $A(arguments);
779 if (Object.isFunction(args.last()))
780 iterator = args.pop();
782 var collections = [this].concat(args).map($A);
783 return this.map(function(value, index) {
784 return iterator(collections.pluck(index));
789 return this.toArray().length;
792 inspect: function() {
793 return '#<Enumerable:' + this.toArray().inspect() + '>';
797 Object.extend(Enumerable, {
798 map: Enumerable.collect,
799 find: Enumerable.detect,
800 select: Enumerable.findAll,
801 filter: Enumerable.findAll,
802 member: Enumerable.include,
803 entries: Enumerable.toArray,
804 every: Enumerable.all,
807 function $A(iterable) {
808 if (!iterable) return [];
809 if (iterable.toArray) return iterable.toArray();
810 var length = iterable.length || 0, results = new Array(length);
811 while (length--) results[length] = iterable[length];
815 if (Prototype.Browser.WebKit) {
816 $A = function(iterable) {
817 if (!iterable) return [];
818 if (!(Object.isFunction(iterable) && iterable == '[object NodeList]') &&
819 iterable.toArray) return iterable.toArray();
820 var length = iterable.length || 0, results = new Array(length);
821 while (length--) results[length] = iterable[length];
828 Object.extend(Array.prototype, Enumerable);
830 if (!Array.prototype._reverse) Array.prototype._reverse = Array.prototype.reverse;
832 Object.extend(Array.prototype, {
833 _each: function(iterator) {
834 for (var i = 0, length = this.length; i < length; i++)
848 return this[this.length - 1];
851 compact: function() {
852 return this.select(function(value) {
853 return value != null;
857 flatten: function() {
858 return this.inject([], function(array, value) {
859 return array.concat(Object.isArray(value) ?
860 value.flatten() : [value]);
864 without: function() {
865 var values = $A(arguments);
866 return this.select(function(value) {
867 return !values.include(value);
871 reverse: function(inline) {
872 return (inline !== false ? this : this.toArray())._reverse();
876 return this.length > 1 ? this : this[0];
879 uniq: function(sorted) {
880 return this.inject([], function(array, value, index) {
881 if (0 == index || (sorted ? array.last() != value : !array.include(value)))
887 intersect: function(array) {
888 return this.uniq().findAll(function(item) {
889 return array.detect(function(value) { return item === value });
894 return [].concat(this);
901 inspect: function() {
902 return '[' + this.map(Object.inspect).join(', ') + ']';
907 this.each(function(object) {
908 var value = Object.toJSON(object);
909 if (!Object.isUndefined(value)) results.push(value);
911 return '[' + results.join(', ') + ']';
915 // use native browser JS 1.6 implementation if available
916 if (Object.isFunction(Array.prototype.forEach))
917 Array.prototype._each = Array.prototype.forEach;
919 if (!Array.prototype.indexOf) Array.prototype.indexOf = function(item, i) {
921 var length = this.length;
922 if (i < 0) i = length + i;
923 for (; i < length; i++)
924 if (this[i] === item) return i;
928 if (!Array.prototype.lastIndexOf) Array.prototype.lastIndexOf = function(item, i) {
929 i = isNaN(i) ? this.length : (i < 0 ? this.length + i : i) + 1;
930 var n = this.slice(0, i).reverse().indexOf(item);
931 return (n < 0) ? n : i - n - 1;
934 Array.prototype.toArray = Array.prototype.clone;
936 function $w(string) {
937 if (!Object.isString(string)) return [];
938 string = string.strip();
939 return string ? string.split(/\s+/) : [];
942 if (Prototype.Browser.Opera){
943 Array.prototype.concat = function() {
945 for (var i = 0, length = this.length; i < length; i++) array.push(this[i]);
946 for (var i = 0, length = arguments.length; i < length; i++) {
947 if (Object.isArray(arguments[i])) {
948 for (var j = 0, arrayLength = arguments[i].length; j < arrayLength; j++)
949 array.push(arguments[i][j]);
951 array.push(arguments[i]);
957 Object.extend(Number.prototype, {
958 toColorPart: function() {
959 return this.toPaddedString(2, 16);
966 times: function(iterator) {
967 $R(0, this, true).each(iterator);
971 toPaddedString: function(length, radix) {
972 var string = this.toString(radix || 10);
973 return '0'.times(length - string.length) + string;
977 return isFinite(this) ? this.toString() : 'null';
981 $w('abs round ceil floor').each(function(method){
982 Number.prototype[method] = Math[method].methodize();
984 function $H(object) {
985 return new Hash(object);
988 var Hash = Class.create(Enumerable, (function() {
990 function toQueryPair(key, value) {
991 if (Object.isUndefined(value)) return key;
992 return key + '=' + encodeURIComponent(String.interpret(value));
996 initialize: function(object) {
997 this._object = Object.isHash(object) ? object.toObject() : Object.clone(object);
1000 _each: function(iterator) {
1001 for (var key in this._object) {
1002 var value = this._object[key], pair = [key, value];
1009 set: function(key, value) {
1010 return this._object[key] = value;
1013 get: function(key) {
1014 return this._object[key];
1017 unset: function(key) {
1018 var value = this._object[key];
1019 delete this._object[key];
1023 toObject: function() {
1024 return Object.clone(this._object);
1028 return this.pluck('key');
1031 values: function() {
1032 return this.pluck('value');
1035 index: function(value) {
1036 var match = this.detect(function(pair) {
1037 return pair.value === value;
1039 return match && match.key;
1042 merge: function(object) {
1043 return this.clone().update(object);
1046 update: function(object) {
1047 return new Hash(object).inject(this, function(result, pair) {
1048 result.set(pair.key, pair.value);
1053 toQueryString: function() {
1054 return this.map(function(pair) {
1055 var key = encodeURIComponent(pair.key), values = pair.value;
1057 if (values && typeof values == 'object') {
1058 if (Object.isArray(values))
1059 return values.map(toQueryPair.curry(key)).join('&');
1061 return toQueryPair(key, values);
1065 inspect: function() {
1066 return '#<Hash:{' + this.map(function(pair) {
1067 return pair.map(Object.inspect).join(': ');
1068 }).join(', ') + '}>';
1071 toJSON: function() {
1072 return Object.toJSON(this.toObject());
1076 return new Hash(this);
1081 Hash.prototype.toTemplateReplacements = Hash.prototype.toObject;
1083 var ObjectRange = Class.create(Enumerable, {
1084 initialize: function(start, end, exclusive) {
1087 this.exclusive = exclusive;
1090 _each: function(iterator) {
1091 var value = this.start;
1092 while (this.include(value)) {
1094 value = value.succ();
1098 include: function(value) {
1099 if (value < this.start)
1102 return value < this.end;
1103 return value <= this.end;
1107 var $R = function(start, end, exclusive) {
1108 return new ObjectRange(start, end, exclusive);
1112 getTransport: function() {
1114 function() {return new XMLHttpRequest()},
1115 function() {return new ActiveXObject('Msxml2.XMLHTTP')},
1116 function() {return new ActiveXObject('Microsoft.XMLHTTP')}
1120 activeRequestCount: 0
1126 _each: function(iterator) {
1127 this.responders._each(iterator);
1130 register: function(responder) {
1131 if (!this.include(responder))
1132 this.responders.push(responder);
1135 unregister: function(responder) {
1136 this.responders = this.responders.without(responder);
1139 dispatch: function(callback, request, transport, json) {
1140 this.each(function(responder) {
1141 if (Object.isFunction(responder[callback])) {
1143 responder[callback].apply(responder, [request, transport, json]);
1150 Object.extend(Ajax.Responders, Enumerable);
1152 Ajax.Responders.register({
1153 onCreate: function() { Ajax.activeRequestCount++ },
1154 onComplete: function() { Ajax.activeRequestCount-- }
1157 Ajax.Base = Class.create({
1158 initialize: function(options) {
1162 contentType: 'application/x-www-form-urlencoded',
1168 Object.extend(this.options, options || { });
1170 this.options.method = this.options.method.toLowerCase();
1172 if (Object.isString(this.options.parameters))
1173 this.options.parameters = this.options.parameters.toQueryParams();
1174 else if (Object.isHash(this.options.parameters))
1175 this.options.parameters = this.options.parameters.toObject();
1179 Ajax.Request = Class.create(Ajax.Base, {
1182 initialize: function($super, url, options) {
1184 this.transport = Ajax.getTransport();
1188 request: function(url) {
1190 this.method = this.options.method;
1191 var params = Object.clone(this.options.parameters);
1193 if (!['get', 'post'].include(this.method)) {
1194 // simulate other verbs over post
1195 params['_method'] = this.method;
1196 this.method = 'post';
1199 this.parameters = params;
1201 if (params = Object.toQueryString(params)) {
1202 // when GET, append parameters to URL
1203 if (this.method == 'get')
1204 this.url += (this.url.include('?') ? '&' : '?') + params;
1205 else if (/Konqueror|Safari|KHTML/.test(navigator.userAgent))
1210 var response = new Ajax.Response(this);
1211 if (this.options.onCreate) this.options.onCreate(response);
1212 Ajax.Responders.dispatch('onCreate', this, response);
1214 this.transport.open(this.method.toUpperCase(), this.url,
1215 this.options.asynchronous);
1217 if (this.options.asynchronous) this.respondToReadyState.bind(this).defer(1);
1219 this.transport.onreadystatechange = this.onStateChange.bind(this);
1220 this.setRequestHeaders();
1222 this.body = this.method == 'post' ? (this.options.postBody || params) : null;
1223 this.transport.send(this.body);
1225 /* Force Firefox to handle ready state 4 for synchronous requests */
1226 if (!this.options.asynchronous && this.transport.overrideMimeType)
1227 this.onStateChange();
1231 this.dispatchException(e);
1235 onStateChange: function() {
1236 var readyState = this.transport.readyState;
1237 if (readyState > 1 && !((readyState == 4) && this._complete))
1238 this.respondToReadyState(this.transport.readyState);
1241 setRequestHeaders: function() {
1243 'X-Requested-With': 'XMLHttpRequest',
1244 'X-Prototype-Version': Prototype.Version,
1245 'Accept': 'text/javascript, text/html, application/xml, text/xml, */*'
1248 if (this.method == 'post') {
1249 headers['Content-type'] = this.options.contentType +
1250 (this.options.encoding ? '; charset=' + this.options.encoding : '');
1252 /* Force "Connection: close" for older Mozilla browsers to work
1253 * around a bug where XMLHttpRequest sends an incorrect
1254 * Content-length header. See Mozilla Bugzilla #246651.
1256 if (this.transport.overrideMimeType &&
1257 (navigator.userAgent.match(/Gecko\/(\d{4})/) || [0,2005])[1] < 2005)
1258 headers['Connection'] = 'close';
1261 // user-defined headers
1262 if (typeof this.options.requestHeaders == 'object') {
1263 var extras = this.options.requestHeaders;
1265 if (Object.isFunction(extras.push))
1266 for (var i = 0, length = extras.length; i < length; i += 2)
1267 headers[extras[i]] = extras[i+1];
1269 $H(extras).each(function(pair) { headers[pair.key] = pair.value });
1272 for (var name in headers)
1273 this.transport.setRequestHeader(name, headers[name]);
1276 success: function() {
1277 var status = this.getStatus();
1278 return !status || (status >= 200 && status < 300);
1281 getStatus: function() {
1283 return this.transport.status || 0;
1284 } catch (e) { return 0 }
1287 respondToReadyState: function(readyState) {
1288 var state = Ajax.Request.Events[readyState], response = new Ajax.Response(this);
1290 if (state == 'Complete') {
1292 this._complete = true;
1293 (this.options['on' + response.status]
1294 || this.options['on' + (this.success() ? 'Success' : 'Failure')]
1295 || Prototype.emptyFunction)(response, response.headerJSON);
1297 this.dispatchException(e);
1300 var contentType = response.getHeader('Content-type');
1301 if (this.options.evalJS == 'force'
1302 || (this.options.evalJS && this.isSameOrigin() && contentType
1303 && contentType.match(/^\s*(text|application)\/(x-)?(java|ecma)script(;.*)?\s*$/i)))
1304 this.evalResponse();
1308 (this.options['on' + state] || Prototype.emptyFunction)(response, response.headerJSON);
1309 Ajax.Responders.dispatch('on' + state, this, response, response.headerJSON);
1311 this.dispatchException(e);
1314 if (state == 'Complete') {
1315 // avoid memory leak in MSIE: clean up
1316 this.transport.onreadystatechange = Prototype.emptyFunction;
1320 isSameOrigin: function() {
1321 var m = this.url.match(/^\s*https?:\/\/[^\/]*/);
1322 return !m || (m[0] == '#{protocol}//#{domain}#{port}'.interpolate({
1323 protocol: location.protocol,
1324 domain: document.domain,
1325 port: location.port ? ':' + location.port : ''
1329 getHeader: function(name) {
1331 return this.transport.getResponseHeader(name) || null;
1332 } catch (e) { return null }
1335 evalResponse: function() {
1337 return eval((this.transport.responseText || '').unfilterJSON());
1339 this.dispatchException(e);
1343 dispatchException: function(exception) {
1344 (this.options.onException || Prototype.emptyFunction)(this, exception);
1345 Ajax.Responders.dispatch('onException', this, exception);
1349 Ajax.Request.Events =
1350 ['Uninitialized', 'Loading', 'Loaded', 'Interactive', 'Complete'];
1352 Ajax.Response = Class.create({
1353 initialize: function(request){
1354 this.request = request;
1355 var transport = this.transport = request.transport,
1356 readyState = this.readyState = transport.readyState;
1358 if((readyState > 2 && !Prototype.Browser.IE) || readyState == 4) {
1359 this.status = this.getStatus();
1360 this.statusText = this.getStatusText();
1361 this.responseText = String.interpret(transport.responseText);
1362 this.headerJSON = this._getHeaderJSON();
1365 if(readyState == 4) {
1366 var xml = transport.responseXML;
1367 this.responseXML = Object.isUndefined(xml) ? null : xml;
1368 this.responseJSON = this._getResponseJSON();
1375 getStatus: Ajax.Request.prototype.getStatus,
1377 getStatusText: function() {
1379 return this.transport.statusText || '';
1380 } catch (e) { return '' }
1383 getHeader: Ajax.Request.prototype.getHeader,
1385 getAllHeaders: function() {
1387 return this.getAllResponseHeaders();
1388 } catch (e) { return null }
1391 getResponseHeader: function(name) {
1392 return this.transport.getResponseHeader(name);
1395 getAllResponseHeaders: function() {
1396 return this.transport.getAllResponseHeaders();
1399 _getHeaderJSON: function() {
1400 var json = this.getHeader('X-JSON');
1401 if (!json) return null;
1402 json = decodeURIComponent(escape(json));
1404 return json.evalJSON(this.request.options.sanitizeJSON ||
1405 !this.request.isSameOrigin());
1407 this.request.dispatchException(e);
1411 _getResponseJSON: function() {
1412 var options = this.request.options;
1413 if (!options.evalJSON || (options.evalJSON != 'force' &&
1414 !(this.getHeader('Content-type') || '').include('application/json')) ||
1415 this.responseText.blank())
1418 return this.responseText.evalJSON(options.sanitizeJSON ||
1419 !this.request.isSameOrigin());
1421 this.request.dispatchException(e);
1426 Ajax.Updater = Class.create(Ajax.Request, {
1427 initialize: function($super, container, url, options) {
1429 success: (container.success || container),
1430 failure: (container.failure || (container.success ? null : container))
1433 options = Object.clone(options);
1434 var onComplete = options.onComplete;
1435 options.onComplete = (function(response, json) {
1436 this.updateContent(response.responseText);
1437 if (Object.isFunction(onComplete)) onComplete(response, json);
1440 $super(url, options);
1443 updateContent: function(responseText) {
1444 var receiver = this.container[this.success() ? 'success' : 'failure'],
1445 options = this.options;
1447 if (!options.evalScripts) responseText = responseText.stripScripts();
1449 if (receiver = $(receiver)) {
1450 if (options.insertion) {
1451 if (Object.isString(options.insertion)) {
1452 var insertion = { }; insertion[options.insertion] = responseText;
1453 receiver.insert(insertion);
1455 else options.insertion(receiver, responseText);
1457 else receiver.update(responseText);
1462 Ajax.PeriodicalUpdater = Class.create(Ajax.Base, {
1463 initialize: function($super, container, url, options) {
1465 this.onComplete = this.options.onComplete;
1467 this.frequency = (this.options.frequency || 2);
1468 this.decay = (this.options.decay || 1);
1471 this.container = container;
1478 this.options.onComplete = this.updateComplete.bind(this);
1479 this.onTimerEvent();
1483 this.updater.options.onComplete = undefined;
1484 clearTimeout(this.timer);
1485 (this.onComplete || Prototype.emptyFunction).apply(this, arguments);
1488 updateComplete: function(response) {
1489 if (this.options.decay) {
1490 this.decay = (response.responseText == this.lastText ?
1491 this.decay * this.options.decay : 1);
1493 this.lastText = response.responseText;
1495 this.timer = this.onTimerEvent.bind(this).delay(this.decay * this.frequency);
1498 onTimerEvent: function() {
1499 this.updater = new Ajax.Updater(this.container, this.url, this.options);
1502 function $(element) {
1503 if (arguments.length > 1) {
1504 for (var i = 0, elements = [], length = arguments.length; i < length; i++)
1505 elements.push($(arguments[i]));
1508 if (Object.isString(element))
1509 element = document.getElementById(element);
1510 return Element.extend(element);
1513 if (Prototype.BrowserFeatures.XPath) {
1514 document._getElementsByXPath = function(expression, parentElement) {
1516 var query = document.evaluate(expression, $(parentElement) || document,
1517 null, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);
1518 for (var i = 0, length = query.snapshotLength; i < length; i++)
1519 results.push(Element.extend(query.snapshotItem(i)));
1524 /*--------------------------------------------------------------------------*/
1526 if (!window.Node) var Node = { };
1528 if (!Node.ELEMENT_NODE) {
1529 // DOM level 2 ECMAScript Language Binding
1530 Object.extend(Node, {
1534 CDATA_SECTION_NODE: 4,
1535 ENTITY_REFERENCE_NODE: 5,
1537 PROCESSING_INSTRUCTION_NODE: 7,
1540 DOCUMENT_TYPE_NODE: 10,
1541 DOCUMENT_FRAGMENT_NODE: 11,
1547 var element = this.Element;
1548 this.Element = function(tagName, attributes) {
1549 attributes = attributes || { };
1550 tagName = tagName.toLowerCase();
1551 var cache = Element.cache;
1552 if (Prototype.Browser.IE && attributes.name) {
1553 tagName = '<' + tagName + ' name="' + attributes.name + '">';
1554 delete attributes.name;
1555 return Element.writeAttribute(document.createElement(tagName), attributes);
1557 if (!cache[tagName]) cache[tagName] = Element.extend(document.createElement(tagName));
1558 return Element.writeAttribute(cache[tagName].cloneNode(false), attributes);
1560 Object.extend(this.Element, element || { });
1563 Element.cache = { };
1566 visible: function(element) {
1567 return $(element).style.display != 'none';
1570 toggle: function(element) {
1571 element = $(element);
1572 Element[Element.visible(element) ? 'hide' : 'show'](element);
1576 hide: function(element) {
1577 $(element).style.display = 'none';
1581 show: function(element) {
1582 $(element).style.display = '';
1586 remove: function(element) {
1587 element = $(element);
1588 element.parentNode.removeChild(element);
1592 update: function(element, content) {
1593 element = $(element);
1594 if (content && content.toElement) content = content.toElement();
1595 if (Object.isElement(content)) return element.update().insert(content);
1596 content = Object.toHTML(content);
1597 element.innerHTML = content.stripScripts();
1598 content.evalScripts.bind(content).defer();
1602 replace: function(element, content) {
1603 element = $(element);
1604 if (content && content.toElement) content = content.toElement();
1605 else if (!Object.isElement(content)) {
1606 content = Object.toHTML(content);
1607 var range = element.ownerDocument.createRange();
1608 range.selectNode(element);
1609 content.evalScripts.bind(content).defer();
1610 content = range.createContextualFragment(content.stripScripts());
1612 element.parentNode.replaceChild(content, element);
1616 insert: function(element, insertions) {
1617 element = $(element);
1619 if (Object.isString(insertions) || Object.isNumber(insertions) ||
1620 Object.isElement(insertions) || (insertions && (insertions.toElement || insertions.toHTML)))
1621 insertions = {bottom:insertions};
1623 var content, insert, tagName, childNodes;
1625 for (var position in insertions) {
1626 content = insertions[position];
1627 position = position.toLowerCase();
1628 insert = Element._insertionTranslations[position];
1630 if (content && content.toElement) content = content.toElement();
1631 if (Object.isElement(content)) {
1632 insert(element, content);
1636 content = Object.toHTML(content);
1638 tagName = ((position == 'before' || position == 'after')
1639 ? element.parentNode : element).tagName.toUpperCase();
1641 childNodes = Element._getContentFromAnonymousElement(tagName, content.stripScripts());
1643 if (position == 'top' || position == 'after') childNodes.reverse();
1644 childNodes.each(insert.curry(element));
1646 content.evalScripts.bind(content).defer();
1652 wrap: function(element, wrapper, attributes) {
1653 element = $(element);
1654 if (Object.isElement(wrapper))
1655 $(wrapper).writeAttribute(attributes || { });
1656 else if (Object.isString(wrapper)) wrapper = new Element(wrapper, attributes);
1657 else wrapper = new Element('div', wrapper);
1658 if (element.parentNode)
1659 element.parentNode.replaceChild(wrapper, element);
1660 wrapper.appendChild(element);
1664 inspect: function(element) {
1665 element = $(element);
1666 var result = '<' + element.tagName.toLowerCase();
1667 $H({'id': 'id', 'className': 'class'}).each(function(pair) {
1668 var property = pair.first(), attribute = pair.last();
1669 var value = (element[property] || '').toString();
1670 if (value) result += ' ' + attribute + '=' + value.inspect(true);
1672 return result + '>';
1675 recursivelyCollect: function(element, property) {
1676 element = $(element);
1678 while (element = element[property])
1679 if (element.nodeType == 1)
1680 elements.push(Element.extend(element));
1684 ancestors: function(element) {
1685 return $(element).recursivelyCollect('parentNode');
1688 descendants: function(element) {
1689 return $(element).select("*");
1692 firstDescendant: function(element) {
1693 element = $(element).firstChild;
1694 while (element && element.nodeType != 1) element = element.nextSibling;
1698 immediateDescendants: function(element) {
1699 if (!(element = $(element).firstChild)) return [];
1700 while (element && element.nodeType != 1) element = element.nextSibling;
1701 if (element) return [element].concat($(element).nextSiblings());
1705 previousSiblings: function(element) {
1706 return $(element).recursivelyCollect('previousSibling');
1709 nextSiblings: function(element) {
1710 return $(element).recursivelyCollect('nextSibling');
1713 siblings: function(element) {
1714 element = $(element);
1715 return element.previousSiblings().reverse().concat(element.nextSiblings());
1718 match: function(element, selector) {
1719 if (Object.isString(selector))
1720 selector = new Selector(selector);
1721 return selector.match($(element));
1724 up: function(element, expression, index) {
1725 element = $(element);
1726 if (arguments.length == 1) return $(element.parentNode);
1727 var ancestors = element.ancestors();
1728 return Object.isNumber(expression) ? ancestors[expression] :
1729 Selector.findElement(ancestors, expression, index);
1732 down: function(element, expression, index) {
1733 element = $(element);
1734 if (arguments.length == 1) return element.firstDescendant();
1735 return Object.isNumber(expression) ? element.descendants()[expression] :
1736 element.select(expression)[index || 0];
1739 previous: function(element, expression, index) {
1740 element = $(element);
1741 if (arguments.length == 1) return $(Selector.handlers.previousElementSibling(element));
1742 var previousSiblings = element.previousSiblings();
1743 return Object.isNumber(expression) ? previousSiblings[expression] :
1744 Selector.findElement(previousSiblings, expression, index);
1747 next: function(element, expression, index) {
1748 element = $(element);
1749 if (arguments.length == 1) return $(Selector.handlers.nextElementSibling(element));
1750 var nextSiblings = element.nextSiblings();
1751 return Object.isNumber(expression) ? nextSiblings[expression] :
1752 Selector.findElement(nextSiblings, expression, index);
1755 select: function() {
1756 var args = $A(arguments), element = $(args.shift());
1757 return Selector.findChildElements(element, args);
1760 adjacent: function() {
1761 var args = $A(arguments), element = $(args.shift());
1762 return Selector.findChildElements(element.parentNode, args).without(element);
1765 identify: function(element) {
1766 element = $(element);
1767 var id = element.readAttribute('id'), self = arguments.callee;
1769 do { id = 'anonymous_element_' + self.counter++ } while ($(id));
1770 element.writeAttribute('id', id);
1774 readAttribute: function(element, name) {
1775 element = $(element);
1776 if (Prototype.Browser.IE) {
1777 var t = Element._attributeTranslations.read;
1778 if (t.values[name]) return t.values[name](element, name);
1779 if (t.names[name]) name = t.names[name];
1780 if (name.include(':')) {
1781 return (!element.attributes || !element.attributes[name]) ? null :
1782 element.attributes[name].value;
1785 return element.getAttribute(name);
1788 writeAttribute: function(element, name, value) {
1789 element = $(element);
1790 var attributes = { }, t = Element._attributeTranslations.write;
1792 if (typeof name == 'object') attributes = name;
1793 else attributes[name] = Object.isUndefined(value) ? true : value;
1795 for (var attr in attributes) {
1796 name = t.names[attr] || attr;
1797 value = attributes[attr];
1798 if (t.values[attr]) name = t.values[attr](element, value);
1799 if (value === false || value === null)
1800 element.removeAttribute(name);
1801 else if (value === true)
1802 element.setAttribute(name, name);
1803 else element.setAttribute(name, value);
1808 getHeight: function(element) {
1809 return $(element).getDimensions().height;
1812 getWidth: function(element) {
1813 return $(element).getDimensions().width;
1816 classNames: function(element) {
1817 return new Element.ClassNames(element);
1820 hasClassName: function(element, className) {
1821 if (!(element = $(element))) return;
1822 var elementClassName = element.className;
1823 return (elementClassName.length > 0 && (elementClassName == className ||
1824 new RegExp("(^|\\s)" + className + "(\\s|$)").test(elementClassName)));
1827 addClassName: function(element, className) {
1828 if (!(element = $(element))) return;
1829 if (!element.hasClassName(className))
1830 element.className += (element.className ? ' ' : '') + className;
1834 removeClassName: function(element, className) {
1835 if (!(element = $(element))) return;
1836 element.className = element.className.replace(
1837 new RegExp("(^|\\s+)" + className + "(\\s+|$)"), ' ').strip();
1841 toggleClassName: function(element, className) {
1842 if (!(element = $(element))) return;
1843 return element[element.hasClassName(className) ?
1844 'removeClassName' : 'addClassName'](className);
1847 // removes whitespace-only text node children
1848 cleanWhitespace: function(element) {
1849 element = $(element);
1850 var node = element.firstChild;
1852 var nextNode = node.nextSibling;
1853 if (node.nodeType == 3 && !/\S/.test(node.nodeValue))
1854 element.removeChild(node);
1860 empty: function(element) {
1861 return $(element).innerHTML.blank();
1864 descendantOf: function(element, ancestor) {
1865 element = $(element), ancestor = $(ancestor);
1866 var originalAncestor = ancestor;
1868 if (element.compareDocumentPosition)
1869 return (element.compareDocumentPosition(ancestor) & 8) === 8;
1871 if (element.sourceIndex && !Prototype.Browser.Opera) {
1872 var e = element.sourceIndex, a = ancestor.sourceIndex,
1873 nextAncestor = ancestor.nextSibling;
1874 if (!nextAncestor) {
1875 do { ancestor = ancestor.parentNode; }
1876 while (!(nextAncestor = ancestor.nextSibling) && ancestor.parentNode);
1878 if (nextAncestor && nextAncestor.sourceIndex)
1879 return (e > a && e < nextAncestor.sourceIndex);
1882 while (element = element.parentNode)
1883 if (element == originalAncestor) return true;
1887 scrollTo: function(element) {
1888 element = $(element);
1889 var pos = element.cumulativeOffset();
1890 window.scrollTo(pos[0], pos[1]);
1894 getStyle: function(element, style) {
1895 element = $(element);
1896 style = style == 'float' ? 'cssFloat' : style.camelize();
1897 var value = element.style[style];
1899 var css = document.defaultView.getComputedStyle(element, null);
1900 value = css ? css[style] : null;
1902 if (style == 'opacity') return value ? parseFloat(value) : 1.0;
1903 return value == 'auto' ? null : value;
1906 getOpacity: function(element) {
1907 return $(element).getStyle('opacity');
1910 setStyle: function(element, styles) {
1911 element = $(element);
1912 var elementStyle = element.style, match;
1913 if (Object.isString(styles)) {
1914 element.style.cssText += ';' + styles;
1915 return styles.include('opacity') ?
1916 element.setOpacity(styles.match(/opacity:\s*(\d?\.?\d*)/)[1]) : element;
1918 for (var property in styles)
1919 if (property == 'opacity') element.setOpacity(styles[property]);
1921 elementStyle[(property == 'float' || property == 'cssFloat') ?
1922 (Object.isUndefined(elementStyle.styleFloat) ? 'cssFloat' : 'styleFloat') :
1923 property] = styles[property];
1928 setOpacity: function(element, value) {
1929 element = $(element);
1930 element.style.opacity = (value == 1 || value === '') ? '' :
1931 (value < 0.00001) ? 0 : value;
1935 getDimensions: function(element) {
1936 element = $(element);
1937 var display = $(element).getStyle('display');
1938 if (display != 'none' && display != null) // Safari bug
1939 return {width: element.offsetWidth, height: element.offsetHeight};
1941 // All *Width and *Height properties give 0 on elements with display none,
1942 // so enable the element temporarily
1943 var els = element.style;
1944 var originalVisibility = els.visibility;
1945 var originalPosition = els.position;
1946 var originalDisplay = els.display;
1947 els.visibility = 'hidden';
1948 els.position = 'absolute';
1949 els.display = 'block';
1950 var originalWidth = element.clientWidth;
1951 var originalHeight = element.clientHeight;
1952 els.display = originalDisplay;
1953 els.position = originalPosition;
1954 els.visibility = originalVisibility;
1955 return {width: originalWidth, height: originalHeight};
1958 makePositioned: function(element) {
1959 element = $(element);
1960 var pos = Element.getStyle(element, 'position');
1961 if (pos == 'static' || !pos) {
1962 element._madePositioned = true;
1963 element.style.position = 'relative';
1964 // Opera returns the offset relative to the positioning context, when an
1965 // element is position relative but top and left have not been defined
1967 element.style.top = 0;
1968 element.style.left = 0;
1974 undoPositioned: function(element) {
1975 element = $(element);
1976 if (element._madePositioned) {
1977 element._madePositioned = undefined;
1978 element.style.position =
1980 element.style.left =
1981 element.style.bottom =
1982 element.style.right = '';
1987 makeClipping: function(element) {
1988 element = $(element);
1989 if (element._overflow) return element;
1990 element._overflow = Element.getStyle(element, 'overflow') || 'auto';
1991 if (element._overflow !== 'hidden')
1992 element.style.overflow = 'hidden';
1996 undoClipping: function(element) {
1997 element = $(element);
1998 if (!element._overflow) return element;
1999 element.style.overflow = element._overflow == 'auto' ? '' : element._overflow;
2000 element._overflow = null;
2004 cumulativeOffset: function(element) {
2005 var valueT = 0, valueL = 0;
2007 valueT += element.offsetTop || 0;
2008 valueL += element.offsetLeft || 0;
2009 element = element.offsetParent;
2011 return Element._returnOffset(valueL, valueT);
2014 positionedOffset: function(element) {
2015 var valueT = 0, valueL = 0;
2017 valueT += element.offsetTop || 0;
2018 valueL += element.offsetLeft || 0;
2019 element = element.offsetParent;
2021 if (element.tagName == 'BODY') break;
2022 var p = Element.getStyle(element, 'position');
2023 if (p !== 'static') break;
2026 return Element._returnOffset(valueL, valueT);
2029 absolutize: function(element) {
2030 element = $(element);
2031 if (element.getStyle('position') == 'absolute') return;
2032 // Position.prepare(); // To be done manually by Scripty when it needs it.
2034 var offsets = element.positionedOffset();
2035 var top = offsets[1];
2036 var left = offsets[0];
2037 var width = element.clientWidth;
2038 var height = element.clientHeight;
2040 element._originalLeft = left - parseFloat(element.style.left || 0);
2041 element._originalTop = top - parseFloat(element.style.top || 0);
2042 element._originalWidth = element.style.width;
2043 element._originalHeight = element.style.height;
2045 element.style.position = 'absolute';
2046 element.style.top = top + 'px';
2047 element.style.left = left + 'px';
2048 element.style.width = width + 'px';
2049 element.style.height = height + 'px';
2053 relativize: function(element) {
2054 element = $(element);
2055 if (element.getStyle('position') == 'relative') return;
2056 // Position.prepare(); // To be done manually by Scripty when it needs it.
2058 element.style.position = 'relative';
2059 var top = parseFloat(element.style.top || 0) - (element._originalTop || 0);
2060 var left = parseFloat(element.style.left || 0) - (element._originalLeft || 0);
2062 element.style.top = top + 'px';
2063 element.style.left = left + 'px';
2064 element.style.height = element._originalHeight;
2065 element.style.width = element._originalWidth;
2069 cumulativeScrollOffset: function(element) {
2070 var valueT = 0, valueL = 0;
2072 valueT += element.scrollTop || 0;
2073 valueL += element.scrollLeft || 0;
2074 element = element.parentNode;
2076 return Element._returnOffset(valueL, valueT);
2079 getOffsetParent: function(element) {
2080 if (element.offsetParent) return $(element.offsetParent);
2081 if (element == document.body) return $(element);
2083 while ((element = element.parentNode) && element != document.body)
2084 if (Element.getStyle(element, 'position') != 'static')
2087 return $(document.body);
2090 viewportOffset: function(forElement) {
2091 var valueT = 0, valueL = 0;
2093 var element = forElement;
2095 valueT += element.offsetTop || 0;
2096 valueL += element.offsetLeft || 0;
2099 if (element.offsetParent == document.body &&
2100 Element.getStyle(element, 'position') == 'absolute') break;
2102 } while (element = element.offsetParent);
2104 element = forElement;
2106 if (!Prototype.Browser.Opera || element.tagName == 'BODY') {
2107 valueT -= element.scrollTop || 0;
2108 valueL -= element.scrollLeft || 0;
2110 } while (element = element.parentNode);
2112 return Element._returnOffset(valueL, valueT);
2115 clonePosition: function(element, source) {
2116 var options = Object.extend({
2123 }, arguments[2] || { });
2125 // find page position of source
2127 var p = source.viewportOffset();
2129 // find coordinate system to use
2130 element = $(element);
2133 // delta [0,0] will do fine with position: fixed elements,
2134 // position:absolute needs offsetParent deltas
2135 if (Element.getStyle(element, 'position') == 'absolute') {
2136 parent = element.getOffsetParent();
2137 delta = parent.viewportOffset();
2140 // correct by body offsets (fixes Safari)
2141 if (parent == document.body) {
2142 delta[0] -= document.body.offsetLeft;
2143 delta[1] -= document.body.offsetTop;
2147 if (options.setLeft) element.style.left = (p[0] - delta[0] + options.offsetLeft) + 'px';
2148 if (options.setTop) element.style.top = (p[1] - delta[1] + options.offsetTop) + 'px';
2149 if (options.setWidth) element.style.width = source.offsetWidth + 'px';
2150 if (options.setHeight) element.style.height = source.offsetHeight + 'px';
2155 Element.Methods.identify.counter = 1;
2157 Object.extend(Element.Methods, {
2158 getElementsBySelector: Element.Methods.select,
2159 childElements: Element.Methods.immediateDescendants
2162 Element._attributeTranslations = {
2172 if (Prototype.Browser.Opera) {
2173 Element.Methods.getStyle = Element.Methods.getStyle.wrap(
2174 function(proceed, element, style) {
2176 case 'left': case 'top': case 'right': case 'bottom':
2177 if (proceed(element, 'position') === 'static') return null;
2178 case 'height': case 'width':
2179 // returns '0px' for hidden elements; we want it to return null
2180 if (!Element.visible(element)) return null;
2182 // returns the border-box dimensions rather than the content-box
2183 // dimensions, so we subtract padding and borders from the value
2184 var dim = parseInt(proceed(element, style), 10);
2186 if (dim !== element['offset' + style.capitalize()])
2190 if (style === 'height') {
2191 properties = ['border-top-width', 'padding-top',
2192 'padding-bottom', 'border-bottom-width'];
2195 properties = ['border-left-width', 'padding-left',
2196 'padding-right', 'border-right-width'];
2198 return properties.inject(dim, function(memo, property) {
2199 var val = proceed(element, property);
2200 return val === null ? memo : memo - parseInt(val, 10);
2202 default: return proceed(element, style);
2207 Element.Methods.readAttribute = Element.Methods.readAttribute.wrap(
2208 function(proceed, element, attribute) {
2209 if (attribute === 'title') return element.title;
2210 return proceed(element, attribute);
2215 else if (Prototype.Browser.IE) {
2216 // IE doesn't report offsets correctly for static elements, so we change them
2217 // to "relative" to get the values, then change them back.
2218 Element.Methods.getOffsetParent = Element.Methods.getOffsetParent.wrap(
2219 function(proceed, element) {
2220 element = $(element);
2221 var position = element.getStyle('position');
2222 if (position !== 'static') return proceed(element);
2223 element.setStyle({ position: 'relative' });
2224 var value = proceed(element);
2225 element.setStyle({ position: position });
2230 $w('positionedOffset viewportOffset').each(function(method) {
2231 Element.Methods[method] = Element.Methods[method].wrap(
2232 function(proceed, element) {
2233 element = $(element);
2234 var position = element.getStyle('position');
2235 if (position !== 'static') return proceed(element);
2236 // Trigger hasLayout on the offset parent so that IE6 reports
2237 // accurate offsetTop and offsetLeft values for position: fixed.
2238 var offsetParent = element.getOffsetParent();
2239 if (offsetParent && offsetParent.getStyle('position') === 'fixed')
2240 offsetParent.setStyle({ zoom: 1 });
2241 element.setStyle({ position: 'relative' });
2242 var value = proceed(element);
2243 element.setStyle({ position: position });
2249 Element.Methods.getStyle = function(element, style) {
2250 element = $(element);
2251 style = (style == 'float' || style == 'cssFloat') ? 'styleFloat' : style.camelize();
2252 var value = element.style[style];
2253 if (!value && element.currentStyle) value = element.currentStyle[style];
2255 if (style == 'opacity') {
2256 if (value = (element.getStyle('filter') || '').match(/alpha\(opacity=(.*)\)/))
2257 if (value[1]) return parseFloat(value[1]) / 100;
2261 if (value == 'auto') {
2262 if ((style == 'width' || style == 'height') && (element.getStyle('display') != 'none'))
2263 return element['offset' + style.capitalize()] + 'px';
2269 Element.Methods.setOpacity = function(element, value) {
2270 function stripAlpha(filter){
2271 return filter.replace(/alpha\([^\)]*\)/gi,'');
2273 element = $(element);
2274 var currentStyle = element.currentStyle;
2275 if ((currentStyle && !currentStyle.hasLayout) ||
2276 (!currentStyle && element.style.zoom == 'normal'))
2277 element.style.zoom = 1;
2279 var filter = element.getStyle('filter'), style = element.style;
2280 if (value == 1 || value === '') {
2281 (filter = stripAlpha(filter)) ?
2282 style.filter = filter : style.removeAttribute('filter');
2284 } else if (value < 0.00001) value = 0;
2285 style.filter = stripAlpha(filter) +
2286 'alpha(opacity=' + (value * 100) + ')';
2290 Element._attributeTranslations = {
2293 'class': 'className',
2297 _getAttr: function(element, attribute) {
2298 return element.getAttribute(attribute, 2);
2300 _getAttrNode: function(element, attribute) {
2301 var node = element.getAttributeNode(attribute);
2302 return node ? node.value : "";
2304 _getEv: function(element, attribute) {
2305 attribute = element.getAttribute(attribute);
2306 return attribute ? attribute.toString().slice(23, -2) : null;
2308 _flag: function(element, attribute) {
2309 return $(element).hasAttribute(attribute) ? attribute : null;
2311 style: function(element) {
2312 return element.style.cssText.toLowerCase();
2314 title: function(element) {
2315 return element.title;
2321 Element._attributeTranslations.write = {
2322 names: Object.extend({
2323 cellpadding: 'cellPadding',
2324 cellspacing: 'cellSpacing'
2325 }, Element._attributeTranslations.read.names),
2327 checked: function(element, value) {
2328 element.checked = !!value;
2331 style: function(element, value) {
2332 element.style.cssText = value ? value : '';
2337 Element._attributeTranslations.has = {};
2339 $w('colSpan rowSpan vAlign dateTime accessKey tabIndex ' +
2340 'encType maxLength readOnly longDesc').each(function(attr) {
2341 Element._attributeTranslations.write.names[attr.toLowerCase()] = attr;
2342 Element._attributeTranslations.has[attr.toLowerCase()] = attr;
2350 action: v._getAttrNode,
2358 ondblclick: v._getEv,
2359 onmousedown: v._getEv,
2360 onmouseup: v._getEv,
2361 onmouseover: v._getEv,
2362 onmousemove: v._getEv,
2363 onmouseout: v._getEv,
2366 onkeypress: v._getEv,
2367 onkeydown: v._getEv,
2374 })(Element._attributeTranslations.read.values);
2377 else if (Prototype.Browser.Gecko && /rv:1\.8\.0/.test(navigator.userAgent)) {
2378 Element.Methods.setOpacity = function(element, value) {
2379 element = $(element);
2380 element.style.opacity = (value == 1) ? 0.999999 :
2381 (value === '') ? '' : (value < 0.00001) ? 0 : value;
2386 else if (Prototype.Browser.WebKit) {
2387 Element.Methods.setOpacity = function(element, value) {
2388 element = $(element);
2389 element.style.opacity = (value == 1 || value === '') ? '' :
2390 (value < 0.00001) ? 0 : value;
2393 if(element.tagName == 'IMG' && element.width) {
2394 element.width++; element.width--;
2396 var n = document.createTextNode(' ');
2397 element.appendChild(n);
2398 element.removeChild(n);
2404 // Safari returns margins on body which is incorrect if the child is absolutely
2405 // positioned. For performance reasons, redefine Element#cumulativeOffset for
2406 // KHTML/WebKit only.
2407 Element.Methods.cumulativeOffset = function(element) {
2408 var valueT = 0, valueL = 0;
2410 valueT += element.offsetTop || 0;
2411 valueL += element.offsetLeft || 0;
2412 if (element.offsetParent == document.body)
2413 if (Element.getStyle(element, 'position') == 'absolute') break;
2415 element = element.offsetParent;
2418 return Element._returnOffset(valueL, valueT);
2422 if (Prototype.Browser.IE || Prototype.Browser.Opera) {
2423 // IE and Opera are missing .innerHTML support for TABLE-related and SELECT elements
2424 Element.Methods.update = function(element, content) {
2425 element = $(element);
2427 if (content && content.toElement) content = content.toElement();
2428 if (Object.isElement(content)) return element.update().insert(content);
2430 content = Object.toHTML(content);
2431 var tagName = element.tagName.toUpperCase();
2433 if (tagName in Element._insertionTranslations.tags) {
2434 $A(element.childNodes).each(function(node) { element.removeChild(node) });
2435 Element._getContentFromAnonymousElement(tagName, content.stripScripts())
2436 .each(function(node) { element.appendChild(node) });
2438 else element.innerHTML = content.stripScripts();
2440 content.evalScripts.bind(content).defer();
2445 if ('outerHTML' in document.createElement('div')) {
2446 Element.Methods.replace = function(element, content) {
2447 element = $(element);
2449 if (content && content.toElement) content = content.toElement();
2450 if (Object.isElement(content)) {
2451 element.parentNode.replaceChild(content, element);
2455 content = Object.toHTML(content);
2456 var parent = element.parentNode, tagName = parent.tagName.toUpperCase();
2458 if (Element._insertionTranslations.tags[tagName]) {
2459 var nextSibling = element.next();
2460 var fragments = Element._getContentFromAnonymousElement(tagName, content.stripScripts());
2461 parent.removeChild(element);
2463 fragments.each(function(node) { parent.insertBefore(node, nextSibling) });
2465 fragments.each(function(node) { parent.appendChild(node) });
2467 else element.outerHTML = content.stripScripts();
2469 content.evalScripts.bind(content).defer();
2474 Element._returnOffset = function(l, t) {
2475 var result = [l, t];
2481 Element._getContentFromAnonymousElement = function(tagName, html) {
2482 var div = new Element('div'), t = Element._insertionTranslations.tags[tagName];
2484 div.innerHTML = t[0] + html + t[1];
2485 t[2].times(function() { div = div.firstChild });
2486 } else div.innerHTML = html;
2487 return $A(div.childNodes);
2490 Element._insertionTranslations = {
2491 before: function(element, node) {
2492 element.parentNode.insertBefore(node, element);
2494 top: function(element, node) {
2495 element.insertBefore(node, element.firstChild);
2497 bottom: function(element, node) {
2498 element.appendChild(node);
2500 after: function(element, node) {
2501 element.parentNode.insertBefore(node, element.nextSibling);
2504 TABLE: ['<table>', '</table>', 1],
2505 TBODY: ['<table><tbody>', '</tbody></table>', 2],
2506 TR: ['<table><tbody><tr>', '</tr></tbody></table>', 3],
2507 TD: ['<table><tbody><tr><td>', '</td></tr></tbody></table>', 4],
2508 SELECT: ['<select>', '</select>', 1]
2513 Object.extend(this.tags, {
2514 THEAD: this.tags.TBODY,
2515 TFOOT: this.tags.TBODY,
2518 }).call(Element._insertionTranslations);
2520 Element.Methods.Simulated = {
2521 hasAttribute: function(element, attribute) {
2522 attribute = Element._attributeTranslations.has[attribute] || attribute;
2523 var node = $(element).getAttributeNode(attribute);
2524 return node && node.specified;
2528 Element.Methods.ByTag = { };
2530 Object.extend(Element, Element.Methods);
2532 if (!Prototype.BrowserFeatures.ElementExtensions &&
2533 document.createElement('div').__proto__) {
2534 window.HTMLElement = { };
2535 window.HTMLElement.prototype = document.createElement('div').__proto__;
2536 Prototype.BrowserFeatures.ElementExtensions = true;
2539 Element.extend = (function() {
2540 if (Prototype.BrowserFeatures.SpecificElementExtensions)
2543 var Methods = { }, ByTag = Element.Methods.ByTag;
2545 var extend = Object.extend(function(element) {
2546 if (!element || element._extendedByPrototype ||
2547 element.nodeType != 1 || element == window) return element;
2549 var methods = Object.clone(Methods),
2550 tagName = element.tagName, property, value;
2552 // extend methods for specific tags
2553 if (ByTag[tagName]) Object.extend(methods, ByTag[tagName]);
2555 for (property in methods) {
2556 value = methods[property];
2557 if (Object.isFunction(value) && !(property in element))
2558 element[property] = value.methodize();
2561 element._extendedByPrototype = Prototype.emptyFunction;
2565 refresh: function() {
2566 // extend methods for all tags (Safari doesn't need this)
2567 if (!Prototype.BrowserFeatures.ElementExtensions) {
2568 Object.extend(Methods, Element.Methods);
2569 Object.extend(Methods, Element.Methods.Simulated);
2578 Element.hasAttribute = function(element, attribute) {
2579 if (element.hasAttribute) return element.hasAttribute(attribute);
2580 return Element.Methods.Simulated.hasAttribute(element, attribute);
2583 Element.addMethods = function(methods) {
2584 var F = Prototype.BrowserFeatures, T = Element.Methods.ByTag;
2587 Object.extend(Form, Form.Methods);
2588 Object.extend(Form.Element, Form.Element.Methods);
2589 Object.extend(Element.Methods.ByTag, {
2590 "FORM": Object.clone(Form.Methods),
2591 "INPUT": Object.clone(Form.Element.Methods),
2592 "SELECT": Object.clone(Form.Element.Methods),
2593 "TEXTAREA": Object.clone(Form.Element.Methods)
2597 if (arguments.length == 2) {
2598 var tagName = methods;
2599 methods = arguments[1];
2602 if (!tagName) Object.extend(Element.Methods, methods || { });
2604 if (Object.isArray(tagName)) tagName.each(extend);
2605 else extend(tagName);
2608 function extend(tagName) {
2609 tagName = tagName.toUpperCase();
2610 if (!Element.Methods.ByTag[tagName])
2611 Element.Methods.ByTag[tagName] = { };
2612 Object.extend(Element.Methods.ByTag[tagName], methods);
2615 function copy(methods, destination, onlyIfAbsent) {
2616 onlyIfAbsent = onlyIfAbsent || false;
2617 for (var property in methods) {
2618 var value = methods[property];
2619 if (!Object.isFunction(value)) continue;
2620 if (!onlyIfAbsent || !(property in destination))
2621 destination[property] = value.methodize();
2625 function findDOMClass(tagName) {
2628 "OPTGROUP": "OptGroup", "TEXTAREA": "TextArea", "P": "Paragraph",
2629 "FIELDSET": "FieldSet", "UL": "UList", "OL": "OList", "DL": "DList",
2630 "DIR": "Directory", "H1": "Heading", "H2": "Heading", "H3": "Heading",
2631 "H4": "Heading", "H5": "Heading", "H6": "Heading", "Q": "Quote",
2632 "INS": "Mod", "DEL": "Mod", "A": "Anchor", "IMG": "Image", "CAPTION":
2633 "TableCaption", "COL": "TableCol", "COLGROUP": "TableCol", "THEAD":
2634 "TableSection", "TFOOT": "TableSection", "TBODY": "TableSection", "TR":
2635 "TableRow", "TH": "TableCell", "TD": "TableCell", "FRAMESET":
2636 "FrameSet", "IFRAME": "IFrame"
2638 if (trans[tagName]) klass = 'HTML' + trans[tagName] + 'Element';
2639 if (window[klass]) return window[klass];
2640 klass = 'HTML' + tagName + 'Element';
2641 if (window[klass]) return window[klass];
2642 klass = 'HTML' + tagName.capitalize() + 'Element';
2643 if (window[klass]) return window[klass];
2645 window[klass] = { };
2646 window[klass].prototype = document.createElement(tagName).__proto__;
2647 return window[klass];
2650 if (F.ElementExtensions) {
2651 copy(Element.Methods, HTMLElement.prototype);
2652 copy(Element.Methods.Simulated, HTMLElement.prototype, true);
2655 if (F.SpecificElementExtensions) {
2656 for (var tag in Element.Methods.ByTag) {
2657 var klass = findDOMClass(tag);
2658 if (Object.isUndefined(klass)) continue;
2659 copy(T[tag], klass.prototype);
2663 Object.extend(Element, Element.Methods);
2664 delete Element.ByTag;
2666 if (Element.extend.refresh) Element.extend.refresh();
2667 Element.cache = { };
2670 document.viewport = {
2671 getDimensions: function() {
2672 var dimensions = { };
2673 var B = Prototype.Browser;
2674 $w('width height').each(function(d) {
2675 var D = d.capitalize();
2676 dimensions[d] = (B.WebKit && !document.evaluate) ? self['inner' + D] :
2677 (B.Opera) ? document.body['client' + D] : document.documentElement['client' + D];
2682 getWidth: function() {
2683 return this.getDimensions().width;
2686 getHeight: function() {
2687 return this.getDimensions().height;
2690 getScrollOffsets: function() {
2691 return Element._returnOffset(
2692 window.pageXOffset || document.documentElement.scrollLeft || document.body.scrollLeft,
2693 window.pageYOffset || document.documentElement.scrollTop || document.body.scrollTop);
2696 /* Portions of the Selector class are derived from Jack Slocum’s DomQuery,
2697 * part of YUI-Ext version 0.40, distributed under the terms of an MIT-style
2698 * license. Please see http://www.yui-ext.com/ for more information. */
2700 var Selector = Class.create({
2701 initialize: function(expression) {
2702 this.expression = expression.strip();
2703 this.compileMatcher();
2706 shouldUseXPath: function() {
2707 if (!Prototype.BrowserFeatures.XPath) return false;
2709 var e = this.expression;
2711 // Safari 3 chokes on :*-of-type and :empty
2712 if (Prototype.Browser.WebKit &&
2713 (e.include("-of-type") || e.include(":empty")))
2716 // XPath can't do namespaced attributes, nor can it read
2717 // the "checked" property from DOM nodes
2718 if ((/(\[[\w-]*?:|:checked)/).test(this.expression))
2724 compileMatcher: function() {
2725 if (this.shouldUseXPath())
2726 return this.compileXPathMatcher();
2728 var e = this.expression, ps = Selector.patterns, h = Selector.handlers,
2729 c = Selector.criteria, le, p, m;
2731 if (Selector._cache[e]) {
2732 this.matcher = Selector._cache[e];
2736 this.matcher = ["this.matcher = function(root) {",
2737 "var r = root, h = Selector.handlers, c = false, n;"];
2739 while (e && le != e && (/\S/).test(e)) {
2743 if (m = e.match(p)) {
2744 this.matcher.push(Object.isFunction(c[i]) ? c[i](m) :
2745 new Template(c[i]).evaluate(m));
2746 e = e.replace(m[0], '');
2752 this.matcher.push("return h.unique(n);\n}");
2753 eval(this.matcher.join('\n'));
2754 Selector._cache[this.expression] = this.matcher;
2757 compileXPathMatcher: function() {
2758 var e = this.expression, ps = Selector.patterns,
2759 x = Selector.xpath, le, m;
2761 if (Selector._cache[e]) {
2762 this.xpath = Selector._cache[e]; return;
2765 this.matcher = ['.//*'];
2766 while (e && le != e && (/\S/).test(e)) {
2769 if (m = e.match(ps[i])) {
2770 this.matcher.push(Object.isFunction(x[i]) ? x[i](m) :
2771 new Template(x[i]).evaluate(m));
2772 e = e.replace(m[0], '');
2778 this.xpath = this.matcher.join('');
2779 Selector._cache[this.expression] = this.xpath;
2782 findElements: function(root) {
2783 root = root || document;
2784 if (this.xpath) return document._getElementsByXPath(this.xpath, root);
2785 return this.matcher(root);
2788 match: function(element) {
2791 var e = this.expression, ps = Selector.patterns, as = Selector.assertions;
2794 while (e && le !== e && (/\S/).test(e)) {
2798 if (m = e.match(p)) {
2799 // use the Selector.assertions methods unless the selector
2802 this.tokens.push([i, Object.clone(m)]);
2803 e = e.replace(m[0], '');
2805 // reluctantly do a document-wide search
2806 // and look for a match in the array
2807 return this.findElements(document).include(element);
2813 var match = true, name, matches;
2814 for (var i = 0, token; token = this.tokens[i]; i++) {
2815 name = token[0], matches = token[1];
2816 if (!Selector.assertions[name](element, matches)) {
2817 match = false; break;
2824 toString: function() {
2825 return this.expression;
2828 inspect: function() {
2829 return "#<Selector:" + this.expression.inspect() + ">";
2833 Object.extend(Selector, {
2839 adjacent: "/following-sibling::*[1]",
2840 laterSibling: '/following-sibling::*',
2841 tagName: function(m) {
2842 if (m[1] == '*') return '';
2843 return "[local-name()='" + m[1].toLowerCase() +
2844 "' or local-name()='" + m[1].toUpperCase() + "']";
2846 className: "[contains(concat(' ', @class, ' '), ' #{1} ')]",
2848 attrPresence: function(m) {
2849 m[1] = m[1].toLowerCase();
2850 return new Template("[@#{1}]").evaluate(m);
2853 m[1] = m[1].toLowerCase();
2854 m[3] = m[5] || m[6];
2855 return new Template(Selector.xpath.operators[m[2]]).evaluate(m);
2857 pseudo: function(m) {
2858 var h = Selector.xpath.pseudos[m[1]];
2860 if (Object.isFunction(h)) return h(m);
2861 return new Template(Selector.xpath.pseudos[m[1]]).evaluate(m);
2864 '=': "[@#{1}='#{3}']",
2865 '!=': "[@#{1}!='#{3}']",
2866 '^=': "[starts-with(@#{1}, '#{3}')]",
2867 '$=': "[substring(@#{1}, (string-length(@#{1}) - string-length('#{3}') + 1))='#{3}']",
2868 '*=': "[contains(@#{1}, '#{3}')]",
2869 '~=': "[contains(concat(' ', @#{1}, ' '), ' #{3} ')]",
2870 '|=': "[contains(concat('-', @#{1}, '-'), '-#{3}-')]"
2873 'first-child': '[not(preceding-sibling::*)]',
2874 'last-child': '[not(following-sibling::*)]',
2875 'only-child': '[not(preceding-sibling::* or following-sibling::*)]',
2876 'empty': "[count(*) = 0 and (count(text()) = 0 or translate(text(), ' \t\r\n', '') = '')]",
2877 'checked': "[@checked]",
2878 'disabled': "[@disabled]",
2879 'enabled': "[not(@disabled)]",
2880 'not': function(m) {
2881 var e = m[6], p = Selector.patterns,
2882 x = Selector.xpath, le, v;
2885 while (e && le != e && (/\S/).test(e)) {
2888 if (m = e.match(p[i])) {
2889 v = Object.isFunction(x[i]) ? x[i](m) : new Template(x[i]).evaluate(m);
2890 exclusion.push("(" + v.substring(1, v.length - 1) + ")");
2891 e = e.replace(m[0], '');
2896 return "[not(" + exclusion.join(" and ") + ")]";
2898 'nth-child': function(m) {
2899 return Selector.xpath.pseudos.nth("(count(./preceding-sibling::*) + 1) ", m);
2901 'nth-last-child': function(m) {
2902 return Selector.xpath.pseudos.nth("(count(./following-sibling::*) + 1) ", m);
2904 'nth-of-type': function(m) {
2905 return Selector.xpath.pseudos.nth("position() ", m);
2907 'nth-last-of-type': function(m) {
2908 return Selector.xpath.pseudos.nth("(last() + 1 - position()) ", m);
2910 'first-of-type': function(m) {
2911 m[6] = "1"; return Selector.xpath.pseudos['nth-of-type'](m);
2913 'last-of-type': function(m) {
2914 m[6] = "1"; return Selector.xpath.pseudos['nth-last-of-type'](m);
2916 'only-of-type': function(m) {
2917 var p = Selector.xpath.pseudos; return p['first-of-type'](m) + p['last-of-type'](m);
2919 nth: function(fragment, m) {
2920 var mm, formula = m[6], predicate;
2921 if (formula == 'even') formula = '2n+0';
2922 if (formula == 'odd') formula = '2n+1';
2923 if (mm = formula.match(/^(\d+)$/)) // digit only
2924 return '[' + fragment + "= " + mm[1] + ']';
2925 if (mm = formula.match(/^(-?\d*)?n(([+-])(\d+))?/)) { // an+b
2926 if (mm[1] == "-") mm[1] = -1;
2927 var a = mm[1] ? Number(mm[1]) : 1;
2928 var b = mm[2] ? Number(mm[2]) : 0;
2929 predicate = "[((#{fragment} - #{b}) mod #{a} = 0) and " +
2930 "((#{fragment} - #{b}) div #{a} >= 0)]";
2931 return new Template(predicate).evaluate({
2932 fragment: fragment, a: a, b: b });
2939 tagName: 'n = h.tagName(n, r, "#{1}", c); c = false;',
2940 className: 'n = h.className(n, r, "#{1}", c); c = false;',
2941 id: 'n = h.id(n, r, "#{1}", c); c = false;',
2942 attrPresence: 'n = h.attrPresence(n, r, "#{1}", c); c = false;',
2944 m[3] = (m[5] || m[6]);
2945 return new Template('n = h.attr(n, r, "#{1}", "#{3}", "#{2}", c); c = false;').evaluate(m);
2947 pseudo: function(m) {
2948 if (m[6]) m[6] = m[6].replace(/"/g, '\\"');
2949 return new Template('n = h.pseudo(n, "#{1}", "#{6}", r, c); c = false;').evaluate(m);
2951 descendant: 'c = "descendant";',
2952 child: 'c = "child";',
2953 adjacent: 'c = "adjacent";',
2954 laterSibling: 'c = "laterSibling";'
2958 // combinators must be listed first
2959 // (and descendant needs to be last combinator)
2960 laterSibling: /^\s*~\s*/,
2962 adjacent: /^\s*\+\s*/,
2966 tagName: /^\s*(\*|[\w\-]+)(\b|$)?/,
2967 id: /^#([\w\-\*]+)(\b|$)/,
2968 className: /^\.([\w\-\*]+)(\b|$)/,
2970 /^:((first|last|nth|nth-last|only)(-child|-of-type)|empty|checked|(en|dis)abled|not)(\((.*?)\))?(\b|$|(?=\s|[:+~>]))/,
2971 attrPresence: /^\[([\w]+)\]/,
2972 attr: /\[((?:[\w-]*:)?[\w-]+)\s*(?:([!^$*~|]?=)\s*((['"])([^\4]*?)\4|([^'"][^\]]*?)))?\]/
2975 // for Selector.match and Element#match
2977 tagName: function(element, matches) {
2978 return matches[1].toUpperCase() == element.tagName.toUpperCase();
2981 className: function(element, matches) {
2982 return Element.hasClassName(element, matches[1]);
2985 id: function(element, matches) {
2986 return element.id === matches[1];
2989 attrPresence: function(element, matches) {
2990 return Element.hasAttribute(element, matches[1]);
2993 attr: function(element, matches) {
2994 var nodeValue = Element.readAttribute(element, matches[1]);
2995 return nodeValue && Selector.operators[matches[2]](nodeValue, matches[5] || matches[6]);
3000 // UTILITY FUNCTIONS
3001 // joins two collections
3002 concat: function(a, b) {
3003 for (var i = 0, node; node = b[i]; i++)
3008 // marks an array of nodes for counting
3009 mark: function(nodes) {
3010 var _true = Prototype.emptyFunction;
3011 for (var i = 0, node; node = nodes[i]; i++)
3012 node._countedByPrototype = _true;
3016 unmark: function(nodes) {
3017 for (var i = 0, node; node = nodes[i]; i++)
3018 node._countedByPrototype = undefined;
3022 // mark each child node with its position (for nth calls)
3023 // "ofType" flag indicates whether we're indexing for nth-of-type
3024 // rather than nth-child
3025 index: function(parentNode, reverse, ofType) {
3026 parentNode._countedByPrototype = Prototype.emptyFunction;
3028 for (var nodes = parentNode.childNodes, i = nodes.length - 1, j = 1; i >= 0; i--) {
3029 var node = nodes[i];
3030 if (node.nodeType == 1 && (!ofType || node._countedByPrototype)) node.nodeIndex = j++;
3033 for (var i = 0, j = 1, nodes = parentNode.childNodes; node = nodes[i]; i++)
3034 if (node.nodeType == 1 && (!ofType || node._countedByPrototype)) node.nodeIndex = j++;
3038 // filters out duplicates and extends all nodes
3039 unique: function(nodes) {
3040 if (nodes.length == 0) return nodes;
3041 var results = [], n;
3042 for (var i = 0, l = nodes.length; i < l; i++)
3043 if (!(n = nodes[i])._countedByPrototype) {
3044 n._countedByPrototype = Prototype.emptyFunction;
3045 results.push(Element.extend(n));
3047 return Selector.handlers.unmark(results);
3050 // COMBINATOR FUNCTIONS
3051 descendant: function(nodes) {
3052 var h = Selector.handlers;
3053 for (var i = 0, results = [], node; node = nodes[i]; i++)
3054 h.concat(results, node.getElementsByTagName('*'));
3058 child: function(nodes) {
3059 var h = Selector.handlers;
3060 for (var i = 0, results = [], node; node = nodes[i]; i++) {
3061 for (var j = 0, child; child = node.childNodes[j]; j++)
3062 if (child.nodeType == 1 && child.tagName != '!') results.push(child);
3067 adjacent: function(nodes) {
3068 for (var i = 0, results = [], node; node = nodes[i]; i++) {
3069 var next = this.nextElementSibling(node);
3070 if (next) results.push(next);
3075 laterSibling: function(nodes) {
3076 var h = Selector.handlers;
3077 for (var i = 0, results = [], node; node = nodes[i]; i++)
3078 h.concat(results, Element.nextSiblings(node));
3082 nextElementSibling: function(node) {
3083 while (node = node.nextSibling)
3084 if (node.nodeType == 1) return node;
3088 previousElementSibling: function(node) {
3089 while (node = node.previousSibling)
3090 if (node.nodeType == 1) return node;
3095 tagName: function(nodes, root, tagName, combinator) {
3096 var uTagName = tagName.toUpperCase();
3097 var results = [], h = Selector.handlers;
3100 // fastlane for ordinary descendant combinators
3101 if (combinator == "descendant") {
3102 for (var i = 0, node; node = nodes[i]; i++)
3103 h.concat(results, node.getElementsByTagName(tagName));
3105 } else nodes = this[combinator](nodes);
3106 if (tagName == "*") return nodes;
3108 for (var i = 0, node; node = nodes[i]; i++)
3109 if (node.tagName.toUpperCase() === uTagName) results.push(node);
3111 } else return root.getElementsByTagName(tagName);
3114 id: function(nodes, root, id, combinator) {
3115 var targetNode = $(id), h = Selector.handlers;
3116 if (!targetNode) return [];
3117 if (!nodes && root == document) return [targetNode];
3120 if (combinator == 'child') {
3121 for (var i = 0, node; node = nodes[i]; i++)
3122 if (targetNode.parentNode == node) return [targetNode];
3123 } else if (combinator == 'descendant') {
3124 for (var i = 0, node; node = nodes[i]; i++)
3125 if (Element.descendantOf(targetNode, node)) return [targetNode];
3126 } else if (combinator == 'adjacent') {
3127 for (var i = 0, node; node = nodes[i]; i++)
3128 if (Selector.handlers.previousElementSibling(targetNode) == node)
3129 return [targetNode];
3130 } else nodes = h[combinator](nodes);
3132 for (var i = 0, node; node = nodes[i]; i++)
3133 if (node == targetNode) return [targetNode];
3136 return (targetNode && Element.descendantOf(targetNode, root)) ? [targetNode] : [];
3139 className: function(nodes, root, className, combinator) {
3140 if (nodes && combinator) nodes = this[combinator](nodes);
3141 return Selector.handlers.byClassName(nodes, root, className);
3144 byClassName: function(nodes, root, className) {
3145 if (!nodes) nodes = Selector.handlers.descendant([root]);
3146 var needle = ' ' + className + ' ';
3147 for (var i = 0, results = [], node, nodeClassName; node = nodes[i]; i++) {
3148 nodeClassName = node.className;
3149 if (nodeClassName.length == 0) continue;
3150 if (nodeClassName == className || (' ' + nodeClassName + ' ').include(needle))
3156 attrPresence: function(nodes, root, attr, combinator) {
3157 if (!nodes) nodes = root.getElementsByTagName("*");
3158 if (nodes && combinator) nodes = this[combinator](nodes);
3160 for (var i = 0, node; node = nodes[i]; i++)
3161 if (Element.hasAttribute(node, attr)) results.push(node);
3165 attr: function(nodes, root, attr, value, operator, combinator) {
3166 if (!nodes) nodes = root.getElementsByTagName("*");
3167 if (nodes && combinator) nodes = this[combinator](nodes);
3168 var handler = Selector.operators[operator], results = [];
3169 for (var i = 0, node; node = nodes[i]; i++) {
3170 var nodeValue = Element.readAttribute(node, attr);
3171 if (nodeValue === null) continue;
3172 if (handler(nodeValue, value)) results.push(node);
3177 pseudo: function(nodes, name, value, root, combinator) {
3178 if (nodes && combinator) nodes = this[combinator](nodes);
3179 if (!nodes) nodes = root.getElementsByTagName("*");
3180 return Selector.pseudos[name](nodes, value, root);
3185 'first-child': function(nodes, value, root) {
3186 for (var i = 0, results = [], node; node = nodes[i]; i++) {
3187 if (Selector.handlers.previousElementSibling(node)) continue;
3192 'last-child': function(nodes, value, root) {
3193 for (var i = 0, results = [], node; node = nodes[i]; i++) {
3194 if (Selector.handlers.nextElementSibling(node)) continue;
3199 'only-child': function(nodes, value, root) {
3200 var h = Selector.handlers;
3201 for (var i = 0, results = [], node; node = nodes[i]; i++)
3202 if (!h.previousElementSibling(node) && !h.nextElementSibling(node))
3206 'nth-child': function(nodes, formula, root) {
3207 return Selector.pseudos.nth(nodes, formula, root);
3209 'nth-last-child': function(nodes, formula, root) {
3210 return Selector.pseudos.nth(nodes, formula, root, true);
3212 'nth-of-type': function(nodes, formula, root) {
3213 return Selector.pseudos.nth(nodes, formula, root, false, true);
3215 'nth-last-of-type': function(nodes, formula, root) {
3216 return Selector.pseudos.nth(nodes, formula, root, true, true);
3218 'first-of-type': function(nodes, formula, root) {
3219 return Selector.pseudos.nth(nodes, "1", root, false, true);
3221 'last-of-type': function(nodes, formula, root) {
3222 return Selector.pseudos.nth(nodes, "1", root, true, true);
3224 'only-of-type': function(nodes, formula, root) {
3225 var p = Selector.pseudos;
3226 return p['last-of-type'](p['first-of-type'](nodes, formula, root), formula, root);
3229 // handles the an+b logic
3230 getIndices: function(a, b, total) {
3231 if (a == 0) return b > 0 ? [b] : [];
3232 return $R(1, total).inject([], function(memo, i) {
3233 if (0 == (i - b) % a && (i - b) / a >= 0) memo.push(i);
3238 // handles nth(-last)-child, nth(-last)-of-type, and (first|last)-of-type
3239 nth: function(nodes, formula, root, reverse, ofType) {
3240 if (nodes.length == 0) return [];
3241 if (formula == 'even') formula = '2n+0';
3242 if (formula == 'odd') formula = '2n+1';
3243 var h = Selector.handlers, results = [], indexed = [], m;
3245 for (var i = 0, node; node = nodes[i]; i++) {
3246 if (!node.parentNode._countedByPrototype) {
3247 h.index(node.parentNode, reverse, ofType);
3248 indexed.push(node.parentNode);
3251 if (formula.match(/^\d+$/)) { // just a number
3252 formula = Number(formula);
3253 for (var i = 0, node; node = nodes[i]; i++)
3254 if (node.nodeIndex == formula) results.push(node);
3255 } else if (m = formula.match(/^(-?\d*)?n(([+-])(\d+))?/)) { // an+b
3256 if (m[1] == "-") m[1] = -1;
3257 var a = m[1] ? Number(m[1]) : 1;
3258 var b = m[2] ? Number(m[2]) : 0;
3259 var indices = Selector.pseudos.getIndices(a, b, nodes.length);
3260 for (var i = 0, node, l = indices.length; node = nodes[i]; i++) {
3261 for (var j = 0; j < l; j++)
3262 if (node.nodeIndex == indices[j]) results.push(node);
3270 'empty': function(nodes, value, root) {
3271 for (var i = 0, results = [], node; node = nodes[i]; i++) {
3272 // IE treats comments as element nodes
3273 if (node.tagName == '!' || (node.firstChild && !node.innerHTML.match(/^\s*$/))) continue;
3279 'not': function(nodes, selector, root) {
3280 var h = Selector.handlers, selectorType, m;
3281 var exclusions = new Selector(selector).findElements(root);
3283 for (var i = 0, results = [], node; node = nodes[i]; i++)
3284 if (!node._countedByPrototype) results.push(node);
3285 h.unmark(exclusions);
3289 'enabled': function(nodes, value, root) {
3290 for (var i = 0, results = [], node; node = nodes[i]; i++)
3291 if (!node.disabled) results.push(node);
3295 'disabled': function(nodes, value, root) {
3296 for (var i = 0, results = [], node; node = nodes[i]; i++)
3297 if (node.disabled) results.push(node);
3301 'checked': function(nodes, value, root) {
3302 for (var i = 0, results = [], node; node = nodes[i]; i++)
3303 if (node.checked) results.push(node);
3309 '=': function(nv, v) { return nv == v; },
3310 '!=': function(nv, v) { return nv != v; },
3311 '^=': function(nv, v) { return nv.startsWith(v); },
3312 '$=': function(nv, v) { return nv.endsWith(v); },
3313 '*=': function(nv, v) { return nv.include(v); },
3314 '~=': function(nv, v) { return (' ' + nv + ' ').include(' ' + v + ' '); },
3315 '|=': function(nv, v) { return ('-' + nv.toUpperCase() + '-').include('-' + v.toUpperCase() + '-'); }
3318 split: function(expression) {
3319 var expressions = [];
3320 expression.scan(/(([\w#:.~>+()\s-]+|\*|\[.*?\])+)\s*(,|$)/, function(m) {
3321 expressions.push(m[1].strip());
3326 matchElements: function(elements, expression) {
3327 var matches = $$(expression), h = Selector.handlers;
3329 for (var i = 0, results = [], element; element = elements[i]; i++)
3330 if (element._countedByPrototype) results.push(element);
3335 findElement: function(elements, expression, index) {
3336 if (Object.isNumber(expression)) {
3337 index = expression; expression = false;
3339 return Selector.matchElements(elements, expression || '*')[index || 0];
3342 findChildElements: function(element, expressions) {
3343 expressions = Selector.split(expressions.join(','));
3344 var results = [], h = Selector.handlers;
3345 for (var i = 0, l = expressions.length, selector; i < l; i++) {
3346 selector = new Selector(expressions[i].strip());
3347 h.concat(results, selector.findElements(element));
3349 return (l > 1) ? h.unique(results) : results;
3353 if (Prototype.Browser.IE) {
3354 Object.extend(Selector.handlers, {
3355 // IE returns comment nodes on getElementsByTagName("*").
3357 concat: function(a, b) {
3358 for (var i = 0, node; node = b[i]; i++)
3359 if (node.tagName !== "!") a.push(node);
3363 // IE improperly serializes _countedByPrototype in (inner|outer)HTML.
3364 unmark: function(nodes) {
3365 for (var i = 0, node; node = nodes[i]; i++)
3366 node.removeAttribute('_countedByPrototype');
3373 return Selector.findChildElements(document, $A(arguments));
3376 reset: function(form) {
3381 serializeElements: function(elements, options) {
3382 if (typeof options != 'object') options = { hash: !!options };
3383 else if (Object.isUndefined(options.hash)) options.hash = true;
3384 var key, value, submitted = false, submit = options.submit;
3386 var data = elements.inject({ }, function(result, element) {
3387 if (!element.disabled && element.name) {
3388 key = element.name; value = $(element).getValue();
3389 if (value != null && (element.type != 'submit' || (!submitted &&
3390 submit !== false && (!submit || key == submit) && (submitted = true)))) {
3391 if (key in result) {
3392 // a key is already present; construct an array of values
3393 if (!Object.isArray(result[key])) result[key] = [result[key]];
3394 result[key].push(value);
3396 else result[key] = value;
3402 return options.hash ? data : Object.toQueryString(data);
3407 serialize: function(form, options) {
3408 return Form.serializeElements(Form.getElements(form), options);
3411 getElements: function(form) {
3412 return $A($(form).getElementsByTagName('*')).inject([],
3413 function(elements, child) {
3414 if (Form.Element.Serializers[child.tagName.toLowerCase()])
3415 elements.push(Element.extend(child));
3421 getInputs: function(form, typeName, name) {
3423 var inputs = form.getElementsByTagName('input');
3425 if (!typeName && !name) return $A(inputs).map(Element.extend);
3427 for (var i = 0, matchingInputs = [], length = inputs.length; i < length; i++) {
3428 var input = inputs[i];
3429 if ((typeName && input.type != typeName) || (name && input.name != name))
3431 matchingInputs.push(Element.extend(input));
3434 return matchingInputs;
3437 disable: function(form) {
3439 Form.getElements(form).invoke('disable');
3443 enable: function(form) {
3445 Form.getElements(form).invoke('enable');
3449 findFirstElement: function(form) {
3450 var elements = $(form).getElements().findAll(function(element) {
3451 return 'hidden' != element.type && !element.disabled;
3453 var firstByIndex = elements.findAll(function(element) {
3454 return element.hasAttribute('tabIndex') && element.tabIndex >= 0;
3455 }).sortBy(function(element) { return element.tabIndex }).first();
3457 return firstByIndex ? firstByIndex : elements.find(function(element) {
3458 return ['input', 'select', 'textarea'].include(element.tagName.toLowerCase());
3462 focusFirstElement: function(form) {
3464 form.findFirstElement().activate();
3468 request: function(form, options) {
3469 form = $(form), options = Object.clone(options || { });
3471 var params = options.parameters, action = form.readAttribute('action') || '';
3472 if (action.blank()) action = window.location.href;
3473 options.parameters = form.serialize(true);
3476 if (Object.isString(params)) params = params.toQueryParams();
3477 Object.extend(options.parameters, params);
3480 if (form.hasAttribute('method') && !options.method)
3481 options.method = form.method;
3483 return new Ajax.Request(action, options);
3487 /*--------------------------------------------------------------------------*/
3490 focus: function(element) {
3495 select: function(element) {
3496 $(element).select();
3501 Form.Element.Methods = {
3502 serialize: function(element) {
3503 element = $(element);
3504 if (!element.disabled && element.name) {
3505 var value = element.getValue();
3506 if (value != undefined) {
3508 pair[element.name] = value;
3509 return Object.toQueryString(pair);
3515 getValue: function(element) {
3516 element = $(element);
3517 var method = element.tagName.toLowerCase();
3518 return Form.Element.Serializers[method](element);
3521 setValue: function(element, value) {
3522 element = $(element);
3523 var method = element.tagName.toLowerCase();
3524 Form.Element.Serializers[method](element, value);
3528 clear: function(element) {
3529 $(element).value = '';
3533 present: function(element) {
3534 return $(element).value != '';
3537 activate: function(element) {
3538 element = $(element);
3541 if (element.select && (element.tagName.toLowerCase() != 'input' ||
3542 !['button', 'reset', 'submit'].include(element.type)))
3548 disable: function(element) {
3549 element = $(element);
3551 element.disabled = true;
3555 enable: function(element) {
3556 element = $(element);
3557 element.disabled = false;
3562 /*--------------------------------------------------------------------------*/
3564 var Field = Form.Element;
3565 var $F = Form.Element.Methods.getValue;
3567 /*--------------------------------------------------------------------------*/