1 /* Prototype JavaScript framework, version 1.7
2 * (c) 2005-2010 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 *--------------------------------------------------------------------------*/
14 var ua = navigator.userAgent;
15 var isOpera = Object.prototype.toString.call(window.opera) == '[object Opera]';
17 IE: !!window.attachEvent && !isOpera,
19 WebKit: ua.indexOf('AppleWebKit/') > -1,
20 Gecko: ua.indexOf('Gecko') > -1 && ua.indexOf('KHTML') === -1,
21 MobileSafari: /Apple.*Mobile/.test(ua)
26 XPath: !!document.evaluate,
28 SelectorsAPI: !!document.querySelector,
30 ElementExtensions: (function() {
31 var constructor = window.Element || window.HTMLElement;
32 return !!(constructor && constructor.prototype);
34 SpecificElementExtensions: (function() {
35 if (typeof window.HTMLDivElement !== 'undefined')
38 var div = document.createElement('div'),
39 form = document.createElement('form'),
42 if (div['__proto__'] && (div['__proto__'] !== form['__proto__'])) {
52 ScriptFragment: '<script[^>]*>([\\S\\s]*?)<\/script>',
53 JSONFilter: /^\/\*-secure-([\s\S]*)\*\/\s*$/,
55 emptyFunction: function() { },
57 K: function(x) { return x }
60 if (Prototype.Browser.MobileSafari)
61 Prototype.BrowserFeatures.SpecificElementExtensions = false;
71 for (var i = 0, length = arguments.length; i < length; i++) {
72 var lambda = arguments[i];
74 returnValue = lambda();
83 /* Based on Alex Arnell's inheritance implementation. */
85 var Class = (function() {
87 var IS_DONTENUM_BUGGY = (function(){
88 for (var p in { toString: 1 }) {
89 if (p === 'toString') return false;
94 function subclass() {};
96 var parent = null, properties = $A(arguments);
97 if (Object.isFunction(properties[0]))
98 parent = properties.shift();
101 this.initialize.apply(this, arguments);
104 Object.extend(klass, Class.Methods);
105 klass.superclass = parent;
106 klass.subclasses = [];
109 subclass.prototype = parent.prototype;
110 klass.prototype = new subclass;
111 parent.subclasses.push(klass);
114 for (var i = 0, length = properties.length; i < length; i++)
115 klass.addMethods(properties[i]);
117 if (!klass.prototype.initialize)
118 klass.prototype.initialize = Prototype.emptyFunction;
120 klass.prototype.constructor = klass;
124 function addMethods(source) {
125 var ancestor = this.superclass && this.superclass.prototype,
126 properties = Object.keys(source);
128 if (IS_DONTENUM_BUGGY) {
129 if (source.toString != Object.prototype.toString)
130 properties.push("toString");
131 if (source.valueOf != Object.prototype.valueOf)
132 properties.push("valueOf");
135 for (var i = 0, length = properties.length; i < length; i++) {
136 var property = properties[i], value = source[property];
137 if (ancestor && Object.isFunction(value) &&
138 value.argumentNames()[0] == "$super") {
140 value = (function(m) {
141 return function() { return ancestor[m].apply(this, arguments); };
142 })(property).wrap(method);
144 value.valueOf = method.valueOf.bind(method);
145 value.toString = method.toString.bind(method);
147 this.prototype[property] = value;
156 addMethods: addMethods
162 var _toString = Object.prototype.toString,
164 UNDEFINED_TYPE = 'Undefined',
165 BOOLEAN_TYPE = 'Boolean',
166 NUMBER_TYPE = 'Number',
167 STRING_TYPE = 'String',
168 OBJECT_TYPE = 'Object',
169 FUNCTION_CLASS = '[object Function]',
170 BOOLEAN_CLASS = '[object Boolean]',
171 NUMBER_CLASS = '[object Number]',
172 STRING_CLASS = '[object String]',
173 ARRAY_CLASS = '[object Array]',
174 DATE_CLASS = '[object Date]',
175 NATIVE_JSON_STRINGIFY_SUPPORT = window.JSON &&
176 typeof JSON.stringify === 'function' &&
177 JSON.stringify(0) === '0' &&
178 typeof JSON.stringify(Prototype.K) === 'undefined';
182 case null: return NULL_TYPE;
183 case (void 0): return UNDEFINED_TYPE;
187 case 'boolean': return BOOLEAN_TYPE;
188 case 'number': return NUMBER_TYPE;
189 case 'string': return STRING_TYPE;
194 function extend(destination, source) {
195 for (var property in source)
196 destination[property] = source[property];
200 function inspect(object) {
202 if (isUndefined(object)) return 'undefined';
203 if (object === null) return 'null';
204 return object.inspect ? object.inspect() : String(object);
206 if (e instanceof RangeError) return '...';
211 function toJSON(value) {
212 return Str('', { '': value }, []);
215 function Str(key, holder, stack) {
216 var value = holder[key],
219 if (Type(value) === OBJECT_TYPE && typeof value.toJSON === 'function') {
220 value = value.toJSON(key);
223 var _class = _toString.call(value);
229 value = value.valueOf();
233 case null: return 'null';
234 case true: return 'true';
235 case false: return 'false';
241 return value.inspect(true);
243 return isFinite(value) ? String(value) : 'null';
246 for (var i = 0, length = stack.length; i < length; i++) {
247 if (stack[i] === value) { throw new TypeError(); }
252 if (_class === ARRAY_CLASS) {
253 for (var i = 0, length = value.length; i < length; i++) {
254 var str = Str(i, value, stack);
255 partial.push(typeof str === 'undefined' ? 'null' : str);
257 partial = '[' + partial.join(',') + ']';
259 var keys = Object.keys(value);
260 for (var i = 0, length = keys.length; i < length; i++) {
261 var key = keys[i], str = Str(key, value, stack);
262 if (typeof str !== "undefined") {
263 partial.push(key.inspect(true)+ ':' + str);
266 partial = '{' + partial.join(',') + '}';
273 function stringify(object) {
274 return JSON.stringify(object);
277 function toQueryString(object) {
278 return $H(object).toQueryString();
281 function toHTML(object) {
282 return object && object.toHTML ? object.toHTML() : String.interpret(object);
285 function keys(object) {
286 if (Type(object) !== OBJECT_TYPE) { throw new TypeError(); }
288 for (var property in object) {
289 if (object.hasOwnProperty(property)) {
290 results.push(property);
296 function values(object) {
298 for (var property in object)
299 results.push(object[property]);
303 function clone(object) {
304 return extend({ }, object);
307 function isElement(object) {
308 return !!(object && object.nodeType == 1);
311 function isArray(object) {
312 return _toString.call(object) === ARRAY_CLASS;
315 var hasNativeIsArray = (typeof Array.isArray == 'function')
316 && Array.isArray([]) && !Array.isArray({});
318 if (hasNativeIsArray) {
319 isArray = Array.isArray;
322 function isHash(object) {
323 return object instanceof Hash;
326 function isFunction(object) {
327 return _toString.call(object) === FUNCTION_CLASS;
330 function isString(object) {
331 return _toString.call(object) === STRING_CLASS;
334 function isNumber(object) {
335 return _toString.call(object) === NUMBER_CLASS;
338 function isDate(object) {
339 return _toString.call(object) === DATE_CLASS;
342 function isUndefined(object) {
343 return typeof object === "undefined";
349 toJSON: NATIVE_JSON_STRINGIFY_SUPPORT ? stringify : toJSON,
350 toQueryString: toQueryString,
352 keys: Object.keys || keys,
355 isElement: isElement,
358 isFunction: isFunction,
362 isUndefined: isUndefined
365 Object.extend(Function.prototype, (function() {
366 var slice = Array.prototype.slice;
368 function update(array, args) {
369 var arrayLength = array.length, length = args.length;
370 while (length--) array[arrayLength + length] = args[length];
374 function merge(array, args) {
375 array = slice.call(array, 0);
376 return update(array, args);
379 function argumentNames() {
380 var names = this.toString().match(/^[\s\(]*function[^(]*\(([^)]*)\)/)[1]
381 .replace(/\/\/.*?[\r\n]|\/\*(?:.|[\r\n])*?\*\//g, '')
382 .replace(/\s+/g, '').split(',');
383 return names.length == 1 && !names[0] ? [] : names;
386 function bind(context) {
387 if (arguments.length < 2 && Object.isUndefined(arguments[0])) return this;
388 var __method = this, args = slice.call(arguments, 1);
390 var a = merge(args, arguments);
391 return __method.apply(context, a);
395 function bindAsEventListener(context) {
396 var __method = this, args = slice.call(arguments, 1);
397 return function(event) {
398 var a = update([event || window.event], args);
399 return __method.apply(context, a);
404 if (!arguments.length) return this;
405 var __method = this, args = slice.call(arguments, 0);
407 var a = merge(args, arguments);
408 return __method.apply(this, a);
412 function delay(timeout) {
413 var __method = this, args = slice.call(arguments, 1);
414 timeout = timeout * 1000;
415 return window.setTimeout(function() {
416 return __method.apply(__method, args);
421 var args = update([0.01], arguments);
422 return this.delay.apply(this, args);
425 function wrap(wrapper) {
428 var a = update([__method.bind(this)], arguments);
429 return wrapper.apply(this, a);
433 function methodize() {
434 if (this._methodized) return this._methodized;
436 return this._methodized = function() {
437 var a = update([this], arguments);
438 return __method.apply(null, a);
443 argumentNames: argumentNames,
445 bindAsEventListener: bindAsEventListener,
459 function toISOString() {
460 return this.getUTCFullYear() + '-' +
461 (this.getUTCMonth() + 1).toPaddedString(2) + '-' +
462 this.getUTCDate().toPaddedString(2) + 'T' +
463 this.getUTCHours().toPaddedString(2) + ':' +
464 this.getUTCMinutes().toPaddedString(2) + ':' +
465 this.getUTCSeconds().toPaddedString(2) + 'Z';
470 return this.toISOString();
473 if (!proto.toISOString) proto.toISOString = toISOString;
474 if (!proto.toJSON) proto.toJSON = toJSON;
479 RegExp.prototype.match = RegExp.prototype.test;
481 RegExp.escape = function(str) {
482 return String(str).replace(/([.*+?^=!:${}()|[\]\/\\])/g, '\\$1');
484 var PeriodicalExecuter = Class.create({
485 initialize: function(callback, frequency) {
486 this.callback = callback;
487 this.frequency = frequency;
488 this.currentlyExecuting = false;
490 this.registerCallback();
493 registerCallback: function() {
494 this.timer = setInterval(this.onTimerEvent.bind(this), this.frequency * 1000);
497 execute: function() {
502 if (!this.timer) return;
503 clearInterval(this.timer);
507 onTimerEvent: function() {
508 if (!this.currentlyExecuting) {
510 this.currentlyExecuting = true;
512 this.currentlyExecuting = false;
514 this.currentlyExecuting = false;
520 Object.extend(String, {
521 interpret: function(value) {
522 return value == null ? '' : String(value);
534 Object.extend(String.prototype, (function() {
535 var NATIVE_JSON_PARSE_SUPPORT = window.JSON &&
536 typeof JSON.parse === 'function' &&
537 JSON.parse('{"test": true}').test;
539 function prepareReplacement(replacement) {
540 if (Object.isFunction(replacement)) return replacement;
541 var template = new Template(replacement);
542 return function(match) { return template.evaluate(match) };
545 function gsub(pattern, replacement) {
546 var result = '', source = this, match;
547 replacement = prepareReplacement(replacement);
549 if (Object.isString(pattern))
550 pattern = RegExp.escape(pattern);
552 if (!(pattern.length || pattern.source)) {
553 replacement = replacement('');
554 return replacement + source.split('').join(replacement) + replacement;
557 while (source.length > 0) {
558 if (match = source.match(pattern)) {
559 result += source.slice(0, match.index);
560 result += String.interpret(replacement(match));
561 source = source.slice(match.index + match[0].length);
563 result += source, source = '';
569 function sub(pattern, replacement, count) {
570 replacement = prepareReplacement(replacement);
571 count = Object.isUndefined(count) ? 1 : count;
573 return this.gsub(pattern, function(match) {
574 if (--count < 0) return match[0];
575 return replacement(match);
579 function scan(pattern, iterator) {
580 this.gsub(pattern, iterator);
584 function truncate(length, truncation) {
585 length = length || 30;
586 truncation = Object.isUndefined(truncation) ? '...' : truncation;
587 return this.length > length ?
588 this.slice(0, length - truncation.length) + truncation : String(this);
592 return this.replace(/^\s+/, '').replace(/\s+$/, '');
595 function stripTags() {
596 return this.replace(/<\w+(\s+("[^"]*"|'[^']*'|[^>])+)?>|<\/\w+>/gi, '');
599 function stripScripts() {
600 return this.replace(new RegExp(Prototype.ScriptFragment, 'img'), '');
603 function extractScripts() {
604 var matchAll = new RegExp(Prototype.ScriptFragment, 'img'),
605 matchOne = new RegExp(Prototype.ScriptFragment, 'im');
606 return (this.match(matchAll) || []).map(function(scriptTag) {
607 return (scriptTag.match(matchOne) || ['', ''])[1];
611 function evalScripts() {
612 return this.extractScripts().map(function(script) { return eval(script) });
615 function escapeHTML() {
616 return this.replace(/&/g,'&').replace(/</g,'<').replace(/>/g,'>');
619 function unescapeHTML() {
620 return this.stripTags().replace(/</g,'<').replace(/>/g,'>').replace(/&/g,'&');
624 function toQueryParams(separator) {
625 var match = this.strip().match(/([^?#]*)(#.*)?$/);
626 if (!match) return { };
628 return match[1].split(separator || '&').inject({ }, function(hash, pair) {
629 if ((pair = pair.split('='))[0]) {
630 var key = decodeURIComponent(pair.shift()),
631 value = pair.length > 1 ? pair.join('=') : pair[0];
633 if (value != undefined) value = decodeURIComponent(value);
636 if (!Object.isArray(hash[key])) hash[key] = [hash[key]];
637 hash[key].push(value);
639 else hash[key] = value;
646 return this.split('');
650 return this.slice(0, this.length - 1) +
651 String.fromCharCode(this.charCodeAt(this.length - 1) + 1);
654 function times(count) {
655 return count < 1 ? '' : new Array(count + 1).join(this);
658 function camelize() {
659 return this.replace(/-+(.)?/g, function(match, chr) {
660 return chr ? chr.toUpperCase() : '';
664 function capitalize() {
665 return this.charAt(0).toUpperCase() + this.substring(1).toLowerCase();
668 function underscore() {
669 return this.replace(/::/g, '/')
670 .replace(/([A-Z]+)([A-Z][a-z])/g, '$1_$2')
671 .replace(/([a-z\d])([A-Z])/g, '$1_$2')
676 function dasherize() {
677 return this.replace(/_/g, '-');
680 function inspect(useDoubleQuotes) {
681 var escapedString = this.replace(/[\x00-\x1f\\]/g, function(character) {
682 if (character in String.specialChar) {
683 return String.specialChar[character];
685 return '\\u00' + character.charCodeAt().toPaddedString(2, 16);
687 if (useDoubleQuotes) return '"' + escapedString.replace(/"/g, '\\"') + '"';
688 return "'" + escapedString.replace(/'/g, '\\\'') + "'";
691 function unfilterJSON(filter) {
692 return this.replace(filter || Prototype.JSONFilter, '$1');
697 if (str.blank()) return false;
698 str = str.replace(/\\(?:["\\\/bfnrt]|u[0-9a-fA-F]{4})/g, '@');
699 str = str.replace(/"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g, ']');
700 str = str.replace(/(?:^|:|,)(?:\s*\[)+/g, '');
701 return (/^[\],:{}\s]*$/).test(str);
704 function evalJSON(sanitize) {
705 var json = this.unfilterJSON(),
706 cx = /[\u0000\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g;
708 json = json.replace(cx, function (a) {
709 return '\\u' + ('0000' + a.charCodeAt(0).toString(16)).slice(-4);
713 if (!sanitize || json.isJSON()) return eval('(' + json + ')');
715 throw new SyntaxError('Badly formed JSON string: ' + this.inspect());
718 function parseJSON() {
719 var json = this.unfilterJSON();
720 return JSON.parse(json);
723 function include(pattern) {
724 return this.indexOf(pattern) > -1;
727 function startsWith(pattern) {
728 return this.lastIndexOf(pattern, 0) === 0;
731 function endsWith(pattern) {
732 var d = this.length - pattern.length;
733 return d >= 0 && this.indexOf(pattern, d) === d;
741 return /^\s*$/.test(this);
744 function interpolate(object, pattern) {
745 return new Template(this, pattern).evaluate(object);
753 strip: String.prototype.trim || strip,
754 stripTags: stripTags,
755 stripScripts: stripScripts,
756 extractScripts: extractScripts,
757 evalScripts: evalScripts,
758 escapeHTML: escapeHTML,
759 unescapeHTML: unescapeHTML,
760 toQueryParams: toQueryParams,
761 parseQuery: toQueryParams,
766 capitalize: capitalize,
767 underscore: underscore,
768 dasherize: dasherize,
770 unfilterJSON: unfilterJSON,
772 evalJSON: NATIVE_JSON_PARSE_SUPPORT ? parseJSON : evalJSON,
774 startsWith: startsWith,
778 interpolate: interpolate
782 var Template = Class.create({
783 initialize: function(template, pattern) {
784 this.template = template.toString();
785 this.pattern = pattern || Template.Pattern;
788 evaluate: function(object) {
789 if (object && Object.isFunction(object.toTemplateReplacements))
790 object = object.toTemplateReplacements();
792 return this.template.gsub(this.pattern, function(match) {
793 if (object == null) return (match[1] + '');
795 var before = match[1] || '';
796 if (before == '\\') return match[2];
798 var ctx = object, expr = match[3],
799 pattern = /^([^.[]+|\[((?:.*?[^\\])?)\])(\.|\[|$)/;
801 match = pattern.exec(expr);
802 if (match == null) return before;
804 while (match != null) {
805 var comp = match[1].startsWith('[') ? match[2].replace(/\\\\]/g, ']') : match[1];
807 if (null == ctx || '' == match[3]) break;
808 expr = expr.substring('[' == match[3] ? match[1].length : match[0].length);
809 match = pattern.exec(expr);
812 return before + String.interpret(ctx);
816 Template.Pattern = /(^|.|\r|\n)(#\{(.*?)\})/;
820 var Enumerable = (function() {
821 function each(iterator, context) {
824 this._each(function(value) {
825 iterator.call(context, value, index++);
828 if (e != $break) throw e;
833 function eachSlice(number, iterator, context) {
834 var index = -number, slices = [], array = this.toArray();
835 if (number < 1) return array;
836 while ((index += number) < array.length)
837 slices.push(array.slice(index, index+number));
838 return slices.collect(iterator, context);
841 function all(iterator, context) {
842 iterator = iterator || Prototype.K;
844 this.each(function(value, index) {
845 result = result && !!iterator.call(context, value, index);
846 if (!result) throw $break;
851 function any(iterator, context) {
852 iterator = iterator || Prototype.K;
854 this.each(function(value, index) {
855 if (result = !!iterator.call(context, value, index))
861 function collect(iterator, context) {
862 iterator = iterator || Prototype.K;
864 this.each(function(value, index) {
865 results.push(iterator.call(context, value, index));
870 function detect(iterator, context) {
872 this.each(function(value, index) {
873 if (iterator.call(context, value, index)) {
881 function findAll(iterator, context) {
883 this.each(function(value, index) {
884 if (iterator.call(context, value, index))
890 function grep(filter, iterator, context) {
891 iterator = iterator || Prototype.K;
894 if (Object.isString(filter))
895 filter = new RegExp(RegExp.escape(filter));
897 this.each(function(value, index) {
898 if (filter.match(value))
899 results.push(iterator.call(context, value, index));
904 function include(object) {
905 if (Object.isFunction(this.indexOf))
906 if (this.indexOf(object) != -1) return true;
909 this.each(function(value) {
910 if (value == object) {
918 function inGroupsOf(number, fillWith) {
919 fillWith = Object.isUndefined(fillWith) ? null : fillWith;
920 return this.eachSlice(number, function(slice) {
921 while(slice.length < number) slice.push(fillWith);
926 function inject(memo, iterator, context) {
927 this.each(function(value, index) {
928 memo = iterator.call(context, memo, value, index);
933 function invoke(method) {
934 var args = $A(arguments).slice(1);
935 return this.map(function(value) {
936 return value[method].apply(value, args);
940 function max(iterator, context) {
941 iterator = iterator || Prototype.K;
943 this.each(function(value, index) {
944 value = iterator.call(context, value, index);
945 if (result == null || value >= result)
951 function min(iterator, context) {
952 iterator = iterator || Prototype.K;
954 this.each(function(value, index) {
955 value = iterator.call(context, value, index);
956 if (result == null || value < result)
962 function partition(iterator, context) {
963 iterator = iterator || Prototype.K;
964 var trues = [], falses = [];
965 this.each(function(value, index) {
966 (iterator.call(context, value, index) ?
967 trues : falses).push(value);
969 return [trues, falses];
972 function pluck(property) {
974 this.each(function(value) {
975 results.push(value[property]);
980 function reject(iterator, context) {
982 this.each(function(value, index) {
983 if (!iterator.call(context, value, index))
989 function sortBy(iterator, context) {
990 return this.map(function(value, index) {
993 criteria: iterator.call(context, value, index)
995 }).sort(function(left, right) {
996 var a = left.criteria, b = right.criteria;
997 return a < b ? -1 : a > b ? 1 : 0;
1001 function toArray() {
1006 var iterator = Prototype.K, args = $A(arguments);
1007 if (Object.isFunction(args.last()))
1008 iterator = args.pop();
1010 var collections = [this].concat(args).map($A);
1011 return this.map(function(value, index) {
1012 return iterator(collections.pluck(index));
1017 return this.toArray().length;
1020 function inspect() {
1021 return '#<Enumerable:' + this.toArray().inspect() + '>';
1034 eachSlice: eachSlice,
1048 inGroupsOf: inGroupsOf,
1053 partition: partition,
1066 function $A(iterable) {
1067 if (!iterable) return [];
1068 if ('toArray' in Object(iterable)) return iterable.toArray();
1069 var length = iterable.length || 0, results = new Array(length);
1070 while (length--) results[length] = iterable[length];
1075 function $w(string) {
1076 if (!Object.isString(string)) return [];
1077 string = string.strip();
1078 return string ? string.split(/\s+/) : [];
1085 var arrayProto = Array.prototype,
1086 slice = arrayProto.slice,
1087 _each = arrayProto.forEach; // use native browser JS 1.6 implementation if available
1089 function each(iterator, context) {
1090 for (var i = 0, length = this.length >>> 0; i < length; i++) {
1091 if (i in this) iterator.call(context, this[i], i, this);
1094 if (!_each) _each = each;
1106 return this[this.length - 1];
1109 function compact() {
1110 return this.select(function(value) {
1111 return value != null;
1115 function flatten() {
1116 return this.inject([], function(array, value) {
1117 if (Object.isArray(value))
1118 return array.concat(value.flatten());
1124 function without() {
1125 var values = slice.call(arguments, 0);
1126 return this.select(function(value) {
1127 return !values.include(value);
1131 function reverse(inline) {
1132 return (inline === false ? this.toArray() : this)._reverse();
1135 function uniq(sorted) {
1136 return this.inject([], function(array, value, index) {
1137 if (0 == index || (sorted ? array.last() != value : !array.include(value)))
1143 function intersect(array) {
1144 return this.uniq().findAll(function(item) {
1145 return array.detect(function(value) { return item === value });
1151 return slice.call(this, 0);
1158 function inspect() {
1159 return '[' + this.map(Object.inspect).join(', ') + ']';
1162 function indexOf(item, i) {
1164 var length = this.length;
1165 if (i < 0) i = length + i;
1166 for (; i < length; i++)
1167 if (this[i] === item) return i;
1171 function lastIndexOf(item, i) {
1172 i = isNaN(i) ? this.length : (i < 0 ? this.length + i : i) + 1;
1173 var n = this.slice(0, i).reverse().indexOf(item);
1174 return (n < 0) ? n : i - n - 1;
1178 var array = slice.call(this, 0), item;
1179 for (var i = 0, length = arguments.length; i < length; i++) {
1180 item = arguments[i];
1181 if (Object.isArray(item) && !('callee' in item)) {
1182 for (var j = 0, arrayLength = item.length; j < arrayLength; j++)
1183 array.push(item[j]);
1191 Object.extend(arrayProto, Enumerable);
1193 if (!arrayProto._reverse)
1194 arrayProto._reverse = arrayProto.reverse;
1196 Object.extend(arrayProto, {
1206 intersect: intersect,
1213 var CONCAT_ARGUMENTS_BUGGY = (function() {
1214 return [].concat(arguments)[0][0] !== 1;
1217 if (CONCAT_ARGUMENTS_BUGGY) arrayProto.concat = concat;
1219 if (!arrayProto.indexOf) arrayProto.indexOf = indexOf;
1220 if (!arrayProto.lastIndexOf) arrayProto.lastIndexOf = lastIndexOf;
1222 function $H(object) {
1223 return new Hash(object);
1226 var Hash = Class.create(Enumerable, (function() {
1227 function initialize(object) {
1228 this._object = Object.isHash(object) ? object.toObject() : Object.clone(object);
1232 function _each(iterator) {
1233 for (var key in this._object) {
1234 var value = this._object[key], pair = [key, value];
1241 function set(key, value) {
1242 return this._object[key] = value;
1246 if (this._object[key] !== Object.prototype[key])
1247 return this._object[key];
1250 function unset(key) {
1251 var value = this._object[key];
1252 delete this._object[key];
1256 function toObject() {
1257 return Object.clone(this._object);
1263 return this.pluck('key');
1267 return this.pluck('value');
1270 function index(value) {
1271 var match = this.detect(function(pair) {
1272 return pair.value === value;
1274 return match && match.key;
1277 function merge(object) {
1278 return this.clone().update(object);
1281 function update(object) {
1282 return new Hash(object).inject(this, function(result, pair) {
1283 result.set(pair.key, pair.value);
1288 function toQueryPair(key, value) {
1289 if (Object.isUndefined(value)) return key;
1290 return key + '=' + encodeURIComponent(String.interpret(value));
1293 function toQueryString() {
1294 return this.inject([], function(results, pair) {
1295 var key = encodeURIComponent(pair.key), values = pair.value;
1297 if (values && typeof values == 'object') {
1298 if (Object.isArray(values)) {
1299 var queryValues = [];
1300 for (var i = 0, len = values.length, value; i < len; i++) {
1302 queryValues.push(toQueryPair(key, value));
1304 return results.concat(queryValues);
1306 } else results.push(toQueryPair(key, values));
1311 function inspect() {
1312 return '#<Hash:{' + this.map(function(pair) {
1313 return pair.map(Object.inspect).join(': ');
1314 }).join(', ') + '}>';
1318 return new Hash(this);
1322 initialize: initialize,
1328 toTemplateReplacements: toObject,
1334 toQueryString: toQueryString,
1342 Object.extend(Number.prototype, (function() {
1343 function toColorPart() {
1344 return this.toPaddedString(2, 16);
1351 function times(iterator, context) {
1352 $R(0, this, true).each(iterator, context);
1356 function toPaddedString(length, radix) {
1357 var string = this.toString(radix || 10);
1358 return '0'.times(length - string.length) + string;
1362 return Math.abs(this);
1366 return Math.round(this);
1370 return Math.ceil(this);
1374 return Math.floor(this);
1378 toColorPart: toColorPart,
1381 toPaddedString: toPaddedString,
1389 function $R(start, end, exclusive) {
1390 return new ObjectRange(start, end, exclusive);
1393 var ObjectRange = Class.create(Enumerable, (function() {
1394 function initialize(start, end, exclusive) {
1397 this.exclusive = exclusive;
1400 function _each(iterator) {
1401 var value = this.start;
1402 while (this.include(value)) {
1404 value = value.succ();
1408 function include(value) {
1409 if (value < this.start)
1412 return value < this.end;
1413 return value <= this.end;
1417 initialize: initialize,
1426 getTransport: function() {
1428 function() {return new XMLHttpRequest()},
1429 function() {return new ActiveXObject('Msxml2.XMLHTTP')},
1430 function() {return new ActiveXObject('Microsoft.XMLHTTP')}
1434 activeRequestCount: 0
1440 _each: function(iterator) {
1441 this.responders._each(iterator);
1444 register: function(responder) {
1445 if (!this.include(responder))
1446 this.responders.push(responder);
1449 unregister: function(responder) {
1450 this.responders = this.responders.without(responder);
1453 dispatch: function(callback, request, transport, json) {
1454 this.each(function(responder) {
1455 if (Object.isFunction(responder[callback])) {
1457 responder[callback].apply(responder, [request, transport, json]);
1464 Object.extend(Ajax.Responders, Enumerable);
1466 Ajax.Responders.register({
1467 onCreate: function() { Ajax.activeRequestCount++ },
1468 onComplete: function() { Ajax.activeRequestCount-- }
1470 Ajax.Base = Class.create({
1471 initialize: function(options) {
1475 contentType: 'application/x-www-form-urlencoded',
1481 Object.extend(this.options, options || { });
1483 this.options.method = this.options.method.toLowerCase();
1485 if (Object.isHash(this.options.parameters))
1486 this.options.parameters = this.options.parameters.toObject();
1489 Ajax.Request = Class.create(Ajax.Base, {
1492 initialize: function($super, url, options) {
1494 this.transport = Ajax.getTransport();
1498 request: function(url) {
1500 this.method = this.options.method;
1501 var params = Object.isString(this.options.parameters) ?
1502 this.options.parameters :
1503 Object.toQueryString(this.options.parameters);
1505 if (!['get', 'post'].include(this.method)) {
1506 params += (params ? '&' : '') + "_method=" + this.method;
1507 this.method = 'post';
1510 if (params && this.method === 'get') {
1511 this.url += (this.url.include('?') ? '&' : '?') + params;
1514 this.parameters = params.toQueryParams();
1517 var response = new Ajax.Response(this);
1518 if (this.options.onCreate) this.options.onCreate(response);
1519 Ajax.Responders.dispatch('onCreate', this, response);
1521 this.transport.open(this.method.toUpperCase(), this.url,
1522 this.options.asynchronous);
1524 if (this.options.asynchronous) this.respondToReadyState.bind(this).defer(1);
1526 this.transport.onreadystatechange = this.onStateChange.bind(this);
1527 this.setRequestHeaders();
1529 this.body = this.method == 'post' ? (this.options.postBody || params) : null;
1530 this.transport.send(this.body);
1532 /* Force Firefox to handle ready state 4 for synchronous requests */
1533 if (!this.options.asynchronous && this.transport.overrideMimeType)
1534 this.onStateChange();
1538 this.dispatchException(e);
1542 onStateChange: function() {
1543 var readyState = this.transport.readyState;
1544 if (readyState > 1 && !((readyState == 4) && this._complete))
1545 this.respondToReadyState(this.transport.readyState);
1548 setRequestHeaders: function() {
1550 'X-Requested-With': 'XMLHttpRequest',
1551 'X-Prototype-Version': Prototype.Version,
1552 'Accept': 'text/javascript, text/html, application/xml, text/xml, */*'
1555 if (this.method == 'post') {
1556 headers['Content-type'] = this.options.contentType +
1557 (this.options.encoding ? '; charset=' + this.options.encoding : '');
1559 /* Force "Connection: close" for older Mozilla browsers to work
1560 * around a bug where XMLHttpRequest sends an incorrect
1561 * Content-length header. See Mozilla Bugzilla #246651.
1563 if (this.transport.overrideMimeType &&
1564 (navigator.userAgent.match(/Gecko\/(\d{4})/) || [0,2005])[1] < 2005)
1565 headers['Connection'] = 'close';
1568 if (typeof this.options.requestHeaders == 'object') {
1569 var extras = this.options.requestHeaders;
1571 if (Object.isFunction(extras.push))
1572 for (var i = 0, length = extras.length; i < length; i += 2)
1573 headers[extras[i]] = extras[i+1];
1575 $H(extras).each(function(pair) { headers[pair.key] = pair.value });
1578 for (var name in headers)
1579 this.transport.setRequestHeader(name, headers[name]);
1582 success: function() {
1583 var status = this.getStatus();
1584 return !status || (status >= 200 && status < 300) || status == 304;
1587 getStatus: function() {
1589 if (this.transport.status === 1223) return 204;
1590 return this.transport.status || 0;
1591 } catch (e) { return 0 }
1594 respondToReadyState: function(readyState) {
1595 var state = Ajax.Request.Events[readyState], response = new Ajax.Response(this);
1597 if (state == 'Complete') {
1599 this._complete = true;
1600 (this.options['on' + response.status]
1601 || this.options['on' + (this.success() ? 'Success' : 'Failure')]
1602 || Prototype.emptyFunction)(response, response.headerJSON);
1604 this.dispatchException(e);
1607 var contentType = response.getHeader('Content-type');
1608 if (this.options.evalJS == 'force'
1609 || (this.options.evalJS && this.isSameOrigin() && contentType
1610 && contentType.match(/^\s*(text|application)\/(x-)?(java|ecma)script(;.*)?\s*$/i)))
1611 this.evalResponse();
1615 (this.options['on' + state] || Prototype.emptyFunction)(response, response.headerJSON);
1616 Ajax.Responders.dispatch('on' + state, this, response, response.headerJSON);
1618 this.dispatchException(e);
1621 if (state == 'Complete') {
1622 this.transport.onreadystatechange = Prototype.emptyFunction;
1626 isSameOrigin: function() {
1627 var m = this.url.match(/^\s*https?:\/\/[^\/]*/);
1628 return !m || (m[0] == '#{protocol}//#{domain}#{port}'.interpolate({
1629 protocol: location.protocol,
1630 domain: document.domain,
1631 port: location.port ? ':' + location.port : ''
1635 getHeader: function(name) {
1637 return this.transport.getResponseHeader(name) || null;
1638 } catch (e) { return null; }
1641 evalResponse: function() {
1643 return eval((this.transport.responseText || '').unfilterJSON());
1645 this.dispatchException(e);
1649 dispatchException: function(exception) {
1650 (this.options.onException || Prototype.emptyFunction)(this, exception);
1651 Ajax.Responders.dispatch('onException', this, exception);
1655 Ajax.Request.Events =
1656 ['Uninitialized', 'Loading', 'Loaded', 'Interactive', 'Complete'];
1665 Ajax.Response = Class.create({
1666 initialize: function(request){
1667 this.request = request;
1668 var transport = this.transport = request.transport,
1669 readyState = this.readyState = transport.readyState;
1671 if ((readyState > 2 && !Prototype.Browser.IE) || readyState == 4) {
1672 this.status = this.getStatus();
1673 this.statusText = this.getStatusText();
1674 this.responseText = String.interpret(transport.responseText);
1675 this.headerJSON = this._getHeaderJSON();
1678 if (readyState == 4) {
1679 var xml = transport.responseXML;
1680 this.responseXML = Object.isUndefined(xml) ? null : xml;
1681 this.responseJSON = this._getResponseJSON();
1689 getStatus: Ajax.Request.prototype.getStatus,
1691 getStatusText: function() {
1693 return this.transport.statusText || '';
1694 } catch (e) { return '' }
1697 getHeader: Ajax.Request.prototype.getHeader,
1699 getAllHeaders: function() {
1701 return this.getAllResponseHeaders();
1702 } catch (e) { return null }
1705 getResponseHeader: function(name) {
1706 return this.transport.getResponseHeader(name);
1709 getAllResponseHeaders: function() {
1710 return this.transport.getAllResponseHeaders();
1713 _getHeaderJSON: function() {
1714 var json = this.getHeader('X-JSON');
1715 if (!json) return null;
1716 json = decodeURIComponent(escape(json));
1718 return json.evalJSON(this.request.options.sanitizeJSON ||
1719 !this.request.isSameOrigin());
1721 this.request.dispatchException(e);
1725 _getResponseJSON: function() {
1726 var options = this.request.options;
1727 if (!options.evalJSON || (options.evalJSON != 'force' &&
1728 !(this.getHeader('Content-type') || '').include('application/json')) ||
1729 this.responseText.blank())
1732 return this.responseText.evalJSON(options.sanitizeJSON ||
1733 !this.request.isSameOrigin());
1735 this.request.dispatchException(e);
1740 Ajax.Updater = Class.create(Ajax.Request, {
1741 initialize: function($super, container, url, options) {
1743 success: (container.success || container),
1744 failure: (container.failure || (container.success ? null : container))
1747 options = Object.clone(options);
1748 var onComplete = options.onComplete;
1749 options.onComplete = (function(response, json) {
1750 this.updateContent(response.responseText);
1751 if (Object.isFunction(onComplete)) onComplete(response, json);
1754 $super(url, options);
1757 updateContent: function(responseText) {
1758 var receiver = this.container[this.success() ? 'success' : 'failure'],
1759 options = this.options;
1761 if (!options.evalScripts) responseText = responseText.stripScripts();
1763 if (receiver = $(receiver)) {
1764 if (options.insertion) {
1765 if (Object.isString(options.insertion)) {
1766 var insertion = { }; insertion[options.insertion] = responseText;
1767 receiver.insert(insertion);
1769 else options.insertion(receiver, responseText);
1771 else receiver.update(responseText);
1776 Ajax.PeriodicalUpdater = Class.create(Ajax.Base, {
1777 initialize: function($super, container, url, options) {
1779 this.onComplete = this.options.onComplete;
1781 this.frequency = (this.options.frequency || 2);
1782 this.decay = (this.options.decay || 1);
1785 this.container = container;
1792 this.options.onComplete = this.updateComplete.bind(this);
1793 this.onTimerEvent();
1797 this.updater.options.onComplete = undefined;
1798 clearTimeout(this.timer);
1799 (this.onComplete || Prototype.emptyFunction).apply(this, arguments);
1802 updateComplete: function(response) {
1803 if (this.options.decay) {
1804 this.decay = (response.responseText == this.lastText ?
1805 this.decay * this.options.decay : 1);
1807 this.lastText = response.responseText;
1809 this.timer = this.onTimerEvent.bind(this).delay(this.decay * this.frequency);
1812 onTimerEvent: function() {
1813 this.updater = new Ajax.Updater(this.container, this.url, this.options);
1818 function $(element) {
1819 if (arguments.length > 1) {
1820 for (var i = 0, elements = [], length = arguments.length; i < length; i++)
1821 elements.push($(arguments[i]));
1824 if (Object.isString(element))
1825 element = document.getElementById(element);
1826 return Element.extend(element);
1829 if (Prototype.BrowserFeatures.XPath) {
1830 document._getElementsByXPath = function(expression, parentElement) {
1832 var query = document.evaluate(expression, $(parentElement) || document,
1833 null, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);
1834 for (var i = 0, length = query.snapshotLength; i < length; i++)
1835 results.push(Element.extend(query.snapshotItem(i)));
1840 /*--------------------------------------------------------------------------*/
1842 if (!Node) var Node = { };
1844 if (!Node.ELEMENT_NODE) {
1845 Object.extend(Node, {
1849 CDATA_SECTION_NODE: 4,
1850 ENTITY_REFERENCE_NODE: 5,
1852 PROCESSING_INSTRUCTION_NODE: 7,
1855 DOCUMENT_TYPE_NODE: 10,
1856 DOCUMENT_FRAGMENT_NODE: 11,
1864 function shouldUseCache(tagName, attributes) {
1865 if (tagName === 'select') return false;
1866 if ('type' in attributes) return false;
1870 var HAS_EXTENDED_CREATE_ELEMENT_SYNTAX = (function(){
1872 var el = document.createElement('<input name="x">');
1873 return el.tagName.toLowerCase() === 'input' && el.name === 'x';
1880 var element = global.Element;
1882 global.Element = function(tagName, attributes) {
1883 attributes = attributes || { };
1884 tagName = tagName.toLowerCase();
1885 var cache = Element.cache;
1887 if (HAS_EXTENDED_CREATE_ELEMENT_SYNTAX && attributes.name) {
1888 tagName = '<' + tagName + ' name="' + attributes.name + '">';
1889 delete attributes.name;
1890 return Element.writeAttribute(document.createElement(tagName), attributes);
1893 if (!cache[tagName]) cache[tagName] = Element.extend(document.createElement(tagName));
1895 var node = shouldUseCache(tagName, attributes) ?
1896 cache[tagName].cloneNode(false) : document.createElement(tagName);
1898 return Element.writeAttribute(node, attributes);
1901 Object.extend(global.Element, element || { });
1902 if (element) global.Element.prototype = element.prototype;
1906 Element.idCounter = 1;
1907 Element.cache = { };
1909 Element._purgeElement = function(element) {
1910 var uid = element._prototypeUID;
1912 Element.stopObserving(element);
1913 element._prototypeUID = void 0;
1914 delete Element.Storage[uid];
1919 visible: function(element) {
1920 return $(element).style.display != 'none';
1923 toggle: function(element) {
1924 element = $(element);
1925 Element[Element.visible(element) ? 'hide' : 'show'](element);
1929 hide: function(element) {
1930 element = $(element);
1931 element.style.display = 'none';
1935 show: function(element) {
1936 element = $(element);
1937 element.style.display = '';
1941 remove: function(element) {
1942 element = $(element);
1943 element.parentNode.removeChild(element);
1947 update: (function(){
1949 var SELECT_ELEMENT_INNERHTML_BUGGY = (function(){
1950 var el = document.createElement("select"),
1952 el.innerHTML = "<option value=\"test\">test</option>";
1953 if (el.options && el.options[0]) {
1954 isBuggy = el.options[0].nodeName.toUpperCase() !== "OPTION";
1960 var TABLE_ELEMENT_INNERHTML_BUGGY = (function(){
1962 var el = document.createElement("table");
1963 if (el && el.tBodies) {
1964 el.innerHTML = "<tbody><tr><td>test</td></tr></tbody>";
1965 var isBuggy = typeof el.tBodies[0] == "undefined";
1974 var LINK_ELEMENT_INNERHTML_BUGGY = (function() {
1976 var el = document.createElement('div');
1977 el.innerHTML = "<link>";
1978 var isBuggy = (el.childNodes.length === 0);
1986 var ANY_INNERHTML_BUGGY = SELECT_ELEMENT_INNERHTML_BUGGY ||
1987 TABLE_ELEMENT_INNERHTML_BUGGY || LINK_ELEMENT_INNERHTML_BUGGY;
1989 var SCRIPT_ELEMENT_REJECTS_TEXTNODE_APPENDING = (function () {
1990 var s = document.createElement("script"),
1993 s.appendChild(document.createTextNode(""));
1994 isBuggy = !s.firstChild ||
1995 s.firstChild && s.firstChild.nodeType !== 3;
2004 function update(element, content) {
2005 element = $(element);
2006 var purgeElement = Element._purgeElement;
2008 var descendants = element.getElementsByTagName('*'),
2009 i = descendants.length;
2010 while (i--) purgeElement(descendants[i]);
2012 if (content && content.toElement)
2013 content = content.toElement();
2015 if (Object.isElement(content))
2016 return element.update().insert(content);
2018 content = Object.toHTML(content);
2020 var tagName = element.tagName.toUpperCase();
2022 if (tagName === 'SCRIPT' && SCRIPT_ELEMENT_REJECTS_TEXTNODE_APPENDING) {
2023 element.text = content;
2027 if (ANY_INNERHTML_BUGGY) {
2028 if (tagName in Element._insertionTranslations.tags) {
2029 while (element.firstChild) {
2030 element.removeChild(element.firstChild);
2032 Element._getContentFromAnonymousElement(tagName, content.stripScripts())
2033 .each(function(node) {
2034 element.appendChild(node)
2036 } else if (LINK_ELEMENT_INNERHTML_BUGGY && Object.isString(content) && content.indexOf('<link') > -1) {
2037 while (element.firstChild) {
2038 element.removeChild(element.firstChild);
2040 var nodes = Element._getContentFromAnonymousElement(tagName, content.stripScripts(), true);
2041 nodes.each(function(node) { element.appendChild(node) });
2044 element.innerHTML = content.stripScripts();
2048 element.innerHTML = content.stripScripts();
2051 content.evalScripts.bind(content).defer();
2058 replace: function(element, content) {
2059 element = $(element);
2060 if (content && content.toElement) content = content.toElement();
2061 else if (!Object.isElement(content)) {
2062 content = Object.toHTML(content);
2063 var range = element.ownerDocument.createRange();
2064 range.selectNode(element);
2065 content.evalScripts.bind(content).defer();
2066 content = range.createContextualFragment(content.stripScripts());
2068 element.parentNode.replaceChild(content, element);
2072 insert: function(element, insertions) {
2073 element = $(element);
2075 if (Object.isString(insertions) || Object.isNumber(insertions) ||
2076 Object.isElement(insertions) || (insertions && (insertions.toElement || insertions.toHTML)))
2077 insertions = {bottom:insertions};
2079 var content, insert, tagName, childNodes;
2081 for (var position in insertions) {
2082 content = insertions[position];
2083 position = position.toLowerCase();
2084 insert = Element._insertionTranslations[position];
2086 if (content && content.toElement) content = content.toElement();
2087 if (Object.isElement(content)) {
2088 insert(element, content);
2092 content = Object.toHTML(content);
2094 tagName = ((position == 'before' || position == 'after')
2095 ? element.parentNode : element).tagName.toUpperCase();
2097 childNodes = Element._getContentFromAnonymousElement(tagName, content.stripScripts());
2099 if (position == 'top' || position == 'after') childNodes.reverse();
2100 childNodes.each(insert.curry(element));
2102 content.evalScripts.bind(content).defer();
2108 wrap: function(element, wrapper, attributes) {
2109 element = $(element);
2110 if (Object.isElement(wrapper))
2111 $(wrapper).writeAttribute(attributes || { });
2112 else if (Object.isString(wrapper)) wrapper = new Element(wrapper, attributes);
2113 else wrapper = new Element('div', wrapper);
2114 if (element.parentNode)
2115 element.parentNode.replaceChild(wrapper, element);
2116 wrapper.appendChild(element);
2120 inspect: function(element) {
2121 element = $(element);
2122 var result = '<' + element.tagName.toLowerCase();
2123 $H({'id': 'id', 'className': 'class'}).each(function(pair) {
2124 var property = pair.first(),
2125 attribute = pair.last(),
2126 value = (element[property] || '').toString();
2127 if (value) result += ' ' + attribute + '=' + value.inspect(true);
2129 return result + '>';
2132 recursivelyCollect: function(element, property, maximumLength) {
2133 element = $(element);
2134 maximumLength = maximumLength || -1;
2137 while (element = element[property]) {
2138 if (element.nodeType == 1)
2139 elements.push(Element.extend(element));
2140 if (elements.length == maximumLength)
2147 ancestors: function(element) {
2148 return Element.recursivelyCollect(element, 'parentNode');
2151 descendants: function(element) {
2152 return Element.select(element, "*");
2155 firstDescendant: function(element) {
2156 element = $(element).firstChild;
2157 while (element && element.nodeType != 1) element = element.nextSibling;
2161 immediateDescendants: function(element) {
2162 var results = [], child = $(element).firstChild;
2164 if (child.nodeType === 1) {
2165 results.push(Element.extend(child));
2167 child = child.nextSibling;
2172 previousSiblings: function(element, maximumLength) {
2173 return Element.recursivelyCollect(element, 'previousSibling');
2176 nextSiblings: function(element) {
2177 return Element.recursivelyCollect(element, 'nextSibling');
2180 siblings: function(element) {
2181 element = $(element);
2182 return Element.previousSiblings(element).reverse()
2183 .concat(Element.nextSiblings(element));
2186 match: function(element, selector) {
2187 element = $(element);
2188 if (Object.isString(selector))
2189 return Prototype.Selector.match(element, selector);
2190 return selector.match(element);
2193 up: function(element, expression, index) {
2194 element = $(element);
2195 if (arguments.length == 1) return $(element.parentNode);
2196 var ancestors = Element.ancestors(element);
2197 return Object.isNumber(expression) ? ancestors[expression] :
2198 Prototype.Selector.find(ancestors, expression, index);
2201 down: function(element, expression, index) {
2202 element = $(element);
2203 if (arguments.length == 1) return Element.firstDescendant(element);
2204 return Object.isNumber(expression) ? Element.descendants(element)[expression] :
2205 Element.select(element, expression)[index || 0];
2208 previous: function(element, expression, index) {
2209 element = $(element);
2210 if (Object.isNumber(expression)) index = expression, expression = false;
2211 if (!Object.isNumber(index)) index = 0;
2214 return Prototype.Selector.find(element.previousSiblings(), expression, index);
2216 return element.recursivelyCollect("previousSibling", index + 1)[index];
2220 next: function(element, expression, index) {
2221 element = $(element);
2222 if (Object.isNumber(expression)) index = expression, expression = false;
2223 if (!Object.isNumber(index)) index = 0;
2226 return Prototype.Selector.find(element.nextSiblings(), expression, index);
2228 var maximumLength = Object.isNumber(index) ? index + 1 : 1;
2229 return element.recursivelyCollect("nextSibling", index + 1)[index];
2234 select: function(element) {
2235 element = $(element);
2236 var expressions = Array.prototype.slice.call(arguments, 1).join(', ');
2237 return Prototype.Selector.select(expressions, element);
2240 adjacent: function(element) {
2241 element = $(element);
2242 var expressions = Array.prototype.slice.call(arguments, 1).join(', ');
2243 return Prototype.Selector.select(expressions, element.parentNode).without(element);
2246 identify: function(element) {
2247 element = $(element);
2248 var id = Element.readAttribute(element, 'id');
2250 do { id = 'anonymous_element_' + Element.idCounter++ } while ($(id));
2251 Element.writeAttribute(element, 'id', id);
2255 readAttribute: function(element, name) {
2256 element = $(element);
2257 if (Prototype.Browser.IE) {
2258 var t = Element._attributeTranslations.read;
2259 if (t.values[name]) return t.values[name](element, name);
2260 if (t.names[name]) name = t.names[name];
2261 if (name.include(':')) {
2262 return (!element.attributes || !element.attributes[name]) ? null :
2263 element.attributes[name].value;
2266 return element.getAttribute(name);
2269 writeAttribute: function(element, name, value) {
2270 element = $(element);
2271 var attributes = { }, t = Element._attributeTranslations.write;
2273 if (typeof name == 'object') attributes = name;
2274 else attributes[name] = Object.isUndefined(value) ? true : value;
2276 for (var attr in attributes) {
2277 name = t.names[attr] || attr;
2278 value = attributes[attr];
2279 if (t.values[attr]) name = t.values[attr](element, value);
2280 if (value === false || value === null)
2281 element.removeAttribute(name);
2282 else if (value === true)
2283 element.setAttribute(name, name);
2284 else element.setAttribute(name, value);
2289 getHeight: function(element) {
2290 return Element.getDimensions(element).height;
2293 getWidth: function(element) {
2294 return Element.getDimensions(element).width;
2297 classNames: function(element) {
2298 return new Element.ClassNames(element);
2301 hasClassName: function(element, className) {
2302 if (!(element = $(element))) return;
2303 var elementClassName = element.className;
2304 return (elementClassName.length > 0 && (elementClassName == className ||
2305 new RegExp("(^|\\s)" + className + "(\\s|$)").test(elementClassName)));
2308 addClassName: function(element, className) {
2309 if (!(element = $(element))) return;
2310 if (!Element.hasClassName(element, className))
2311 element.className += (element.className ? ' ' : '') + className;
2315 removeClassName: function(element, className) {
2316 if (!(element = $(element))) return;
2317 element.className = element.className.replace(
2318 new RegExp("(^|\\s+)" + className + "(\\s+|$)"), ' ').strip();
2322 toggleClassName: function(element, className) {
2323 if (!(element = $(element))) return;
2324 return Element[Element.hasClassName(element, className) ?
2325 'removeClassName' : 'addClassName'](element, className);
2328 cleanWhitespace: function(element) {
2329 element = $(element);
2330 var node = element.firstChild;
2332 var nextNode = node.nextSibling;
2333 if (node.nodeType == 3 && !/\S/.test(node.nodeValue))
2334 element.removeChild(node);
2340 empty: function(element) {
2341 return $(element).innerHTML.blank();
2344 descendantOf: function(element, ancestor) {
2345 element = $(element), ancestor = $(ancestor);
2347 if (element.compareDocumentPosition)
2348 return (element.compareDocumentPosition(ancestor) & 8) === 8;
2350 if (ancestor.contains)
2351 return ancestor.contains(element) && ancestor !== element;
2353 while (element = element.parentNode)
2354 if (element == ancestor) return true;
2359 scrollTo: function(element) {
2360 element = $(element);
2361 var pos = Element.cumulativeOffset(element);
2362 window.scrollTo(pos[0], pos[1]);
2366 getStyle: function(element, style) {
2367 element = $(element);
2368 style = style == 'float' ? 'cssFloat' : style.camelize();
2369 var value = element.style[style];
2370 if (!value || value == 'auto') {
2371 var css = document.defaultView.getComputedStyle(element, null);
2372 value = css ? css[style] : null;
2374 if (style == 'opacity') return value ? parseFloat(value) : 1.0;
2375 return value == 'auto' ? null : value;
2378 getOpacity: function(element) {
2379 return $(element).getStyle('opacity');
2382 setStyle: function(element, styles) {
2383 element = $(element);
2384 var elementStyle = element.style, match;
2385 if (Object.isString(styles)) {
2386 element.style.cssText += ';' + styles;
2387 return styles.include('opacity') ?
2388 element.setOpacity(styles.match(/opacity:\s*(\d?\.?\d*)/)[1]) : element;
2390 for (var property in styles)
2391 if (property == 'opacity') element.setOpacity(styles[property]);
2393 elementStyle[(property == 'float' || property == 'cssFloat') ?
2394 (Object.isUndefined(elementStyle.styleFloat) ? 'cssFloat' : 'styleFloat') :
2395 property] = styles[property];
2400 setOpacity: function(element, value) {
2401 element = $(element);
2402 element.style.opacity = (value == 1 || value === '') ? '' :
2403 (value < 0.00001) ? 0 : value;
2407 makePositioned: function(element) {
2408 element = $(element);
2409 var pos = Element.getStyle(element, 'position');
2410 if (pos == 'static' || !pos) {
2411 element._madePositioned = true;
2412 element.style.position = 'relative';
2413 if (Prototype.Browser.Opera) {
2414 element.style.top = 0;
2415 element.style.left = 0;
2421 undoPositioned: function(element) {
2422 element = $(element);
2423 if (element._madePositioned) {
2424 element._madePositioned = undefined;
2425 element.style.position =
2427 element.style.left =
2428 element.style.bottom =
2429 element.style.right = '';
2434 makeClipping: function(element) {
2435 element = $(element);
2436 if (element._overflow) return element;
2437 element._overflow = Element.getStyle(element, 'overflow') || 'auto';
2438 if (element._overflow !== 'hidden')
2439 element.style.overflow = 'hidden';
2443 undoClipping: function(element) {
2444 element = $(element);
2445 if (!element._overflow) return element;
2446 element.style.overflow = element._overflow == 'auto' ? '' : element._overflow;
2447 element._overflow = null;
2451 clonePosition: function(element, source) {
2452 var options = Object.extend({
2459 }, arguments[2] || { });
2462 var p = Element.viewportOffset(source), delta = [0, 0], parent = null;
2464 element = $(element);
2466 if (Element.getStyle(element, 'position') == 'absolute') {
2467 parent = Element.getOffsetParent(element);
2468 delta = Element.viewportOffset(parent);
2471 if (parent == document.body) {
2472 delta[0] -= document.body.offsetLeft;
2473 delta[1] -= document.body.offsetTop;
2476 if (options.setLeft) element.style.left = (p[0] - delta[0] + options.offsetLeft) + 'px';
2477 if (options.setTop) element.style.top = (p[1] - delta[1] + options.offsetTop) + 'px';
2478 if (options.setWidth) element.style.width = source.offsetWidth + 'px';
2479 if (options.setHeight) element.style.height = source.offsetHeight + 'px';
2484 Object.extend(Element.Methods, {
2485 getElementsBySelector: Element.Methods.select,
2487 childElements: Element.Methods.immediateDescendants
2490 Element._attributeTranslations = {
2500 if (Prototype.Browser.Opera) {
2501 Element.Methods.getStyle = Element.Methods.getStyle.wrap(
2502 function(proceed, element, style) {
2504 case 'height': case 'width':
2505 if (!Element.visible(element)) return null;
2507 var dim = parseInt(proceed(element, style), 10);
2509 if (dim !== element['offset' + style.capitalize()])
2513 if (style === 'height') {
2514 properties = ['border-top-width', 'padding-top',
2515 'padding-bottom', 'border-bottom-width'];
2518 properties = ['border-left-width', 'padding-left',
2519 'padding-right', 'border-right-width'];
2521 return properties.inject(dim, function(memo, property) {
2522 var val = proceed(element, property);
2523 return val === null ? memo : memo - parseInt(val, 10);
2525 default: return proceed(element, style);
2530 Element.Methods.readAttribute = Element.Methods.readAttribute.wrap(
2531 function(proceed, element, attribute) {
2532 if (attribute === 'title') return element.title;
2533 return proceed(element, attribute);
2538 else if (Prototype.Browser.IE) {
2539 Element.Methods.getStyle = function(element, style) {
2540 element = $(element);
2541 style = (style == 'float' || style == 'cssFloat') ? 'styleFloat' : style.camelize();
2542 var value = element.style[style];
2543 if (!value && element.currentStyle) value = element.currentStyle[style];
2545 if (style == 'opacity') {
2546 if (value = (element.getStyle('filter') || '').match(/alpha\(opacity=(.*)\)/))
2547 if (value[1]) return parseFloat(value[1]) / 100;
2551 if (value == 'auto') {
2552 if ((style == 'width' || style == 'height') && (element.getStyle('display') != 'none'))
2553 return element['offset' + style.capitalize()] + 'px';
2559 Element.Methods.setOpacity = function(element, value) {
2560 function stripAlpha(filter){
2561 return filter.replace(/alpha\([^\)]*\)/gi,'');
2563 element = $(element);
2564 var currentStyle = element.currentStyle;
2565 if ((currentStyle && !currentStyle.hasLayout) ||
2566 (!currentStyle && element.style.zoom == 'normal'))
2567 element.style.zoom = 1;
2569 var filter = element.getStyle('filter'), style = element.style;
2570 if (value == 1 || value === '') {
2571 (filter = stripAlpha(filter)) ?
2572 style.filter = filter : style.removeAttribute('filter');
2574 } else if (value < 0.00001) value = 0;
2575 style.filter = stripAlpha(filter) +
2576 'alpha(opacity=' + (value * 100) + ')';
2580 Element._attributeTranslations = (function(){
2582 var classProp = 'className',
2584 el = document.createElement('div');
2586 el.setAttribute(classProp, 'x');
2588 if (el.className !== 'x') {
2589 el.setAttribute('class', 'x');
2590 if (el.className === 'x') {
2591 classProp = 'class';
2596 el = document.createElement('label');
2597 el.setAttribute(forProp, 'x');
2598 if (el.htmlFor !== 'x') {
2599 el.setAttribute('htmlFor', 'x');
2600 if (el.htmlFor === 'x') {
2601 forProp = 'htmlFor';
2610 'className': classProp,
2615 _getAttr: function(element, attribute) {
2616 return element.getAttribute(attribute);
2618 _getAttr2: function(element, attribute) {
2619 return element.getAttribute(attribute, 2);
2621 _getAttrNode: function(element, attribute) {
2622 var node = element.getAttributeNode(attribute);
2623 return node ? node.value : "";
2625 _getEv: (function(){
2627 var el = document.createElement('div'), f;
2628 el.onclick = Prototype.emptyFunction;
2629 var value = el.getAttribute('onclick');
2631 if (String(value).indexOf('{') > -1) {
2632 f = function(element, attribute) {
2633 attribute = element.getAttribute(attribute);
2634 if (!attribute) return null;
2635 attribute = attribute.toString();
2636 attribute = attribute.split('{')[1];
2637 attribute = attribute.split('}')[0];
2638 return attribute.strip();
2641 else if (value === '') {
2642 f = function(element, attribute) {
2643 attribute = element.getAttribute(attribute);
2644 if (!attribute) return null;
2645 return attribute.strip();
2651 _flag: function(element, attribute) {
2652 return $(element).hasAttribute(attribute) ? attribute : null;
2654 style: function(element) {
2655 return element.style.cssText.toLowerCase();
2657 title: function(element) {
2658 return element.title;
2665 Element._attributeTranslations.write = {
2666 names: Object.extend({
2667 cellpadding: 'cellPadding',
2668 cellspacing: 'cellSpacing'
2669 }, Element._attributeTranslations.read.names),
2671 checked: function(element, value) {
2672 element.checked = !!value;
2675 style: function(element, value) {
2676 element.style.cssText = value ? value : '';
2681 Element._attributeTranslations.has = {};
2683 $w('colSpan rowSpan vAlign dateTime accessKey tabIndex ' +
2684 'encType maxLength readOnly longDesc frameBorder').each(function(attr) {
2685 Element._attributeTranslations.write.names[attr.toLowerCase()] = attr;
2686 Element._attributeTranslations.has[attr.toLowerCase()] = attr;
2694 action: v._getAttrNode,
2702 ondblclick: v._getEv,
2703 onmousedown: v._getEv,
2704 onmouseup: v._getEv,
2705 onmouseover: v._getEv,
2706 onmousemove: v._getEv,
2707 onmouseout: v._getEv,
2710 onkeypress: v._getEv,
2711 onkeydown: v._getEv,
2718 })(Element._attributeTranslations.read.values);
2720 if (Prototype.BrowserFeatures.ElementExtensions) {
2722 function _descendants(element) {
2723 var nodes = element.getElementsByTagName('*'), results = [];
2724 for (var i = 0, node; node = nodes[i]; i++)
2725 if (node.tagName !== "!") // Filter out comment nodes.
2730 Element.Methods.down = function(element, expression, index) {
2731 element = $(element);
2732 if (arguments.length == 1) return element.firstDescendant();
2733 return Object.isNumber(expression) ? _descendants(element)[expression] :
2734 Element.select(element, expression)[index || 0];
2741 else if (Prototype.Browser.Gecko && /rv:1\.8\.0/.test(navigator.userAgent)) {
2742 Element.Methods.setOpacity = function(element, value) {
2743 element = $(element);
2744 element.style.opacity = (value == 1) ? 0.999999 :
2745 (value === '') ? '' : (value < 0.00001) ? 0 : value;
2750 else if (Prototype.Browser.WebKit) {
2751 Element.Methods.setOpacity = function(element, value) {
2752 element = $(element);
2753 element.style.opacity = (value == 1 || value === '') ? '' :
2754 (value < 0.00001) ? 0 : value;
2757 if (element.tagName.toUpperCase() == 'IMG' && element.width) {
2758 element.width++; element.width--;
2760 var n = document.createTextNode(' ');
2761 element.appendChild(n);
2762 element.removeChild(n);
2769 if ('outerHTML' in document.documentElement) {
2770 Element.Methods.replace = function(element, content) {
2771 element = $(element);
2773 if (content && content.toElement) content = content.toElement();
2774 if (Object.isElement(content)) {
2775 element.parentNode.replaceChild(content, element);
2779 content = Object.toHTML(content);
2780 var parent = element.parentNode, tagName = parent.tagName.toUpperCase();
2782 if (Element._insertionTranslations.tags[tagName]) {
2783 var nextSibling = element.next(),
2784 fragments = Element._getContentFromAnonymousElement(tagName, content.stripScripts());
2785 parent.removeChild(element);
2787 fragments.each(function(node) { parent.insertBefore(node, nextSibling) });
2789 fragments.each(function(node) { parent.appendChild(node) });
2791 else element.outerHTML = content.stripScripts();
2793 content.evalScripts.bind(content).defer();
2798 Element._returnOffset = function(l, t) {
2799 var result = [l, t];
2805 Element._getContentFromAnonymousElement = function(tagName, html, force) {
2806 var div = new Element('div'),
2807 t = Element._insertionTranslations.tags[tagName];
2809 var workaround = false;
2810 if (t) workaround = true;
2817 div.innerHTML = ' ' + t[0] + html + t[1];
2818 div.removeChild(div.firstChild);
2819 for (var i = t[2]; i--; ) {
2820 div = div.firstChild;
2824 div.innerHTML = html;
2826 return $A(div.childNodes);
2829 Element._insertionTranslations = {
2830 before: function(element, node) {
2831 element.parentNode.insertBefore(node, element);
2833 top: function(element, node) {
2834 element.insertBefore(node, element.firstChild);
2836 bottom: function(element, node) {
2837 element.appendChild(node);
2839 after: function(element, node) {
2840 element.parentNode.insertBefore(node, element.nextSibling);
2843 TABLE: ['<table>', '</table>', 1],
2844 TBODY: ['<table><tbody>', '</tbody></table>', 2],
2845 TR: ['<table><tbody><tr>', '</tr></tbody></table>', 3],
2846 TD: ['<table><tbody><tr><td>', '</td></tr></tbody></table>', 4],
2847 SELECT: ['<select>', '</select>', 1]
2852 var tags = Element._insertionTranslations.tags;
2853 Object.extend(tags, {
2860 Element.Methods.Simulated = {
2861 hasAttribute: function(element, attribute) {
2862 attribute = Element._attributeTranslations.has[attribute] || attribute;
2863 var node = $(element).getAttributeNode(attribute);
2864 return !!(node && node.specified);
2868 Element.Methods.ByTag = { };
2870 Object.extend(Element, Element.Methods);
2874 if (!Prototype.BrowserFeatures.ElementExtensions && div['__proto__']) {
2875 window.HTMLElement = { };
2876 window.HTMLElement.prototype = div['__proto__'];
2877 Prototype.BrowserFeatures.ElementExtensions = true;
2882 })(document.createElement('div'));
2884 Element.extend = (function() {
2886 function checkDeficiency(tagName) {
2887 if (typeof window.Element != 'undefined') {
2888 var proto = window.Element.prototype;
2890 var id = '_' + (Math.random()+'').slice(2),
2891 el = document.createElement(tagName);
2893 var isBuggy = (el[id] !== 'x');
2902 function extendElementWith(element, methods) {
2903 for (var property in methods) {
2904 var value = methods[property];
2905 if (Object.isFunction(value) && !(property in element))
2906 element[property] = value.methodize();
2910 var HTMLOBJECTELEMENT_PROTOTYPE_BUGGY = checkDeficiency('object');
2912 if (Prototype.BrowserFeatures.SpecificElementExtensions) {
2913 if (HTMLOBJECTELEMENT_PROTOTYPE_BUGGY) {
2914 return function(element) {
2915 if (element && typeof element._extendedByPrototype == 'undefined') {
2916 var t = element.tagName;
2917 if (t && (/^(?:object|applet|embed)$/i.test(t))) {
2918 extendElementWith(element, Element.Methods);
2919 extendElementWith(element, Element.Methods.Simulated);
2920 extendElementWith(element, Element.Methods.ByTag[t.toUpperCase()]);
2929 var Methods = { }, ByTag = Element.Methods.ByTag;
2931 var extend = Object.extend(function(element) {
2932 if (!element || typeof element._extendedByPrototype != 'undefined' ||
2933 element.nodeType != 1 || element == window) return element;
2935 var methods = Object.clone(Methods),
2936 tagName = element.tagName.toUpperCase();
2938 if (ByTag[tagName]) Object.extend(methods, ByTag[tagName]);
2940 extendElementWith(element, methods);
2942 element._extendedByPrototype = Prototype.emptyFunction;
2946 refresh: function() {
2947 if (!Prototype.BrowserFeatures.ElementExtensions) {
2948 Object.extend(Methods, Element.Methods);
2949 Object.extend(Methods, Element.Methods.Simulated);
2958 if (document.documentElement.hasAttribute) {
2959 Element.hasAttribute = function(element, attribute) {
2960 return element.hasAttribute(attribute);
2964 Element.hasAttribute = Element.Methods.Simulated.hasAttribute;
2967 Element.addMethods = function(methods) {
2968 var F = Prototype.BrowserFeatures, T = Element.Methods.ByTag;
2971 Object.extend(Form, Form.Methods);
2972 Object.extend(Form.Element, Form.Element.Methods);
2973 Object.extend(Element.Methods.ByTag, {
2974 "FORM": Object.clone(Form.Methods),
2975 "INPUT": Object.clone(Form.Element.Methods),
2976 "SELECT": Object.clone(Form.Element.Methods),
2977 "TEXTAREA": Object.clone(Form.Element.Methods),
2978 "BUTTON": Object.clone(Form.Element.Methods)
2982 if (arguments.length == 2) {
2983 var tagName = methods;
2984 methods = arguments[1];
2987 if (!tagName) Object.extend(Element.Methods, methods || { });
2989 if (Object.isArray(tagName)) tagName.each(extend);
2990 else extend(tagName);
2993 function extend(tagName) {
2994 tagName = tagName.toUpperCase();
2995 if (!Element.Methods.ByTag[tagName])
2996 Element.Methods.ByTag[tagName] = { };
2997 Object.extend(Element.Methods.ByTag[tagName], methods);
3000 function copy(methods, destination, onlyIfAbsent) {
3001 onlyIfAbsent = onlyIfAbsent || false;
3002 for (var property in methods) {
3003 var value = methods[property];
3004 if (!Object.isFunction(value)) continue;
3005 if (!onlyIfAbsent || !(property in destination))
3006 destination[property] = value.methodize();
3010 function findDOMClass(tagName) {
3013 "OPTGROUP": "OptGroup", "TEXTAREA": "TextArea", "P": "Paragraph",
3014 "FIELDSET": "FieldSet", "UL": "UList", "OL": "OList", "DL": "DList",
3015 "DIR": "Directory", "H1": "Heading", "H2": "Heading", "H3": "Heading",
3016 "H4": "Heading", "H5": "Heading", "H6": "Heading", "Q": "Quote",
3017 "INS": "Mod", "DEL": "Mod", "A": "Anchor", "IMG": "Image", "CAPTION":
3018 "TableCaption", "COL": "TableCol", "COLGROUP": "TableCol", "THEAD":
3019 "TableSection", "TFOOT": "TableSection", "TBODY": "TableSection", "TR":
3020 "TableRow", "TH": "TableCell", "TD": "TableCell", "FRAMESET":
3021 "FrameSet", "IFRAME": "IFrame"
3023 if (trans[tagName]) klass = 'HTML' + trans[tagName] + 'Element';
3024 if (window[klass]) return window[klass];
3025 klass = 'HTML' + tagName + 'Element';
3026 if (window[klass]) return window[klass];
3027 klass = 'HTML' + tagName.capitalize() + 'Element';
3028 if (window[klass]) return window[klass];
3030 var element = document.createElement(tagName),
3031 proto = element['__proto__'] || element.constructor.prototype;
3037 var elementPrototype = window.HTMLElement ? HTMLElement.prototype :
3040 if (F.ElementExtensions) {
3041 copy(Element.Methods, elementPrototype);
3042 copy(Element.Methods.Simulated, elementPrototype, true);
3045 if (F.SpecificElementExtensions) {
3046 for (var tag in Element.Methods.ByTag) {
3047 var klass = findDOMClass(tag);
3048 if (Object.isUndefined(klass)) continue;
3049 copy(T[tag], klass.prototype);
3053 Object.extend(Element, Element.Methods);
3054 delete Element.ByTag;
3056 if (Element.extend.refresh) Element.extend.refresh();
3057 Element.cache = { };
3061 document.viewport = {
3063 getDimensions: function() {
3064 return { width: this.getWidth(), height: this.getHeight() };
3067 getScrollOffsets: function() {
3068 return Element._returnOffset(
3069 window.pageXOffset || document.documentElement.scrollLeft || document.body.scrollLeft,
3070 window.pageYOffset || document.documentElement.scrollTop || document.body.scrollTop);
3074 (function(viewport) {
3075 var B = Prototype.Browser, doc = document, element, property = {};
3077 function getRootElement() {
3078 if (B.WebKit && !doc.evaluate)
3081 if (B.Opera && window.parseFloat(window.opera.version()) < 9.5)
3082 return document.body;
3084 return document.documentElement;
3087 function define(D) {
3088 if (!element) element = getRootElement();
3090 property[D] = 'client' + D;
3092 viewport['get' + D] = function() { return element[property[D]] };
3093 return viewport['get' + D]();
3096 viewport.getWidth = define.curry('Width');
3098 viewport.getHeight = define.curry('Height');
3099 })(document.viewport);
3106 Element.addMethods({
3107 getStorage: function(element) {
3108 if (!(element = $(element))) return;
3111 if (element === window) {
3114 if (typeof element._prototypeUID === "undefined")
3115 element._prototypeUID = Element.Storage.UID++;
3116 uid = element._prototypeUID;
3119 if (!Element.Storage[uid])
3120 Element.Storage[uid] = $H();
3122 return Element.Storage[uid];
3125 store: function(element, key, value) {
3126 if (!(element = $(element))) return;
3128 if (arguments.length === 2) {
3129 Element.getStorage(element).update(key);
3131 Element.getStorage(element).set(key, value);
3137 retrieve: function(element, key, defaultValue) {
3138 if (!(element = $(element))) return;
3139 var hash = Element.getStorage(element), value = hash.get(key);
3141 if (Object.isUndefined(value)) {
3142 hash.set(key, defaultValue);
3143 value = defaultValue;
3149 clone: function(element, deep) {
3150 if (!(element = $(element))) return;
3151 var clone = element.cloneNode(deep);
3152 clone._prototypeUID = void 0;
3154 var descendants = Element.select(clone, '*'),
3155 i = descendants.length;
3157 descendants[i]._prototypeUID = void 0;
3160 return Element.extend(clone);
3163 purge: function(element) {
3164 if (!(element = $(element))) return;
3165 var purgeElement = Element._purgeElement;
3167 purgeElement(element);
3169 var descendants = element.getElementsByTagName('*'),
3170 i = descendants.length;
3172 while (i--) purgeElement(descendants[i]);
3180 function toDecimal(pctString) {
3181 var match = pctString.match(/^(\d+)%?$/i);
3182 if (!match) return null;
3183 return (Number(match[1]) / 100);
3186 function getPixelValue(value, property, context) {
3188 if (Object.isElement(value)) {
3190 value = element.getStyle(property);
3193 if (value === null) {
3197 if ((/^(?:-)?\d+(\.\d+)?(px)?$/i).test(value)) {
3198 return window.parseFloat(value);
3201 var isPercentage = value.include('%'), isViewport = (context === document.viewport);
3203 if (/\d/.test(value) && element && element.runtimeStyle && !(isPercentage && isViewport)) {
3204 var style = element.style.left, rStyle = element.runtimeStyle.left;
3205 element.runtimeStyle.left = element.currentStyle.left;
3206 element.style.left = value || 0;
3207 value = element.style.pixelLeft;
3208 element.style.left = style;
3209 element.runtimeStyle.left = rStyle;
3214 if (element && isPercentage) {
3215 context = context || element.parentNode;
3216 var decimal = toDecimal(value);
3218 var position = element.getStyle('position');
3220 var isHorizontal = property.include('left') || property.include('right') ||
3221 property.include('width');
3223 var isVertical = property.include('top') || property.include('bottom') ||
3224 property.include('height');
3226 if (context === document.viewport) {
3228 whole = document.viewport.getWidth();
3229 } else if (isVertical) {
3230 whole = document.viewport.getHeight();
3234 whole = $(context).measure('width');
3235 } else if (isVertical) {
3236 whole = $(context).measure('height');
3240 return (whole === null) ? 0 : whole * decimal;
3246 function toCSSPixels(number) {
3247 if (Object.isString(number) && number.endsWith('px')) {
3250 return number + 'px';
3253 function isDisplayed(element) {
3254 var originalElement = element;
3255 while (element && element.parentNode) {
3256 var display = element.getStyle('display');
3257 if (display === 'none') {
3260 element = $(element.parentNode);
3265 var hasLayout = Prototype.K;
3266 if ('currentStyle' in document.documentElement) {
3267 hasLayout = function(element) {
3268 if (!element.currentStyle.hasLayout) {
3269 element.style.zoom = 1;
3275 function cssNameFor(key) {
3276 if (key.include('border')) key = key + '-width';
3277 return key.camelize();
3280 Element.Layout = Class.create(Hash, {
3281 initialize: function($super, element, preCompute) {
3283 this.element = $(element);
3285 Element.Layout.PROPERTIES.each( function(property) {
3286 this._set(property, null);
3290 this._preComputing = true;
3292 Element.Layout.PROPERTIES.each( this._compute, this );
3294 this._preComputing = false;
3298 _set: function(property, value) {
3299 return Hash.prototype.set.call(this, property, value);
3302 set: function(property, value) {
3303 throw "Properties of Element.Layout are read-only.";
3306 get: function($super, property) {
3307 var value = $super(property);
3308 return value === null ? this._compute(property) : value;
3311 _begin: function() {
3312 if (this._prepared) return;
3314 var element = this.element;
3315 if (isDisplayed(element)) {
3316 this._prepared = true;
3320 var originalStyles = {
3321 position: element.style.position || '',
3322 width: element.style.width || '',
3323 visibility: element.style.visibility || '',
3324 display: element.style.display || ''
3327 element.store('prototype_original_styles', originalStyles);
3329 var position = element.getStyle('position'),
3330 width = element.getStyle('width');
3332 if (width === "0px" || width === null) {
3333 element.style.display = 'block';
3334 width = element.getStyle('width');
3337 var context = (position === 'fixed') ? document.viewport :
3341 position: 'absolute',
3342 visibility: 'hidden',
3346 var positionedWidth = element.getStyle('width');
3349 if (width && (positionedWidth === width)) {
3350 newWidth = getPixelValue(element, 'width', context);
3351 } else if (position === 'absolute' || position === 'fixed') {
3352 newWidth = getPixelValue(element, 'width', context);
3354 var parent = element.parentNode, pLayout = $(parent).getLayout();
3356 newWidth = pLayout.get('width') -
3357 this.get('margin-left') -
3358 this.get('border-left') -
3359 this.get('padding-left') -
3360 this.get('padding-right') -
3361 this.get('border-right') -
3362 this.get('margin-right');
3365 element.setStyle({ width: newWidth + 'px' });
3367 this._prepared = true;
3371 var element = this.element;
3372 var originalStyles = element.retrieve('prototype_original_styles');
3373 element.store('prototype_original_styles', null);
3374 element.setStyle(originalStyles);
3375 this._prepared = false;
3378 _compute: function(property) {
3379 var COMPUTATIONS = Element.Layout.COMPUTATIONS;
3380 if (!(property in COMPUTATIONS)) {
3381 throw "Property not found.";
3384 return this._set(property, COMPUTATIONS[property].call(this, this.element));
3387 toObject: function() {
3388 var args = $A(arguments);
3389 var keys = (args.length === 0) ? Element.Layout.PROPERTIES :
3390 args.join(' ').split(' ');
3392 keys.each( function(key) {
3393 if (!Element.Layout.PROPERTIES.include(key)) return;
3394 var value = this.get(key);
3395 if (value != null) obj[key] = value;
3400 toHash: function() {
3401 var obj = this.toObject.apply(this, arguments);
3402 return new Hash(obj);
3406 var args = $A(arguments);
3407 var keys = (args.length === 0) ? Element.Layout.PROPERTIES :
3408 args.join(' ').split(' ');
3411 keys.each( function(key) {
3412 if (!Element.Layout.PROPERTIES.include(key)) return;
3413 if (Element.Layout.COMPOSITE_PROPERTIES.include(key)) return;
3415 var value = this.get(key);
3416 if (value != null) css[cssNameFor(key)] = value + 'px';
3421 inspect: function() {
3422 return "#<Element.Layout>";
3426 Object.extend(Element.Layout, {
3427 PROPERTIES: $w('height width top left right bottom border-left border-right border-top border-bottom padding-left padding-right padding-top padding-bottom margin-top margin-bottom margin-left margin-right padding-box-width padding-box-height border-box-width border-box-height margin-box-width margin-box-height'),
3429 COMPOSITE_PROPERTIES: $w('padding-box-width padding-box-height margin-box-width margin-box-height border-box-width border-box-height'),
3432 'height': function(element) {
3433 if (!this._preComputing) this._begin();
3435 var bHeight = this.get('border-box-height');
3437 if (!this._preComputing) this._end();
3441 var bTop = this.get('border-top'),
3442 bBottom = this.get('border-bottom');
3444 var pTop = this.get('padding-top'),
3445 pBottom = this.get('padding-bottom');
3447 if (!this._preComputing) this._end();
3449 return bHeight - bTop - bBottom - pTop - pBottom;
3452 'width': function(element) {
3453 if (!this._preComputing) this._begin();
3455 var bWidth = this.get('border-box-width');
3457 if (!this._preComputing) this._end();
3461 var bLeft = this.get('border-left'),
3462 bRight = this.get('border-right');
3464 var pLeft = this.get('padding-left'),
3465 pRight = this.get('padding-right');
3467 if (!this._preComputing) this._end();
3469 return bWidth - bLeft - bRight - pLeft - pRight;
3472 'padding-box-height': function(element) {
3473 var height = this.get('height'),
3474 pTop = this.get('padding-top'),
3475 pBottom = this.get('padding-bottom');
3477 return height + pTop + pBottom;
3480 'padding-box-width': function(element) {
3481 var width = this.get('width'),
3482 pLeft = this.get('padding-left'),
3483 pRight = this.get('padding-right');
3485 return width + pLeft + pRight;
3488 'border-box-height': function(element) {
3489 if (!this._preComputing) this._begin();
3490 var height = element.offsetHeight;
3491 if (!this._preComputing) this._end();
3495 'border-box-width': function(element) {
3496 if (!this._preComputing) this._begin();
3497 var width = element.offsetWidth;
3498 if (!this._preComputing) this._end();
3502 'margin-box-height': function(element) {
3503 var bHeight = this.get('border-box-height'),
3504 mTop = this.get('margin-top'),
3505 mBottom = this.get('margin-bottom');
3507 if (bHeight <= 0) return 0;
3509 return bHeight + mTop + mBottom;
3512 'margin-box-width': function(element) {
3513 var bWidth = this.get('border-box-width'),
3514 mLeft = this.get('margin-left'),
3515 mRight = this.get('margin-right');
3517 if (bWidth <= 0) return 0;
3519 return bWidth + mLeft + mRight;
3522 'top': function(element) {
3523 var offset = element.positionedOffset();
3527 'bottom': function(element) {
3528 var offset = element.positionedOffset(),
3529 parent = element.getOffsetParent(),
3530 pHeight = parent.measure('height');
3532 var mHeight = this.get('border-box-height');
3534 return pHeight - mHeight - offset.top;
3537 'left': function(element) {
3538 var offset = element.positionedOffset();
3542 'right': function(element) {
3543 var offset = element.positionedOffset(),
3544 parent = element.getOffsetParent(),
3545 pWidth = parent.measure('width');
3547 var mWidth = this.get('border-box-width');
3549 return pWidth - mWidth - offset.left;
3552 'padding-top': function(element) {
3553 return getPixelValue(element, 'paddingTop');
3556 'padding-bottom': function(element) {
3557 return getPixelValue(element, 'paddingBottom');
3560 'padding-left': function(element) {
3561 return getPixelValue(element, 'paddingLeft');
3564 'padding-right': function(element) {
3565 return getPixelValue(element, 'paddingRight');
3568 'border-top': function(element) {
3569 return getPixelValue(element, 'borderTopWidth');
3572 'border-bottom': function(element) {
3573 return getPixelValue(element, 'borderBottomWidth');
3576 'border-left': function(element) {
3577 return getPixelValue(element, 'borderLeftWidth');
3580 'border-right': function(element) {
3581 return getPixelValue(element, 'borderRightWidth');
3584 'margin-top': function(element) {
3585 return getPixelValue(element, 'marginTop');
3588 'margin-bottom': function(element) {
3589 return getPixelValue(element, 'marginBottom');
3592 'margin-left': function(element) {
3593 return getPixelValue(element, 'marginLeft');
3596 'margin-right': function(element) {
3597 return getPixelValue(element, 'marginRight');
3602 if ('getBoundingClientRect' in document.documentElement) {
3603 Object.extend(Element.Layout.COMPUTATIONS, {
3604 'right': function(element) {
3605 var parent = hasLayout(element.getOffsetParent());
3606 var rect = element.getBoundingClientRect(),
3607 pRect = parent.getBoundingClientRect();
3609 return (pRect.right - rect.right).round();
3612 'bottom': function(element) {
3613 var parent = hasLayout(element.getOffsetParent());
3614 var rect = element.getBoundingClientRect(),
3615 pRect = parent.getBoundingClientRect();
3617 return (pRect.bottom - rect.bottom).round();
3622 Element.Offset = Class.create({
3623 initialize: function(left, top) {
3624 this.left = left.round();
3625 this.top = top.round();
3627 this[0] = this.left;
3631 relativeTo: function(offset) {
3632 return new Element.Offset(
3633 this.left - offset.left,
3634 this.top - offset.top
3638 inspect: function() {
3639 return "#<Element.Offset left: #{left} top: #{top}>".interpolate(this);
3642 toString: function() {
3643 return "[#{left}, #{top}]".interpolate(this);
3646 toArray: function() {
3647 return [this.left, this.top];
3651 function getLayout(element, preCompute) {
3652 return new Element.Layout(element, preCompute);
3655 function measure(element, property) {
3656 return $(element).getLayout().get(property);
3659 function getDimensions(element) {
3660 element = $(element);
3661 var display = Element.getStyle(element, 'display');
3663 if (display && display !== 'none') {
3664 return { width: element.offsetWidth, height: element.offsetHeight };
3667 var style = element.style;
3668 var originalStyles = {
3669 visibility: style.visibility,
3670 position: style.position,
3671 display: style.display
3675 visibility: 'hidden',
3679 if (originalStyles.position !== 'fixed')
3680 newStyles.position = 'absolute';
3682 Element.setStyle(element, newStyles);
3685 width: element.offsetWidth,
3686 height: element.offsetHeight
3689 Element.setStyle(element, originalStyles);
3694 function getOffsetParent(element) {
3695 element = $(element);
3697 if (isDocument(element) || isDetached(element) || isBody(element) || isHtml(element))
3698 return $(document.body);
3700 var isInline = (Element.getStyle(element, 'display') === 'inline');
3701 if (!isInline && element.offsetParent) return $(element.offsetParent);
3703 while ((element = element.parentNode) && element !== document.body) {
3704 if (Element.getStyle(element, 'position') !== 'static') {
3705 return isHtml(element) ? $(document.body) : $(element);
3709 return $(document.body);
3713 function cumulativeOffset(element) {
3714 element = $(element);
3715 var valueT = 0, valueL = 0;
3716 if (element.parentNode) {
3718 valueT += element.offsetTop || 0;
3719 valueL += element.offsetLeft || 0;
3720 element = element.offsetParent;
3723 return new Element.Offset(valueL, valueT);
3726 function positionedOffset(element) {
3727 element = $(element);
3729 var layout = element.getLayout();
3731 var valueT = 0, valueL = 0;
3733 valueT += element.offsetTop || 0;
3734 valueL += element.offsetLeft || 0;
3735 element = element.offsetParent;
3737 if (isBody(element)) break;
3738 var p = Element.getStyle(element, 'position');
3739 if (p !== 'static') break;
3743 valueL -= layout.get('margin-top');
3744 valueT -= layout.get('margin-left');
3746 return new Element.Offset(valueL, valueT);
3749 function cumulativeScrollOffset(element) {
3750 var valueT = 0, valueL = 0;
3752 valueT += element.scrollTop || 0;
3753 valueL += element.scrollLeft || 0;
3754 element = element.parentNode;
3756 return new Element.Offset(valueL, valueT);
3759 function viewportOffset(forElement) {
3760 element = $(element);
3761 var valueT = 0, valueL = 0, docBody = document.body;
3763 var element = forElement;
3765 valueT += element.offsetTop || 0;
3766 valueL += element.offsetLeft || 0;
3767 if (element.offsetParent == docBody &&
3768 Element.getStyle(element, 'position') == 'absolute') break;
3769 } while (element = element.offsetParent);
3771 element = forElement;
3773 if (element != docBody) {
3774 valueT -= element.scrollTop || 0;
3775 valueL -= element.scrollLeft || 0;
3777 } while (element = element.parentNode);
3778 return new Element.Offset(valueL, valueT);
3781 function absolutize(element) {
3782 element = $(element);
3784 if (Element.getStyle(element, 'position') === 'absolute') {
3788 var offsetParent = getOffsetParent(element);
3789 var eOffset = element.viewportOffset(),
3790 pOffset = offsetParent.viewportOffset();
3792 var offset = eOffset.relativeTo(pOffset);
3793 var layout = element.getLayout();
3795 element.store('prototype_absolutize_original_styles', {
3796 left: element.getStyle('left'),
3797 top: element.getStyle('top'),
3798 width: element.getStyle('width'),
3799 height: element.getStyle('height')
3803 position: 'absolute',
3804 top: offset.top + 'px',
3805 left: offset.left + 'px',
3806 width: layout.get('width') + 'px',
3807 height: layout.get('height') + 'px'
3813 function relativize(element) {
3814 element = $(element);
3815 if (Element.getStyle(element, 'position') === 'relative') {
3819 var originalStyles =
3820 element.retrieve('prototype_absolutize_original_styles');
3822 if (originalStyles) element.setStyle(originalStyles);
3826 if (Prototype.Browser.IE) {
3827 getOffsetParent = getOffsetParent.wrap(
3828 function(proceed, element) {
3829 element = $(element);
3831 if (isDocument(element) || isDetached(element) || isBody(element) || isHtml(element))
3832 return $(document.body);
3834 var position = element.getStyle('position');
3835 if (position !== 'static') return proceed(element);
3837 element.setStyle({ position: 'relative' });
3838 var value = proceed(element);
3839 element.setStyle({ position: position });
3844 positionedOffset = positionedOffset.wrap(function(proceed, element) {
3845 element = $(element);
3846 if (!element.parentNode) return new Element.Offset(0, 0);
3847 var position = element.getStyle('position');
3848 if (position !== 'static') return proceed(element);
3850 var offsetParent = element.getOffsetParent();
3851 if (offsetParent && offsetParent.getStyle('position') === 'fixed')
3852 hasLayout(offsetParent);
3854 element.setStyle({ position: 'relative' });
3855 var value = proceed(element);
3856 element.setStyle({ position: position });
3859 } else if (Prototype.Browser.Webkit) {
3860 cumulativeOffset = function(element) {
3861 element = $(element);
3862 var valueT = 0, valueL = 0;
3864 valueT += element.offsetTop || 0;
3865 valueL += element.offsetLeft || 0;
3866 if (element.offsetParent == document.body)
3867 if (Element.getStyle(element, 'position') == 'absolute') break;
3869 element = element.offsetParent;
3872 return new Element.Offset(valueL, valueT);
3877 Element.addMethods({
3878 getLayout: getLayout,
3880 getDimensions: getDimensions,
3881 getOffsetParent: getOffsetParent,
3882 cumulativeOffset: cumulativeOffset,
3883 positionedOffset: positionedOffset,
3884 cumulativeScrollOffset: cumulativeScrollOffset,
3885 viewportOffset: viewportOffset,
3886 absolutize: absolutize,
3887 relativize: relativize
3890 function isBody(element) {
3891 return element.nodeName.toUpperCase() === 'BODY';
3894 function isHtml(element) {
3895 return element.nodeName.toUpperCase() === 'HTML';
3898 function isDocument(element) {
3899 return element.nodeType === Node.DOCUMENT_NODE;
3902 function isDetached(element) {
3903 return element !== document.body &&
3904 !Element.descendantOf(element, document.body);
3907 if ('getBoundingClientRect' in document.documentElement) {
3908 Element.addMethods({
3909 viewportOffset: function(element) {
3910 element = $(element);
3911 if (isDetached(element)) return new Element.Offset(0, 0);
3913 var rect = element.getBoundingClientRect(),
3914 docEl = document.documentElement;
3915 return new Element.Offset(rect.left - docEl.clientLeft,
3916 rect.top - docEl.clientTop);
3921 window.$$ = function() {
3922 var expression = $A(arguments).join(', ');
3923 return Prototype.Selector.select(expression, document);
3926 Prototype.Selector = (function() {
3929 throw new Error('Method "Prototype.Selector.select" must be defined.');
3933 throw new Error('Method "Prototype.Selector.match" must be defined.');
3936 function find(elements, expression, index) {
3938 var match = Prototype.Selector.match, length = elements.length, matchIndex = 0, i;
3940 for (i = 0; i < length; i++) {
3941 if (match(elements[i], expression) && index == matchIndex++) {
3942 return Element.extend(elements[i]);
3947 function extendElements(elements) {
3948 for (var i = 0, length = elements.length; i < length; i++) {
3949 Element.extend(elements[i]);
3955 var K = Prototype.K;
3961 extendElements: (Element.extend === K) ? K : extendElements,
3962 extendElement: Element.extend
3965 Prototype._original_property = window.Sizzle;
3967 * Sizzle CSS Selector Engine - v1.0
3968 * Copyright 2009, The Dojo Foundation
3969 * Released under the MIT, BSD, and GPL Licenses.
3970 * More information: http://sizzlejs.com/
3974 var chunker = /((?:\((?:\([^()]+\)|[^()]+)+\)|\[(?:\[[^[\]]*\]|['"][^'"]*['"]|[^[\]'"]+)+\]|\\.|[^ >+~,(\[\\]+)+|[>+~])(\s*,\s*)?((?:.|\r|\n)*)/g,
3976 toString = Object.prototype.toString,
3977 hasDuplicate = false,
3978 baseHasDuplicate = true;
3980 [0, 0].sort(function(){
3981 baseHasDuplicate = false;
3985 var Sizzle = function(selector, context, results, seed) {
3986 results = results || [];
3987 var origContext = context = context || document;
3989 if ( context.nodeType !== 1 && context.nodeType !== 9 ) {
3993 if ( !selector || typeof selector !== "string" ) {
3997 var parts = [], m, set, checkSet, check, mode, extra, prune = true, contextXML = isXML(context),
4000 while ( (chunker.exec(""), m = chunker.exec(soFar)) !== null ) {
4011 if ( parts.length > 1 && origPOS.exec( selector ) ) {
4012 if ( parts.length === 2 && Expr.relative[ parts[0] ] ) {
4013 set = posProcess( parts[0] + parts[1], context );
4015 set = Expr.relative[ parts[0] ] ?
4017 Sizzle( parts.shift(), context );
4019 while ( parts.length ) {
4020 selector = parts.shift();
4022 if ( Expr.relative[ selector ] )
4023 selector += parts.shift();
4025 set = posProcess( selector, set );
4029 if ( !seed && parts.length > 1 && context.nodeType === 9 && !contextXML &&
4030 Expr.match.ID.test(parts[0]) && !Expr.match.ID.test(parts[parts.length - 1]) ) {
4031 var ret = Sizzle.find( parts.shift(), context, contextXML );
4032 context = ret.expr ? Sizzle.filter( ret.expr, ret.set )[0] : ret.set[0];
4037 { expr: parts.pop(), set: makeArray(seed) } :
4038 Sizzle.find( parts.pop(), parts.length === 1 && (parts[0] === "~" || parts[0] === "+") && context.parentNode ? context.parentNode : context, contextXML );
4039 set = ret.expr ? Sizzle.filter( ret.expr, ret.set ) : ret.set;
4041 if ( parts.length > 0 ) {
4042 checkSet = makeArray(set);
4047 while ( parts.length ) {
4048 var cur = parts.pop(), pop = cur;
4050 if ( !Expr.relative[ cur ] ) {
4056 if ( pop == null ) {
4060 Expr.relative[ cur ]( checkSet, pop, contextXML );
4063 checkSet = parts = [];
4072 throw "Syntax error, unrecognized expression: " + (cur || selector);
4075 if ( toString.call(checkSet) === "[object Array]" ) {
4077 results.push.apply( results, checkSet );
4078 } else if ( context && context.nodeType === 1 ) {
4079 for ( var i = 0; checkSet[i] != null; i++ ) {
4080 if ( checkSet[i] && (checkSet[i] === true || checkSet[i].nodeType === 1 && contains(context, checkSet[i])) ) {
4081 results.push( set[i] );
4085 for ( var i = 0; checkSet[i] != null; i++ ) {
4086 if ( checkSet[i] && checkSet[i].nodeType === 1 ) {
4087 results.push( set[i] );
4092 makeArray( checkSet, results );
4096 Sizzle( extra, origContext, results, seed );
4097 Sizzle.uniqueSort( results );
4103 Sizzle.uniqueSort = function(results){
4105 hasDuplicate = baseHasDuplicate;
4106 results.sort(sortOrder);
4108 if ( hasDuplicate ) {
4109 for ( var i = 1; i < results.length; i++ ) {
4110 if ( results[i] === results[i-1] ) {
4111 results.splice(i--, 1);
4120 Sizzle.matches = function(expr, set){
4121 return Sizzle(expr, null, null, set);
4124 Sizzle.find = function(expr, context, isXML){
4131 for ( var i = 0, l = Expr.order.length; i < l; i++ ) {
4132 var type = Expr.order[i], match;
4134 if ( (match = Expr.leftMatch[ type ].exec( expr )) ) {
4135 var left = match[1];
4138 if ( left.substr( left.length - 1 ) !== "\\" ) {
4139 match[1] = (match[1] || "").replace(/\\/g, "");
4140 set = Expr.find[ type ]( match, context, isXML );
4141 if ( set != null ) {
4142 expr = expr.replace( Expr.match[ type ], "" );
4150 set = context.getElementsByTagName("*");
4153 return {set: set, expr: expr};
4156 Sizzle.filter = function(expr, set, inplace, not){
4157 var old = expr, result = [], curLoop = set, match, anyFound,
4158 isXMLFilter = set && set[0] && isXML(set[0]);
4160 while ( expr && set.length ) {
4161 for ( var type in Expr.filter ) {
4162 if ( (match = Expr.match[ type ].exec( expr )) != null ) {
4163 var filter = Expr.filter[ type ], found, item;
4166 if ( curLoop == result ) {
4170 if ( Expr.preFilter[ type ] ) {
4171 match = Expr.preFilter[ type ]( match, curLoop, inplace, result, not, isXMLFilter );
4174 anyFound = found = true;
4175 } else if ( match === true ) {
4181 for ( var i = 0; (item = curLoop[i]) != null; i++ ) {
4183 found = filter( item, match, i, curLoop );
4184 var pass = not ^ !!found;
4186 if ( inplace && found != null ) {
4192 } else if ( pass ) {
4193 result.push( item );
4200 if ( found !== undefined ) {
4205 expr = expr.replace( Expr.match[ type ], "" );
4216 if ( expr == old ) {
4217 if ( anyFound == null ) {
4218 throw "Syntax error, unrecognized expression: " + expr;
4230 var Expr = Sizzle.selectors = {
4231 order: [ "ID", "NAME", "TAG" ],
4233 ID: /#((?:[\w\u00c0-\uFFFF-]|\\.)+)/,
4234 CLASS: /\.((?:[\w\u00c0-\uFFFF-]|\\.)+)/,
4235 NAME: /\[name=['"]*((?:[\w\u00c0-\uFFFF-]|\\.)+)['"]*\]/,
4236 ATTR: /\[\s*((?:[\w\u00c0-\uFFFF-]|\\.)+)\s*(?:(\S?=)\s*(['"]*)(.*?)\3|)\s*\]/,
4237 TAG: /^((?:[\w\u00c0-\uFFFF\*-]|\\.)+)/,
4238 CHILD: /:(only|nth|last|first)-child(?:\((even|odd|[\dn+-]*)\))?/,
4239 POS: /:(nth|eq|gt|lt|first|last|even|odd)(?:\((\d*)\))?(?=[^-]|$)/,
4240 PSEUDO: /:((?:[\w\u00c0-\uFFFF-]|\\.)+)(?:\((['"]*)((?:\([^\)]+\)|[^\2\(\)]*)+)\2\))?/
4244 "class": "className",
4248 href: function(elem){
4249 return elem.getAttribute("href");
4253 "+": function(checkSet, part, isXML){
4254 var isPartStr = typeof part === "string",
4255 isTag = isPartStr && !/\W/.test(part),
4256 isPartStrNotTag = isPartStr && !isTag;
4258 if ( isTag && !isXML ) {
4259 part = part.toUpperCase();
4262 for ( var i = 0, l = checkSet.length, elem; i < l; i++ ) {
4263 if ( (elem = checkSet[i]) ) {
4264 while ( (elem = elem.previousSibling) && elem.nodeType !== 1 ) {}
4266 checkSet[i] = isPartStrNotTag || elem && elem.nodeName === part ?
4272 if ( isPartStrNotTag ) {
4273 Sizzle.filter( part, checkSet, true );
4276 ">": function(checkSet, part, isXML){
4277 var isPartStr = typeof part === "string";
4279 if ( isPartStr && !/\W/.test(part) ) {
4280 part = isXML ? part : part.toUpperCase();
4282 for ( var i = 0, l = checkSet.length; i < l; i++ ) {
4283 var elem = checkSet[i];
4285 var parent = elem.parentNode;
4286 checkSet[i] = parent.nodeName === part ? parent : false;
4290 for ( var i = 0, l = checkSet.length; i < l; i++ ) {
4291 var elem = checkSet[i];
4293 checkSet[i] = isPartStr ?
4295 elem.parentNode === part;
4300 Sizzle.filter( part, checkSet, true );
4304 "": function(checkSet, part, isXML){
4305 var doneName = done++, checkFn = dirCheck;
4307 if ( !/\W/.test(part) ) {
4308 var nodeCheck = part = isXML ? part : part.toUpperCase();
4309 checkFn = dirNodeCheck;
4312 checkFn("parentNode", part, doneName, checkSet, nodeCheck, isXML);
4314 "~": function(checkSet, part, isXML){
4315 var doneName = done++, checkFn = dirCheck;
4317 if ( typeof part === "string" && !/\W/.test(part) ) {
4318 var nodeCheck = part = isXML ? part : part.toUpperCase();
4319 checkFn = dirNodeCheck;
4322 checkFn("previousSibling", part, doneName, checkSet, nodeCheck, isXML);
4326 ID: function(match, context, isXML){
4327 if ( typeof context.getElementById !== "undefined" && !isXML ) {
4328 var m = context.getElementById(match[1]);
4329 return m ? [m] : [];
4332 NAME: function(match, context, isXML){
4333 if ( typeof context.getElementsByName !== "undefined" ) {
4334 var ret = [], results = context.getElementsByName(match[1]);
4336 for ( var i = 0, l = results.length; i < l; i++ ) {
4337 if ( results[i].getAttribute("name") === match[1] ) {
4338 ret.push( results[i] );
4342 return ret.length === 0 ? null : ret;
4345 TAG: function(match, context){
4346 return context.getElementsByTagName(match[1]);
4350 CLASS: function(match, curLoop, inplace, result, not, isXML){
4351 match = " " + match[1].replace(/\\/g, "") + " ";
4357 for ( var i = 0, elem; (elem = curLoop[i]) != null; i++ ) {
4359 if ( not ^ (elem.className && (" " + elem.className + " ").indexOf(match) >= 0) ) {
4361 result.push( elem );
4362 } else if ( inplace ) {
4370 ID: function(match){
4371 return match[1].replace(/\\/g, "");
4373 TAG: function(match, curLoop){
4374 for ( var i = 0; curLoop[i] === false; i++ ){}
4375 return curLoop[i] && isXML(curLoop[i]) ? match[1] : match[1].toUpperCase();
4377 CHILD: function(match){
4378 if ( match[1] == "nth" ) {
4379 var test = /(-?)(\d*)n((?:\+|-)?\d*)/.exec(
4380 match[2] == "even" && "2n" || match[2] == "odd" && "2n+1" ||
4381 !/\D/.test( match[2] ) && "0n+" + match[2] || match[2]);
4383 match[2] = (test[1] + (test[2] || 1)) - 0;
4384 match[3] = test[3] - 0;
4391 ATTR: function(match, curLoop, inplace, result, not, isXML){
4392 var name = match[1].replace(/\\/g, "");
4394 if ( !isXML && Expr.attrMap[name] ) {
4395 match[1] = Expr.attrMap[name];
4398 if ( match[2] === "~=" ) {
4399 match[4] = " " + match[4] + " ";
4404 PSEUDO: function(match, curLoop, inplace, result, not){
4405 if ( match[1] === "not" ) {
4406 if ( ( chunker.exec(match[3]) || "" ).length > 1 || /^\w/.test(match[3]) ) {
4407 match[3] = Sizzle(match[3], null, null, curLoop);
4409 var ret = Sizzle.filter(match[3], curLoop, inplace, true ^ not);
4411 result.push.apply( result, ret );
4415 } else if ( Expr.match.POS.test( match[0] ) || Expr.match.CHILD.test( match[0] ) ) {
4421 POS: function(match){
4422 match.unshift( true );
4427 enabled: function(elem){
4428 return elem.disabled === false && elem.type !== "hidden";
4430 disabled: function(elem){
4431 return elem.disabled === true;
4433 checked: function(elem){
4434 return elem.checked === true;
4436 selected: function(elem){
4437 elem.parentNode.selectedIndex;
4438 return elem.selected === true;
4440 parent: function(elem){
4441 return !!elem.firstChild;
4443 empty: function(elem){
4444 return !elem.firstChild;
4446 has: function(elem, i, match){
4447 return !!Sizzle( match[3], elem ).length;
4449 header: function(elem){
4450 return /h\d/i.test( elem.nodeName );
4452 text: function(elem){
4453 return "text" === elem.type;
4455 radio: function(elem){
4456 return "radio" === elem.type;
4458 checkbox: function(elem){
4459 return "checkbox" === elem.type;
4461 file: function(elem){
4462 return "file" === elem.type;
4464 password: function(elem){
4465 return "password" === elem.type;
4467 submit: function(elem){
4468 return "submit" === elem.type;
4470 image: function(elem){
4471 return "image" === elem.type;
4473 reset: function(elem){
4474 return "reset" === elem.type;
4476 button: function(elem){
4477 return "button" === elem.type || elem.nodeName.toUpperCase() === "BUTTON";
4479 input: function(elem){
4480 return /input|select|textarea|button/i.test(elem.nodeName);
4484 first: function(elem, i){
4487 last: function(elem, i, match, array){
4488 return i === array.length - 1;
4490 even: function(elem, i){
4493 odd: function(elem, i){
4496 lt: function(elem, i, match){
4497 return i < match[3] - 0;
4499 gt: function(elem, i, match){
4500 return i > match[3] - 0;
4502 nth: function(elem, i, match){
4503 return match[3] - 0 == i;
4505 eq: function(elem, i, match){
4506 return match[3] - 0 == i;
4510 PSEUDO: function(elem, match, i, array){
4511 var name = match[1], filter = Expr.filters[ name ];
4514 return filter( elem, i, match, array );
4515 } else if ( name === "contains" ) {
4516 return (elem.textContent || elem.innerText || "").indexOf(match[3]) >= 0;
4517 } else if ( name === "not" ) {
4520 for ( var i = 0, l = not.length; i < l; i++ ) {
4521 if ( not[i] === elem ) {
4529 CHILD: function(elem, match){
4530 var type = match[1], node = elem;
4534 while ( (node = node.previousSibling) ) {
4535 if ( node.nodeType === 1 ) return false;
4537 if ( type == 'first') return true;
4540 while ( (node = node.nextSibling) ) {
4541 if ( node.nodeType === 1 ) return false;
4545 var first = match[2], last = match[3];
4547 if ( first == 1 && last == 0 ) {
4551 var doneName = match[0],
4552 parent = elem.parentNode;
4554 if ( parent && (parent.sizcache !== doneName || !elem.nodeIndex) ) {
4556 for ( node = parent.firstChild; node; node = node.nextSibling ) {
4557 if ( node.nodeType === 1 ) {
4558 node.nodeIndex = ++count;
4561 parent.sizcache = doneName;
4564 var diff = elem.nodeIndex - last;
4568 return ( diff % first == 0 && diff / first >= 0 );
4572 ID: function(elem, match){
4573 return elem.nodeType === 1 && elem.getAttribute("id") === match;
4575 TAG: function(elem, match){
4576 return (match === "*" && elem.nodeType === 1) || elem.nodeName === match;
4578 CLASS: function(elem, match){
4579 return (" " + (elem.className || elem.getAttribute("class")) + " ")
4580 .indexOf( match ) > -1;
4582 ATTR: function(elem, match){
4583 var name = match[1],
4584 result = Expr.attrHandle[ name ] ?
4585 Expr.attrHandle[ name ]( elem ) :
4586 elem[ name ] != null ?
4588 elem.getAttribute( name ),
4589 value = result + "",
4593 return result == null ?
4598 value.indexOf(check) >= 0 :
4600 (" " + value + " ").indexOf(check) >= 0 :
4602 value && result !== false :
4606 value.indexOf(check) === 0 :
4608 value.substr(value.length - check.length) === check :
4610 value === check || value.substr(0, check.length + 1) === check + "-" :
4613 POS: function(elem, match, i, array){
4614 var name = match[2], filter = Expr.setFilters[ name ];
4617 return filter( elem, i, match, array );
4623 var origPOS = Expr.match.POS;
4625 for ( var type in Expr.match ) {
4626 Expr.match[ type ] = new RegExp( Expr.match[ type ].source + /(?![^\[]*\])(?![^\(]*\))/.source );
4627 Expr.leftMatch[ type ] = new RegExp( /(^(?:.|\r|\n)*?)/.source + Expr.match[ type ].source );
4630 var makeArray = function(array, results) {
4631 array = Array.prototype.slice.call( array, 0 );
4634 results.push.apply( results, array );
4642 Array.prototype.slice.call( document.documentElement.childNodes, 0 );
4645 makeArray = function(array, results) {
4646 var ret = results || [];
4648 if ( toString.call(array) === "[object Array]" ) {
4649 Array.prototype.push.apply( ret, array );
4651 if ( typeof array.length === "number" ) {
4652 for ( var i = 0, l = array.length; i < l; i++ ) {
4653 ret.push( array[i] );
4656 for ( var i = 0; array[i]; i++ ) {
4657 ret.push( array[i] );
4668 if ( document.documentElement.compareDocumentPosition ) {
4669 sortOrder = function( a, b ) {
4670 if ( !a.compareDocumentPosition || !b.compareDocumentPosition ) {
4672 hasDuplicate = true;
4677 var ret = a.compareDocumentPosition(b) & 4 ? -1 : a === b ? 0 : 1;
4679 hasDuplicate = true;
4683 } else if ( "sourceIndex" in document.documentElement ) {
4684 sortOrder = function( a, b ) {
4685 if ( !a.sourceIndex || !b.sourceIndex ) {
4687 hasDuplicate = true;
4692 var ret = a.sourceIndex - b.sourceIndex;
4694 hasDuplicate = true;
4698 } else if ( document.createRange ) {
4699 sortOrder = function( a, b ) {
4700 if ( !a.ownerDocument || !b.ownerDocument ) {
4702 hasDuplicate = true;
4707 var aRange = a.ownerDocument.createRange(), bRange = b.ownerDocument.createRange();
4708 aRange.setStart(a, 0);
4709 aRange.setEnd(a, 0);
4710 bRange.setStart(b, 0);
4711 bRange.setEnd(b, 0);
4712 var ret = aRange.compareBoundaryPoints(Range.START_TO_END, bRange);
4714 hasDuplicate = true;
4721 var form = document.createElement("div"),
4722 id = "script" + (new Date).getTime();
4723 form.innerHTML = "<a name='" + id + "'/>";
4725 var root = document.documentElement;
4726 root.insertBefore( form, root.firstChild );
4728 if ( !!document.getElementById( id ) ) {
4729 Expr.find.ID = function(match, context, isXML){
4730 if ( typeof context.getElementById !== "undefined" && !isXML ) {
4731 var m = context.getElementById(match[1]);
4732 return m ? m.id === match[1] || typeof m.getAttributeNode !== "undefined" && m.getAttributeNode("id").nodeValue === match[1] ? [m] : undefined : [];
4736 Expr.filter.ID = function(elem, match){
4737 var node = typeof elem.getAttributeNode !== "undefined" && elem.getAttributeNode("id");
4738 return elem.nodeType === 1 && node && node.nodeValue === match;
4742 root.removeChild( form );
4743 root = form = null; // release memory in IE
4748 var div = document.createElement("div");
4749 div.appendChild( document.createComment("") );
4751 if ( div.getElementsByTagName("*").length > 0 ) {
4752 Expr.find.TAG = function(match, context){
4753 var results = context.getElementsByTagName(match[1]);
4755 if ( match[1] === "*" ) {
4758 for ( var i = 0; results[i]; i++ ) {
4759 if ( results[i].nodeType === 1 ) {
4760 tmp.push( results[i] );
4771 div.innerHTML = "<a href='#'></a>";
4772 if ( div.firstChild && typeof div.firstChild.getAttribute !== "undefined" &&
4773 div.firstChild.getAttribute("href") !== "#" ) {
4774 Expr.attrHandle.href = function(elem){
4775 return elem.getAttribute("href", 2);
4779 div = null; // release memory in IE
4782 if ( document.querySelectorAll ) (function(){
4783 var oldSizzle = Sizzle, div = document.createElement("div");
4784 div.innerHTML = "<p class='TEST'></p>";
4786 if ( div.querySelectorAll && div.querySelectorAll(".TEST").length === 0 ) {
4790 Sizzle = function(query, context, extra, seed){
4791 context = context || document;
4793 if ( !seed && context.nodeType === 9 && !isXML(context) ) {
4795 return makeArray( context.querySelectorAll(query), extra );
4799 return oldSizzle(query, context, extra, seed);
4802 for ( var prop in oldSizzle ) {
4803 Sizzle[ prop ] = oldSizzle[ prop ];
4806 div = null; // release memory in IE
4809 if ( document.getElementsByClassName && document.documentElement.getElementsByClassName ) (function(){
4810 var div = document.createElement("div");
4811 div.innerHTML = "<div class='test e'></div><div class='test'></div>";
4813 if ( div.getElementsByClassName("e").length === 0 )
4816 div.lastChild.className = "e";
4818 if ( div.getElementsByClassName("e").length === 1 )
4821 Expr.order.splice(1, 0, "CLASS");
4822 Expr.find.CLASS = function(match, context, isXML) {
4823 if ( typeof context.getElementsByClassName !== "undefined" && !isXML ) {
4824 return context.getElementsByClassName(match[1]);
4828 div = null; // release memory in IE
4831 function dirNodeCheck( dir, cur, doneName, checkSet, nodeCheck, isXML ) {
4832 var sibDir = dir == "previousSibling" && !isXML;
4833 for ( var i = 0, l = checkSet.length; i < l; i++ ) {
4834 var elem = checkSet[i];
4836 if ( sibDir && elem.nodeType === 1 ){
4837 elem.sizcache = doneName;
4844 if ( elem.sizcache === doneName ) {
4845 match = checkSet[elem.sizset];
4849 if ( elem.nodeType === 1 && !isXML ){
4850 elem.sizcache = doneName;
4854 if ( elem.nodeName === cur ) {
4862 checkSet[i] = match;
4867 function dirCheck( dir, cur, doneName, checkSet, nodeCheck, isXML ) {
4868 var sibDir = dir == "previousSibling" && !isXML;
4869 for ( var i = 0, l = checkSet.length; i < l; i++ ) {
4870 var elem = checkSet[i];
4872 if ( sibDir && elem.nodeType === 1 ) {
4873 elem.sizcache = doneName;
4880 if ( elem.sizcache === doneName ) {
4881 match = checkSet[elem.sizset];
4885 if ( elem.nodeType === 1 ) {
4887 elem.sizcache = doneName;
4890 if ( typeof cur !== "string" ) {
4891 if ( elem === cur ) {
4896 } else if ( Sizzle.filter( cur, [elem] ).length > 0 ) {
4905 checkSet[i] = match;
4910 var contains = document.compareDocumentPosition ? function(a, b){
4911 return a.compareDocumentPosition(b) & 16;
4913 return a !== b && (a.contains ? a.contains(b) : true);
4916 var isXML = function(elem){
4917 return elem.nodeType === 9 && elem.documentElement.nodeName !== "HTML" ||
4918 !!elem.ownerDocument && elem.ownerDocument.documentElement.nodeName !== "HTML";
4921 var posProcess = function(selector, context){
4922 var tmpSet = [], later = "", match,
4923 root = context.nodeType ? [context] : context;
4925 while ( (match = Expr.match.PSEUDO.exec( selector )) ) {
4927 selector = selector.replace( Expr.match.PSEUDO, "" );
4930 selector = Expr.relative[selector] ? selector + "*" : selector;
4932 for ( var i = 0, l = root.length; i < l; i++ ) {
4933 Sizzle( selector, root[i], tmpSet );
4936 return Sizzle.filter( later, tmpSet );
4940 window.Sizzle = Sizzle;
4944 ;(function(engine) {
4945 var extendElements = Prototype.Selector.extendElements;
4947 function select(selector, scope) {
4948 return extendElements(engine(selector, scope || document));
4951 function match(element, selector) {
4952 return engine.matches(selector, [element]).length == 1;
4955 Prototype.Selector.engine = engine;
4956 Prototype.Selector.select = select;
4957 Prototype.Selector.match = match;
4960 window.Sizzle = Prototype._original_property;
4961 delete Prototype._original_property;
4964 reset: function(form) {
4970 serializeElements: function(elements, options) {
4971 if (typeof options != 'object') options = { hash: !!options };
4972 else if (Object.isUndefined(options.hash)) options.hash = true;
4973 var key, value, submitted = false, submit = options.submit, accumulator, initial;
4977 accumulator = function(result, key, value) {
4978 if (key in result) {
4979 if (!Object.isArray(result[key])) result[key] = [result[key]];
4980 result[key].push(value);
4981 } else result[key] = value;
4986 accumulator = function(result, key, value) {
4987 return result + (result ? '&' : '') + encodeURIComponent(key) + '=' + encodeURIComponent(value);
4991 return elements.inject(initial, function(result, element) {
4992 if (!element.disabled && element.name) {
4993 key = element.name; value = $(element).getValue();
4994 if (value != null && element.type != 'file' && (element.type != 'submit' || (!submitted &&
4995 submit !== false && (!submit || key == submit) && (submitted = true)))) {
4996 result = accumulator(result, key, value);
5005 serialize: function(form, options) {
5006 return Form.serializeElements(Form.getElements(form), options);
5009 getElements: function(form) {
5010 var elements = $(form).getElementsByTagName('*'),
5013 serializers = Form.Element.Serializers;
5014 for (var i = 0; element = elements[i]; i++) {
5017 return arr.inject([], function(elements, child) {
5018 if (serializers[child.tagName.toLowerCase()])
5019 elements.push(Element.extend(child));
5024 getInputs: function(form, typeName, name) {
5026 var inputs = form.getElementsByTagName('input');
5028 if (!typeName && !name) return $A(inputs).map(Element.extend);
5030 for (var i = 0, matchingInputs = [], length = inputs.length; i < length; i++) {
5031 var input = inputs[i];
5032 if ((typeName && input.type != typeName) || (name && input.name != name))
5034 matchingInputs.push(Element.extend(input));
5037 return matchingInputs;
5040 disable: function(form) {
5042 Form.getElements(form).invoke('disable');
5046 enable: function(form) {
5048 Form.getElements(form).invoke('enable');
5052 findFirstElement: function(form) {
5053 var elements = $(form).getElements().findAll(function(element) {
5054 return 'hidden' != element.type && !element.disabled;
5056 var firstByIndex = elements.findAll(function(element) {
5057 return element.hasAttribute('tabIndex') && element.tabIndex >= 0;
5058 }).sortBy(function(element) { return element.tabIndex }).first();
5060 return firstByIndex ? firstByIndex : elements.find(function(element) {
5061 return /^(?:input|select|textarea)$/i.test(element.tagName);
5065 focusFirstElement: function(form) {
5067 var element = form.findFirstElement();
5068 if (element) element.activate();
5072 request: function(form, options) {
5073 form = $(form), options = Object.clone(options || { });
5075 var params = options.parameters, action = form.readAttribute('action') || '';
5076 if (action.blank()) action = window.location.href;
5077 options.parameters = form.serialize(true);
5080 if (Object.isString(params)) params = params.toQueryParams();
5081 Object.extend(options.parameters, params);
5084 if (form.hasAttribute('method') && !options.method)
5085 options.method = form.method;
5087 return new Ajax.Request(action, options);
5091 /*--------------------------------------------------------------------------*/
5095 focus: function(element) {
5100 select: function(element) {
5101 $(element).select();
5106 Form.Element.Methods = {
5108 serialize: function(element) {
5109 element = $(element);
5110 if (!element.disabled && element.name) {
5111 var value = element.getValue();
5112 if (value != undefined) {
5114 pair[element.name] = value;
5115 return Object.toQueryString(pair);
5121 getValue: function(element) {
5122 element = $(element);
5123 var method = element.tagName.toLowerCase();
5124 return Form.Element.Serializers[method](element);
5127 setValue: function(element, value) {
5128 element = $(element);
5129 var method = element.tagName.toLowerCase();
5130 Form.Element.Serializers[method](element, value);
5134 clear: function(element) {
5135 $(element).value = '';
5139 present: function(element) {
5140 return $(element).value != '';
5143 activate: function(element) {
5144 element = $(element);
5147 if (element.select && (element.tagName.toLowerCase() != 'input' ||
5148 !(/^(?:button|reset|submit)$/i.test(element.type))))
5154 disable: function(element) {
5155 element = $(element);
5156 element.disabled = true;
5160 enable: function(element) {
5161 element = $(element);
5162 element.disabled = false;
5167 /*--------------------------------------------------------------------------*/
5169 var Field = Form.Element;
5171 var $F = Form.Element.Methods.getValue;
5173 /*--------------------------------------------------------------------------*/
5175 Form.Element.Serializers = (function() {
5176 function input(element, value) {
5177 switch (element.type.toLowerCase()) {
5180 return inputSelector(element, value);
5182 return valueSelector(element, value);
5186 function inputSelector(element, value) {
5187 if (Object.isUndefined(value))
5188 return element.checked ? element.value : null;
5189 else element.checked = !!value;
5192 function valueSelector(element, value) {
5193 if (Object.isUndefined(value)) return element.value;
5194 else element.value = value;
5197 function select(element, value) {
5198 if (Object.isUndefined(value))
5199 return (element.type === 'select-one' ? selectOne : selectMany)(element);
5201 var opt, currentValue, single = !Object.isArray(value);
5202 for (var i = 0, length = element.length; i < length; i++) {
5203 opt = element.options[i];
5204 currentValue = this.optionValue(opt);
5206 if (currentValue == value) {
5207 opt.selected = true;
5211 else opt.selected = value.include(currentValue);
5215 function selectOne(element) {
5216 var index = element.selectedIndex;
5217 return index >= 0 ? optionValue(element.options[index]) : null;
5220 function selectMany(element) {
5221 var values, length = element.length;
5222 if (!length) return null;
5224 for (var i = 0, values = []; i < length; i++) {
5225 var opt = element.options[i];
5226 if (opt.selected) values.push(optionValue(opt));
5231 function optionValue(opt) {
5232 return Element.hasAttribute(opt, 'value') ? opt.value : opt.text;
5237 inputSelector: inputSelector,
5238 textarea: valueSelector,
5240 selectOne: selectOne,
5241 selectMany: selectMany,
5242 optionValue: optionValue,
5243 button: valueSelector
5247 /*--------------------------------------------------------------------------*/
5250 Abstract.TimedObserver = Class.create(PeriodicalExecuter, {
5251 initialize: function($super, element, frequency, callback) {
5252 $super(callback, frequency);
5253 this.element = $(element);
5254 this.lastValue = this.getValue();
5257 execute: function() {
5258 var value = this.getValue();
5259 if (Object.isString(this.lastValue) && Object.isString(value) ?
5260 this.lastValue != value : String(this.lastValue) != String(value)) {
5261 this.callback(this.element, value);
5262 this.lastValue = value;
5267 Form.Element.Observer = Class.create(Abstract.TimedObserver, {
5268 getValue: function() {
5269 return Form.Element.getValue(this.element);
5273 Form.Observer = Class.create(Abstract.TimedObserver, {
5274 getValue: function() {
5275 return Form.serialize(this.element);
5279 /*--------------------------------------------------------------------------*/
5281 Abstract.EventObserver = Class.create({
5282 initialize: function(element, callback) {
5283 this.element = $(element);
5284 this.callback = callback;
5286 this.lastValue = this.getValue();
5287 if (this.element.tagName.toLowerCase() == 'form')
5288 this.registerFormCallbacks();
5290 this.registerCallback(this.element);
5293 onElementEvent: function() {
5294 var value = this.getValue();
5295 if (this.lastValue != value) {
5296 this.callback(this.element, value);
5297 this.lastValue = value;
5301 registerFormCallbacks: function() {
5302 Form.getElements(this.element).each(this.registerCallback, this);
5305 registerCallback: function(element) {
5307 switch (element.type.toLowerCase()) {
5310 Event.observe(element, 'click', this.onElementEvent.bind(this));
5313 Event.observe(element, 'change', this.onElementEvent.bind(this));
5320 Form.Element.EventObserver = Class.create(Abstract.EventObserver, {
5321 getValue: function() {
5322 return Form.Element.getValue(this.element);
5326 Form.EventObserver = Class.create(Abstract.EventObserver, {
5327 getValue: function() {
5328 return Form.serialize(this.element);
5352 var docEl = document.documentElement;
5353 var MOUSEENTER_MOUSELEAVE_EVENTS_SUPPORTED = 'onmouseenter' in docEl
5354 && 'onmouseleave' in docEl;
5358 var isIELegacyEvent = function(event) { return false; };
5360 if (window.attachEvent) {
5361 if (window.addEventListener) {
5362 isIELegacyEvent = function(event) {
5363 return !(event instanceof window.Event);
5366 isIELegacyEvent = function(event) { return true; };
5372 function _isButtonForDOMEvents(event, code) {
5373 return event.which ? (event.which === code + 1) : (event.button === code);
5376 var legacyButtonMap = { 0: 1, 1: 4, 2: 2 };
5377 function _isButtonForLegacyEvents(event, code) {
5378 return event.button === legacyButtonMap[code];
5381 function _isButtonForWebKit(event, code) {
5383 case 0: return event.which == 1 && !event.metaKey;
5384 case 1: return event.which == 2 || (event.which == 1 && event.metaKey);
5385 case 2: return event.which == 3;
5386 default: return false;
5390 if (window.attachEvent) {
5391 if (!window.addEventListener) {
5392 _isButton = _isButtonForLegacyEvents;
5394 _isButton = function(event, code) {
5395 return isIELegacyEvent(event) ? _isButtonForLegacyEvents(event, code) :
5396 _isButtonForDOMEvents(event, code);
5399 } else if (Prototype.Browser.WebKit) {
5400 _isButton = _isButtonForWebKit;
5402 _isButton = _isButtonForDOMEvents;
5405 function isLeftClick(event) { return _isButton(event, 0) }
5407 function isMiddleClick(event) { return _isButton(event, 1) }
5409 function isRightClick(event) { return _isButton(event, 2) }
5411 function element(event) {
5412 event = Event.extend(event);
5414 var node = event.target, type = event.type,
5415 currentTarget = event.currentTarget;
5417 if (currentTarget && currentTarget.tagName) {
5418 if (type === 'load' || type === 'error' ||
5419 (type === 'click' && currentTarget.tagName.toLowerCase() === 'input'
5420 && currentTarget.type === 'radio'))
5421 node = currentTarget;
5424 if (node.nodeType == Node.TEXT_NODE)
5425 node = node.parentNode;
5427 return Element.extend(node);
5430 function findElement(event, expression) {
5431 var element = Event.element(event);
5433 if (!expression) return element;
5435 if (Object.isElement(element) && Prototype.Selector.match(element, expression)) {
5436 return Element.extend(element);
5438 element = element.parentNode;
5442 function pointer(event) {
5443 return { x: pointerX(event), y: pointerY(event) };
5446 function pointerX(event) {
5447 var docElement = document.documentElement,
5448 body = document.body || { scrollLeft: 0 };
5450 return event.pageX || (event.clientX +
5451 (docElement.scrollLeft || body.scrollLeft) -
5452 (docElement.clientLeft || 0));
5455 function pointerY(event) {
5456 var docElement = document.documentElement,
5457 body = document.body || { scrollTop: 0 };
5459 return event.pageY || (event.clientY +
5460 (docElement.scrollTop || body.scrollTop) -
5461 (docElement.clientTop || 0));
5465 function stop(event) {
5466 Event.extend(event);
5467 event.preventDefault();
5468 event.stopPropagation();
5470 event.stopped = true;
5475 isLeftClick: isLeftClick,
5476 isMiddleClick: isMiddleClick,
5477 isRightClick: isRightClick,
5480 findElement: findElement,
5489 var methods = Object.keys(Event.Methods).inject({ }, function(m, name) {
5490 m[name] = Event.Methods[name].methodize();
5494 if (window.attachEvent) {
5495 function _relatedTarget(event) {
5497 switch (event.type) {
5500 element = event.fromElement;
5504 element = event.toElement;
5509 return Element.extend(element);
5512 var additionalMethods = {
5513 stopPropagation: function() { this.cancelBubble = true },
5514 preventDefault: function() { this.returnValue = false },
5515 inspect: function() { return '[object Event]' }
5518 Event.extend = function(event, element) {
5519 if (!event) return false;
5521 if (!isIELegacyEvent(event)) return event;
5523 if (event._extendedByPrototype) return event;
5524 event._extendedByPrototype = Prototype.emptyFunction;
5526 var pointer = Event.pointer(event);
5528 Object.extend(event, {
5529 target: event.srcElement || element,
5530 relatedTarget: _relatedTarget(event),
5535 Object.extend(event, methods);
5536 Object.extend(event, additionalMethods);
5541 Event.extend = Prototype.K;
5544 if (window.addEventListener) {
5545 Event.prototype = window.Event.prototype || document.createEvent('HTMLEvents').__proto__;
5546 Object.extend(Event.prototype, methods);
5549 function _createResponder(element, eventName, handler) {
5550 var registry = Element.retrieve(element, 'prototype_event_registry');
5552 if (Object.isUndefined(registry)) {
5553 CACHE.push(element);
5554 registry = Element.retrieve(element, 'prototype_event_registry', $H());
5557 var respondersForEvent = registry.get(eventName);
5558 if (Object.isUndefined(respondersForEvent)) {
5559 respondersForEvent = [];
5560 registry.set(eventName, respondersForEvent);
5563 if (respondersForEvent.pluck('handler').include(handler)) return false;
5566 if (eventName.include(":")) {
5567 responder = function(event) {
5568 if (Object.isUndefined(event.eventName))
5571 if (event.eventName !== eventName)
5574 Event.extend(event, element);
5575 handler.call(element, event);
5578 if (!MOUSEENTER_MOUSELEAVE_EVENTS_SUPPORTED &&
5579 (eventName === "mouseenter" || eventName === "mouseleave")) {
5580 if (eventName === "mouseenter" || eventName === "mouseleave") {
5581 responder = function(event) {
5582 Event.extend(event, element);
5584 var parent = event.relatedTarget;
5585 while (parent && parent !== element) {
5586 try { parent = parent.parentNode; }
5587 catch(e) { parent = element; }
5590 if (parent === element) return;
5592 handler.call(element, event);
5596 responder = function(event) {
5597 Event.extend(event, element);
5598 handler.call(element, event);
5603 responder.handler = handler;
5604 respondersForEvent.push(responder);
5608 function _destroyCache() {
5609 for (var i = 0, length = CACHE.length; i < length; i++) {
5610 Event.stopObserving(CACHE[i]);
5617 if (Prototype.Browser.IE)
5618 window.attachEvent('onunload', _destroyCache);
5620 if (Prototype.Browser.WebKit)
5621 window.addEventListener('unload', Prototype.emptyFunction, false);
5624 var _getDOMEventName = Prototype.K,
5625 translations = { mouseenter: "mouseover", mouseleave: "mouseout" };
5627 if (!MOUSEENTER_MOUSELEAVE_EVENTS_SUPPORTED) {
5628 _getDOMEventName = function(eventName) {
5629 return (translations[eventName] || eventName);
5633 function observe(element, eventName, handler) {
5634 element = $(element);
5636 var responder = _createResponder(element, eventName, handler);
5638 if (!responder) return element;
5640 if (eventName.include(':')) {
5641 if (element.addEventListener)
5642 element.addEventListener("dataavailable", responder, false);
5644 element.attachEvent("ondataavailable", responder);
5645 element.attachEvent("onlosecapture", responder);
5648 var actualEventName = _getDOMEventName(eventName);
5650 if (element.addEventListener)
5651 element.addEventListener(actualEventName, responder, false);
5653 element.attachEvent("on" + actualEventName, responder);
5659 function stopObserving(element, eventName, handler) {
5660 element = $(element);
5662 var registry = Element.retrieve(element, 'prototype_event_registry');
5663 if (!registry) return element;
5666 registry.each( function(pair) {
5667 var eventName = pair.key;
5668 stopObserving(element, eventName);
5673 var responders = registry.get(eventName);
5674 if (!responders) return element;
5677 responders.each(function(r) {
5678 stopObserving(element, eventName, r.handler);
5683 var i = responders.length, responder;
5685 if (responders[i].handler === handler) {
5686 responder = responders[i];
5690 if (!responder) return element;
5692 if (eventName.include(':')) {
5693 if (element.removeEventListener)
5694 element.removeEventListener("dataavailable", responder, false);
5696 element.detachEvent("ondataavailable", responder);
5697 element.detachEvent("onlosecapture", responder);
5700 var actualEventName = _getDOMEventName(eventName);
5701 if (element.removeEventListener)
5702 element.removeEventListener(actualEventName, responder, false);
5704 element.detachEvent('on' + actualEventName, responder);
5707 registry.set(eventName, responders.without(responder));
5712 function fire(element, eventName, memo, bubble) {
5713 element = $(element);
5715 if (Object.isUndefined(bubble))
5718 if (element == document && document.createEvent && !element.dispatchEvent)
5719 element = document.documentElement;
5722 if (document.createEvent) {
5723 event = document.createEvent('HTMLEvents');
5724 event.initEvent('dataavailable', bubble, true);
5726 event = document.createEventObject();
5727 event.eventType = bubble ? 'ondataavailable' : 'onlosecapture';
5730 event.eventName = eventName;
5731 event.memo = memo || { };
5733 if (document.createEvent)
5734 element.dispatchEvent(event);
5736 element.fireEvent(event.eventType, event);
5738 return Event.extend(event);
5741 Event.Handler = Class.create({
5742 initialize: function(element, eventName, selector, callback) {
5743 this.element = $(element);
5744 this.eventName = eventName;
5745 this.selector = selector;
5746 this.callback = callback;
5747 this.handler = this.handleEvent.bind(this);
5751 Event.observe(this.element, this.eventName, this.handler);
5756 Event.stopObserving(this.element, this.eventName, this.handler);
5760 handleEvent: function(event) {
5761 var element = Event.findElement(event, this.selector);
5762 if (element) this.callback.call(this.element, event, element);
5766 function on(element, eventName, selector, callback) {
5767 element = $(element);
5768 if (Object.isFunction(selector) && Object.isUndefined(callback)) {
5769 callback = selector, selector = null;
5772 return new Event.Handler(element, eventName, selector, callback).start();
5775 Object.extend(Event, Event.Methods);
5777 Object.extend(Event, {
5780 stopObserving: stopObserving,
5784 Element.addMethods({
5789 stopObserving: stopObserving,
5794 Object.extend(document, {
5795 fire: fire.methodize(),
5797 observe: observe.methodize(),
5799 stopObserving: stopObserving.methodize(),
5806 if (window.Event) Object.extend(window.Event, Event);
5807 else window.Event = Event;
5811 /* Support for the DOMContentLoaded event is based on work by Dan Webb,
5812 Matthias Miller, Dean Edwards, John Resig, and Diego Perini. */
5816 function fireContentLoadedEvent() {
5817 if (document.loaded) return;
5818 if (timer) window.clearTimeout(timer);
5819 document.loaded = true;
5820 document.fire('dom:loaded');
5823 function checkReadyState() {
5824 if (document.readyState === 'complete') {
5825 document.stopObserving('readystatechange', checkReadyState);
5826 fireContentLoadedEvent();
5830 function pollDoScroll() {
5831 try { document.documentElement.doScroll('left'); }
5833 timer = pollDoScroll.defer();
5836 fireContentLoadedEvent();
5839 if (document.addEventListener) {
5840 document.addEventListener('DOMContentLoaded', fireContentLoadedEvent, false);
5842 document.observe('readystatechange', checkReadyState);
5844 timer = pollDoScroll.defer();
5847 Event.observe(window, 'load', fireContentLoadedEvent);
5850 Element.addMethods();
5852 /*------------------------------- DEPRECATED -------------------------------*/
5854 Hash.toQueryString = Object.toQueryString;
5856 var Toggle = { display: Element.toggle };
5858 Element.Methods.childOf = Element.Methods.descendantOf;
5861 Before: function(element, content) {
5862 return Element.insert(element, {before:content});
5865 Top: function(element, content) {
5866 return Element.insert(element, {top:content});
5869 Bottom: function(element, content) {
5870 return Element.insert(element, {bottom:content});
5873 After: function(element, content) {
5874 return Element.insert(element, {after:content});
5878 var $continue = new Error('"throw $continue" is deprecated, use "return" instead');
5881 includeScrollOffsets: false,
5883 prepare: function() {
5884 this.deltaX = window.pageXOffset
5885 || document.documentElement.scrollLeft
5886 || document.body.scrollLeft
5888 this.deltaY = window.pageYOffset
5889 || document.documentElement.scrollTop
5890 || document.body.scrollTop
5894 within: function(element, x, y) {
5895 if (this.includeScrollOffsets)
5896 return this.withinIncludingScrolloffsets(element, x, y);
5899 this.offset = Element.cumulativeOffset(element);
5901 return (y >= this.offset[1] &&
5902 y < this.offset[1] + element.offsetHeight &&
5903 x >= this.offset[0] &&
5904 x < this.offset[0] + element.offsetWidth);
5907 withinIncludingScrolloffsets: function(element, x, y) {
5908 var offsetcache = Element.cumulativeScrollOffset(element);
5910 this.xcomp = x + offsetcache[0] - this.deltaX;
5911 this.ycomp = y + offsetcache[1] - this.deltaY;
5912 this.offset = Element.cumulativeOffset(element);
5914 return (this.ycomp >= this.offset[1] &&
5915 this.ycomp < this.offset[1] + element.offsetHeight &&
5916 this.xcomp >= this.offset[0] &&
5917 this.xcomp < this.offset[0] + element.offsetWidth);
5920 overlap: function(mode, element) {
5921 if (!mode) return 0;
5922 if (mode == 'vertical')
5923 return ((this.offset[1] + element.offsetHeight) - this.ycomp) /
5924 element.offsetHeight;
5925 if (mode == 'horizontal')
5926 return ((this.offset[0] + element.offsetWidth) - this.xcomp) /
5927 element.offsetWidth;
5931 cumulativeOffset: Element.Methods.cumulativeOffset,
5933 positionedOffset: Element.Methods.positionedOffset,
5935 absolutize: function(element) {
5937 return Element.absolutize(element);
5940 relativize: function(element) {
5942 return Element.relativize(element);
5945 realOffset: Element.Methods.cumulativeScrollOffset,
5947 offsetParent: Element.Methods.getOffsetParent,
5949 page: Element.Methods.viewportOffset,
5951 clone: function(source, target, options) {
5952 options = options || { };
5953 return Element.clonePosition(target, source, options);
5957 /*--------------------------------------------------------------------------*/
5959 if (!document.getElementsByClassName) document.getElementsByClassName = function(instanceMethods){
5960 function iter(name) {
5961 return name.blank() ? null : "[contains(concat(' ', @class, ' '), ' " + name + " ')]";
5964 instanceMethods.getElementsByClassName = Prototype.BrowserFeatures.XPath ?
5965 function(element, className) {
5966 className = className.toString().strip();
5967 var cond = /\s/.test(className) ? $w(className).map(iter).join('') : iter(className);
5968 return cond ? document._getElementsByXPath('.//*' + cond, element) : [];
5969 } : function(element, className) {
5970 className = className.toString().strip();
5971 var elements = [], classNames = (/\s/.test(className) ? $w(className) : null);
5972 if (!classNames && !className) return elements;
5974 var nodes = $(element).getElementsByTagName('*');
5975 className = ' ' + className + ' ';
5977 for (var i = 0, child, cn; child = nodes[i]; i++) {
5978 if (child.className && (cn = ' ' + child.className + ' ') && (cn.include(className) ||
5979 (classNames && classNames.all(function(name) {
5980 return !name.toString().blank() && cn.include(' ' + name + ' ');
5982 elements.push(Element.extend(child));
5987 return function(className, parentElement) {
5988 return $(parentElement || document.body).getElementsByClassName(className);
5992 /*--------------------------------------------------------------------------*/
5994 Element.ClassNames = Class.create();
5995 Element.ClassNames.prototype = {
5996 initialize: function(element) {
5997 this.element = $(element);
6000 _each: function(iterator) {
6001 this.element.className.split(/\s+/).select(function(name) {
6002 return name.length > 0;
6006 set: function(className) {
6007 this.element.className = className;
6010 add: function(classNameToAdd) {
6011 if (this.include(classNameToAdd)) return;
6012 this.set($A(this).concat(classNameToAdd).join(' '));
6015 remove: function(classNameToRemove) {
6016 if (!this.include(classNameToRemove)) return;
6017 this.set($A(this).without(classNameToRemove).join(' '));
6020 toString: function() {
6021 return $A(this).join(' ');
6025 Object.extend(Element.ClassNames.prototype, Enumerable);
6027 /*--------------------------------------------------------------------------*/
6030 window.Selector = Class.create({
6031 initialize: function(expression) {
6032 this.expression = expression.strip();
6035 findElements: function(rootElement) {
6036 return Prototype.Selector.select(this.expression, rootElement);
6039 match: function(element) {
6040 return Prototype.Selector.match(element, this.expression);
6043 toString: function() {
6044 return this.expression;
6047 inspect: function() {
6048 return "#<Selector: " + this.expression + ">";
6052 Object.extend(Selector, {
6053 matchElements: function(elements, expression) {
6054 var match = Prototype.Selector.match,
6057 for (var i = 0, length = elements.length; i < length; i++) {
6058 var element = elements[i];
6059 if (match(element, expression)) {
6060 results.push(Element.extend(element));
6066 findElement: function(elements, expression, index) {
6068 var matchIndex = 0, element;
6069 for (var i = 0, length = elements.length; i < length; i++) {
6070 element = elements[i];
6071 if (Prototype.Selector.match(element, expression) && index === matchIndex++) {
6072 return Element.extend(element);
6077 findChildElements: function(element, expressions) {
6078 var selector = expressions.toArray().join(', ');
6079 return Prototype.Selector.select(selector, element || document);