jasmine_webos 0.0.6

Sign up to get free protection for your applications and to get access to all the features.
data/History.txt ADDED
@@ -0,0 +1,4 @@
1
+ === 0.0.1 2009-09-17
2
+
3
+ * 1 major enhancement:
4
+ * Initial release
data/Manifest.txt ADDED
@@ -0,0 +1,22 @@
1
+ History.txt
2
+ Manifest.txt
3
+ PostInstall.txt
4
+ README.rdoc
5
+ Rakefile
6
+ bin/jasmine_webos
7
+ lib/jasminewebos.rb
8
+ lib/jasminewebos/cli.rb
9
+ lib/jasminewebos/configuration.rb
10
+ lib/jasminewebos/generator.rb
11
+ lib/jasminewebos/server.rb
12
+ templates/webos/spec/javascript/matchers/all_matchers.js
13
+ templates/webos/spec/javascript/spec/sample_spec.js
14
+ vendor/jasmine/lib/jasmine.css
15
+ vendor/jasmine/lib/jasmine-0.9.0.js
16
+ vendor/jasmine/lib/json2.js
17
+ vendor/jasmine/lib/TrivialReporter.js
18
+ vendor/jasmine/contrib/ruby/run.html
19
+ vendor/jasmine/contrib/ruby/jasmine_spec_builder.rb
20
+ vendor/jasmine/contrib/ruby/jasmine_runner.rb
21
+ vendor/jasmine/contrib/ruby/spec/jasmine_runner_spec.rb
22
+ jslib/prototype.js
data/PostInstall.txt ADDED
@@ -0,0 +1 @@
1
+ For more information on jasminewebos, see http://github.com/gaffo/jasmine_webos
data/README.rdoc ADDED
@@ -0,0 +1,38 @@
1
+ = jasminewebos
2
+
3
+ * http://github.com/gaffo/jasmine_webos
4
+
5
+ == DESCRIPTION:
6
+
7
+ Generates the stub files needed for testing with jasmine on a webos application.
8
+ Runs a server to view your tests against.
9
+
10
+ == INSTALL:
11
+
12
+ sudo gem source -a http://gems.github.com
13
+ sudo gem install gaffo-jasmine_webos
14
+
15
+ == LICENSE:
16
+
17
+ (The MIT License)
18
+
19
+ Copyright (c) 2009 Mike Gaffney
20
+
21
+ Permission is hereby granted, free of charge, to any person obtaining
22
+ a copy of this software and associated documentation files (the
23
+ 'Software'), to deal in the Software without restriction, including
24
+ without limitation the rights to use, copy, modify, merge, publish,
25
+ distribute, sublicense, and/or sell copies of the Software, and to
26
+ permit persons to whom the Software is furnished to do so, subject to
27
+ the following conditions:
28
+
29
+ The above copyright notice and this permission notice shall be
30
+ included in all copies or substantial portions of the Software.
31
+
32
+ THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND,
33
+ EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
34
+ MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
35
+ IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
36
+ CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
37
+ TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
38
+ SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
data/Rakefile ADDED
@@ -0,0 +1,21 @@
1
+ require 'rubygems'
2
+ gem 'hoe', '>= 2.1.0'
3
+ require 'hoe'
4
+ require 'fileutils'
5
+ require './lib/jasminewebos'
6
+
7
+ Hoe.plugin :newgem
8
+ # Hoe.plugin :website
9
+ # Hoe.plugin :cucumberfeatures
10
+
11
+ # Generate all the Rake tasks
12
+ # Run 'rake -T' to see list of generated tasks (from gem root directory)
13
+ $hoe = Hoe.spec 'jasmine_webos' do
14
+ self.developer 'Mike Gaffney', 'mr.gaffo@gmail.com'
15
+ self.post_install_message = 'PostInstall.txt' # TODO remove if post-install message not required
16
+ self.rubyforge_name = self.name # TODO this is default value
17
+ self.extra_deps = [['thin','>= 1.2.4'], ['json', ">= 1.1.9"]]
18
+ end
19
+
20
+ require 'newgem/tasks'
21
+ Dir['tasks/**/*.rake'].each { |t| load t }
data/bin/jasmine_webos ADDED
@@ -0,0 +1,9 @@
1
+ #!/usr/bin/env ruby
2
+ #
3
+ # Created on 2009-9-17.
4
+ # Copyright (c) 2009. All rights reserved.
5
+
6
+ require 'rubygems'
7
+ require File.expand_path(File.dirname(__FILE__) + "/../lib/jasminewebos")
8
+
9
+ Jasminewebos::CLI.execute(STDOUT, ARGV)
@@ -0,0 +1,4281 @@
1
+ /* Prototype JavaScript framework, version 1.6.0.3
2
+ * (c) 2005-2008 Sam Stephenson
3
+ *
4
+ * Prototype is freely distributable under the terms of an MIT-style license.
5
+ * For details, see the Prototype web site: http://www.prototypejs.org/
6
+ *
7
+ *--------------------------------------------------------------------------*/
8
+
9
+ var Prototype = {
10
+ Version: '1.6.0.3',
11
+
12
+ Browser: {
13
+ IE: !!(window.attachEvent &&
14
+ navigator.userAgent.indexOf('Opera') === -1),
15
+ Opera: navigator.userAgent.indexOf('Opera') > -1,
16
+ WebKit: navigator.userAgent.indexOf('AppleWebKit/') > -1,
17
+ Gecko: navigator.userAgent.indexOf('Gecko') > -1 &&
18
+ navigator.userAgent.indexOf('KHTML') === -1,
19
+ MobileSafari: !!navigator.userAgent.match(/Apple.*Mobile.*Safari/)
20
+ },
21
+
22
+ BrowserFeatures: {
23
+ XPath: !!document.evaluate,
24
+ SelectorsAPI: !!document.querySelector,
25
+ ElementExtensions: !!window.HTMLElement,
26
+ SpecificElementExtensions:
27
+ document.createElement('div')['__proto__'] &&
28
+ document.createElement('div')['__proto__'] !==
29
+ document.createElement('form')['__proto__']
30
+ },
31
+
32
+ ScriptFragment: '<script[^>]*>([\\S\\s]*?)<\/script>',
33
+ JSONFilter: /^\/\*-secure-([\s\S]*)\*\/\s*$/,
34
+
35
+ emptyFunction: function() { },
36
+ K: function(x) { return x }
37
+ };
38
+
39
+ if (Prototype.Browser.MobileSafari)
40
+ Prototype.BrowserFeatures.SpecificElementExtensions = false;
41
+
42
+
43
+ /* Based on Alex Arnell's inheritance implementation. */
44
+ var Class = {
45
+ create: function() {
46
+ var parent = null, properties = $A(arguments);
47
+ if (Object.isFunction(properties[0]))
48
+ parent = properties.shift();
49
+
50
+ function klass() {
51
+ this.initialize.apply(this, arguments);
52
+ }
53
+
54
+ Object.extend(klass, Class.Methods);
55
+ klass.superclass = parent;
56
+ klass.subclasses = [];
57
+
58
+ if (parent) {
59
+ var subclass = function() { };
60
+ subclass.prototype = parent.prototype;
61
+ klass.prototype = new subclass;
62
+ parent.subclasses.push(klass);
63
+ }
64
+
65
+ for (var i = 0; i < properties.length; i++)
66
+ klass.addMethods(properties[i]);
67
+
68
+ if (!klass.prototype.initialize)
69
+ klass.prototype.initialize = Prototype.emptyFunction;
70
+
71
+ klass.prototype.constructor = klass;
72
+
73
+ return klass;
74
+ }
75
+ };
76
+
77
+ Class.Methods = {
78
+ addMethods: function(source) {
79
+ var ancestor = this.superclass && this.superclass.prototype;
80
+ var properties = Object.keys(source);
81
+
82
+ if (!Object.keys({ toString: true }).length)
83
+ properties.push("toString", "valueOf");
84
+
85
+ for (var i = 0, length = properties.length; i < length; i++) {
86
+ var property = properties[i], value = source[property];
87
+ if (ancestor && Object.isFunction(value) &&
88
+ value.argumentNames().first() == "$super") {
89
+ var method = value;
90
+ value = (function(m) {
91
+ return function() { return ancestor[m].apply(this, arguments) };
92
+ })(property).wrap(method);
93
+
94
+ value.valueOf = method.valueOf.bind(method);
95
+ value.toString = method.toString.bind(method);
96
+ }
97
+ this.prototype[property] = value;
98
+ }
99
+
100
+ return this;
101
+ }
102
+ };
103
+
104
+ var Abstract = { };
105
+
106
+ Object.extend = function(destination, source) {
107
+ for (var property in source)
108
+ destination[property] = source[property];
109
+ return destination;
110
+ };
111
+
112
+ Object.extend(Object, {
113
+ inspect: function(object) {
114
+ try {
115
+ if (Object.isUndefined(object)) return 'undefined';
116
+ if (object === null) return 'null';
117
+ return object.inspect ? object.inspect() : String(object);
118
+ } catch (e) {
119
+ if (e instanceof RangeError) return '...';
120
+ throw e;
121
+ }
122
+ },
123
+
124
+ toJSON: function(object) {
125
+ var type = typeof object;
126
+ switch (type) {
127
+ case 'undefined':
128
+ case 'function':
129
+ case 'unknown': return;
130
+ case 'boolean': return object.toString();
131
+ }
132
+
133
+ if (object === null) return 'null';
134
+ if (object.toJSON) return object.toJSON();
135
+ if (Object.isElement(object)) return;
136
+
137
+ var results = [];
138
+ for (var property in object) {
139
+ var value = Object.toJSON(object[property]);
140
+ if (!Object.isUndefined(value))
141
+ results.push(property.toJSON() + ': ' + value);
142
+ }
143
+
144
+ return '{' + results.join(', ') + '}';
145
+ },
146
+
147
+ toQueryString: function(object) {
148
+ return $H(object).toQueryString();
149
+ },
150
+
151
+ toHTML: function(object) {
152
+ return object && object.toHTML ? object.toHTML() : String.interpret(object);
153
+ },
154
+
155
+ keys: function(object) {
156
+ var keys = [];
157
+ for (var property in object)
158
+ keys.push(property);
159
+ return keys;
160
+ },
161
+
162
+ values: function(object) {
163
+ var values = [];
164
+ for (var property in object)
165
+ values.push(object[property]);
166
+ return values;
167
+ },
168
+
169
+ clone: function(object) {
170
+ return Object.extend({ }, object);
171
+ },
172
+
173
+ isElement: function(object) {
174
+ return !!(object && object.nodeType == 1);
175
+ },
176
+
177
+ isArray: function(object) {
178
+ return object != null && typeof object == "object" &&
179
+ 'splice' in object && 'join' in object;
180
+ },
181
+
182
+ isHash: function(object) {
183
+ return object instanceof Hash;
184
+ },
185
+
186
+ isFunction: function(object) {
187
+ return typeof object == "function";
188
+ },
189
+
190
+ isString: function(object) {
191
+ return typeof object == "string";
192
+ },
193
+
194
+ isNumber: function(object) {
195
+ return typeof object == "number";
196
+ },
197
+
198
+ isUndefined: function(object) {
199
+ return typeof object == "undefined";
200
+ }
201
+ });
202
+
203
+ Object.extend(Function.prototype, {
204
+ argumentNames: function() {
205
+ var names = this.toString().match(/^[\s\(]*function[^(]*\(([^\)]*)\)/)[1]
206
+ .replace(/\s+/g, '').split(',');
207
+ return names.length == 1 && !names[0] ? [] : names;
208
+ },
209
+
210
+ bind: function() {
211
+ if (arguments.length < 2 && Object.isUndefined(arguments[0])) return this;
212
+ var __method = this, args = $A(arguments), object = args.shift();
213
+ return function() {
214
+ return __method.apply(object, args.concat($A(arguments)));
215
+ }
216
+ },
217
+
218
+ bindAsEventListener: function() {
219
+ var __method = this, args = $A(arguments), object = args.shift();
220
+ return function(event) {
221
+ return __method.apply(object, [event || window.event].concat(args));
222
+ }
223
+ },
224
+
225
+ curry: function() {
226
+ if (!arguments.length) return this;
227
+ var __method = this, args = $A(arguments);
228
+ return function() {
229
+ return __method.apply(this, args.concat($A(arguments)));
230
+ }
231
+ },
232
+
233
+ delay: function() {
234
+ var __method = this, args = $A(arguments), timeout = args.shift() * 1000;
235
+ return window.setTimeout(function() {
236
+ return __method.apply(__method, args);
237
+ }, timeout);
238
+ },
239
+
240
+ defer: function() {
241
+ var args = [0.01].concat($A(arguments));
242
+ return this.delay.apply(this, args);
243
+ },
244
+
245
+ wrap: function(wrapper) {
246
+ var __method = this;
247
+ return function() {
248
+ return wrapper.apply(this, [__method.bind(this)].concat($A(arguments)));
249
+ }
250
+ },
251
+
252
+ methodize: function() {
253
+ if (this._methodized) return this._methodized;
254
+ var __method = this;
255
+ return this._methodized = function() {
256
+ return __method.apply(null, [this].concat($A(arguments)));
257
+ };
258
+ }
259
+ });
260
+
261
+ Date.prototype.toJSON = function() {
262
+ return '"' + this.getUTCFullYear() + '-' +
263
+ (this.getUTCMonth() + 1).toPaddedString(2) + '-' +
264
+ this.getUTCDate().toPaddedString(2) + 'T' +
265
+ this.getUTCHours().toPaddedString(2) + ':' +
266
+ this.getUTCMinutes().toPaddedString(2) + ':' +
267
+ this.getUTCSeconds().toPaddedString(2) + 'Z"';
268
+ };
269
+
270
+ var Try = {
271
+ these: function() {
272
+ var returnValue;
273
+
274
+ for (var i = 0, length = arguments.length; i < length; i++) {
275
+ var lambda = arguments[i];
276
+ try {
277
+ returnValue = lambda();
278
+ break;
279
+ } catch (e) { }
280
+ }
281
+
282
+ return returnValue;
283
+ }
284
+ };
285
+
286
+ RegExp.prototype.match = RegExp.prototype.test;
287
+
288
+ RegExp.escape = function(str) {
289
+ return String(str).replace(/([.*+?^=!:${}()|[\]\/\\])/g, '\\$1');
290
+ };
291
+
292
+ /*--------------------------------------------------------------------------*/
293
+
294
+ var PeriodicalExecuter = Class.create({
295
+ initialize: function(callback, frequency, targetWindow) {
296
+ this.targetWindow = targetWindow || window;
297
+ this.callback = callback;
298
+ this.frequency = frequency;
299
+ this.currentlyExecuting = false;
300
+
301
+ this.registerCallback();
302
+ },
303
+
304
+ registerCallback: function() {
305
+ this.timer = this.targetWindow.setInterval(this.onTimerEvent.bind(this), this.frequency * 1000);
306
+ },
307
+
308
+ execute: function() {
309
+ this.callback(this);
310
+ },
311
+
312
+ stop: function() {
313
+ if (!this.timer) return;
314
+ this.targetWindow.clearInterval(this.timer);
315
+ this.timer = null;
316
+ },
317
+
318
+ onTimerEvent: function() {
319
+ if (!this.currentlyExecuting) {
320
+ try {
321
+ this.currentlyExecuting = true;
322
+ this.execute();
323
+ } finally {
324
+ this.currentlyExecuting = false;
325
+ }
326
+ }
327
+ }
328
+ });
329
+ Object.extend(String, {
330
+ interpret: function(value) {
331
+ return value == null ? '' : String(value);
332
+ },
333
+ specialChar: {
334
+ '\b': '\\b',
335
+ '\t': '\\t',
336
+ '\n': '\\n',
337
+ '\f': '\\f',
338
+ '\r': '\\r',
339
+ '\\': '\\\\'
340
+ }
341
+ });
342
+
343
+ Object.extend(String.prototype, {
344
+ gsub: function(pattern, replacement) {
345
+ var result = '', source = this, match;
346
+ replacement = arguments.callee.prepareReplacement(replacement);
347
+
348
+ while (source.length > 0) {
349
+ if (match = source.match(pattern)) {
350
+ result += source.slice(0, match.index);
351
+ result += String.interpret(replacement(match));
352
+ source = source.slice(match.index + match[0].length);
353
+ } else {
354
+ result += source, source = '';
355
+ }
356
+ }
357
+ return result;
358
+ },
359
+
360
+ sub: function(pattern, replacement, count) {
361
+ replacement = this.gsub.prepareReplacement(replacement);
362
+ count = Object.isUndefined(count) ? 1 : count;
363
+
364
+ return this.gsub(pattern, function(match) {
365
+ if (--count < 0) return match[0];
366
+ return replacement(match);
367
+ });
368
+ },
369
+
370
+ scan: function(pattern, iterator) {
371
+ this.gsub(pattern, iterator);
372
+ return String(this);
373
+ },
374
+
375
+ truncate: function(length, truncation) {
376
+ length = length || 30;
377
+ truncation = Object.isUndefined(truncation) ? '...' : truncation;
378
+ return this.length > length ?
379
+ this.slice(0, length - truncation.length) + truncation : String(this);
380
+ },
381
+
382
+ strip: function() {
383
+ return this.replace(/^\s+/, '').replace(/\s+$/, '');
384
+ },
385
+
386
+ stripTags: function() {
387
+ return this.replace(/<\/?[^>]+>/gi, '');
388
+ },
389
+
390
+ stripScripts: function() {
391
+ return this.replace(new RegExp(Prototype.ScriptFragment, 'img'), '');
392
+ },
393
+
394
+ extractScripts: function() {
395
+ var matchAll = new RegExp(Prototype.ScriptFragment, 'img');
396
+ var matchOne = new RegExp(Prototype.ScriptFragment, 'im');
397
+ return (this.match(matchAll) || []).map(function(scriptTag) {
398
+ return (scriptTag.match(matchOne) || ['', ''])[1];
399
+ });
400
+ },
401
+
402
+ evalScripts: function() {
403
+ return this.extractScripts().map(function(script) { return eval(script) });
404
+ },
405
+
406
+ escapeHTML: function() {
407
+ var self = arguments.callee;
408
+ self.text.data = this;
409
+ return self.div.innerHTML;
410
+ },
411
+
412
+ unescapeHTML: function() {
413
+ var div = new Element('div');
414
+ div.innerHTML = this.stripTags();
415
+ return div.childNodes[0] ? (div.childNodes.length > 1 ?
416
+ $A(div.childNodes).inject('', function(memo, node) { return memo+node.nodeValue }) :
417
+ div.childNodes[0].nodeValue) : '';
418
+ },
419
+
420
+ toQueryParams: function(separator) {
421
+ var match = this.strip().match(/([^?#]*)(#.*)?$/);
422
+ if (!match) return { };
423
+
424
+ return match[1].split(separator || '&').inject({ }, function(hash, pair) {
425
+ if ((pair = pair.split('='))[0]) {
426
+ var key = decodeURIComponent(pair.shift());
427
+ var value = pair.length > 1 ? pair.join('=') : pair[0];
428
+ if (value != undefined) value = decodeURIComponent(value);
429
+
430
+ if (key in hash) {
431
+ if (!Object.isArray(hash[key])) hash[key] = [hash[key]];
432
+ hash[key].push(value);
433
+ }
434
+ else hash[key] = value;
435
+ }
436
+ return hash;
437
+ });
438
+ },
439
+
440
+ toArray: function() {
441
+ return this.split('');
442
+ },
443
+
444
+ succ: function() {
445
+ return this.slice(0, this.length - 1) +
446
+ String.fromCharCode(this.charCodeAt(this.length - 1) + 1);
447
+ },
448
+
449
+ times: function(count) {
450
+ return count < 1 ? '' : new Array(count + 1).join(this);
451
+ },
452
+
453
+ camelize: function() {
454
+ var parts = this.split('-'), len = parts.length;
455
+ if (len == 1) return parts[0];
456
+
457
+ var camelized = this.charAt(0) == '-'
458
+ ? parts[0].charAt(0).toUpperCase() + parts[0].substring(1)
459
+ : parts[0];
460
+
461
+ for (var i = 1; i < len; i++)
462
+ camelized += parts[i].charAt(0).toUpperCase() + parts[i].substring(1);
463
+
464
+ return camelized;
465
+ },
466
+
467
+ capitalize: function() {
468
+ return this.charAt(0).toUpperCase() + this.substring(1).toLowerCase();
469
+ },
470
+
471
+ underscore: function() {
472
+ return this.gsub(/::/, '/').gsub(/([A-Z]+)([A-Z][a-z])/,'#{1}_#{2}').gsub(/([a-z\d])([A-Z])/,'#{1}_#{2}').gsub(/-/,'_').toLowerCase();
473
+ },
474
+
475
+ dasherize: function() {
476
+ return this.gsub(/_/,'-');
477
+ },
478
+
479
+ inspect: function(useDoubleQuotes) {
480
+ var escapedString = this.gsub(/[\x00-\x1f\\]/, function(match) {
481
+ var character = String.specialChar[match[0]];
482
+ return character ? character : '\\u00' + match[0].charCodeAt().toPaddedString(2, 16);
483
+ });
484
+ if (useDoubleQuotes) return '"' + escapedString.replace(/"/g, '\\"') + '"';
485
+ return "'" + escapedString.replace(/'/g, '\\\'') + "'";
486
+ },
487
+
488
+ toJSON: function() {
489
+ return this.inspect(true);
490
+ },
491
+
492
+ unfilterJSON: function(filter) {
493
+ return this.sub(filter || Prototype.JSONFilter, '#{1}');
494
+ },
495
+
496
+ isJSON: function() {
497
+ var str = this;
498
+ if (str.blank()) return false;
499
+ str = this.replace(/\\./g, '@').replace(/"[^"\\\n\r]*"/g, '');
500
+ return (/^[,:{}\[\]0-9.\-+Eaeflnr-u \n\r\t]*$/).test(str);
501
+ },
502
+
503
+ evalJSON: function(sanitize) {
504
+ var json = this.unfilterJSON();
505
+ try {
506
+ if (!sanitize || json.isJSON()) return eval('(' + json + ')');
507
+ } catch (e) { }
508
+ throw new SyntaxError('Badly formed JSON string: ' + this.inspect());
509
+ },
510
+
511
+ include: function(pattern) {
512
+ return this.indexOf(pattern) > -1;
513
+ },
514
+
515
+ startsWith: function(pattern) {
516
+ return this.indexOf(pattern) === 0;
517
+ },
518
+
519
+ endsWith: function(pattern) {
520
+ var d = this.length - pattern.length;
521
+ return d >= 0 && this.lastIndexOf(pattern) === d;
522
+ },
523
+
524
+ empty: function() {
525
+ return this == '';
526
+ },
527
+
528
+ blank: function() {
529
+ return /^\s*$/.test(this);
530
+ },
531
+
532
+ interpolate: function(object, pattern) {
533
+ return new Template(this, pattern).evaluate(object);
534
+ }
535
+ });
536
+
537
+ if (Prototype.Browser.WebKit || Prototype.Browser.IE) Object.extend(String.prototype, {
538
+ escapeHTML: function() {
539
+ return this.replace(/&/g,'&amp;').replace(/</g,'&lt;').replace(/>/g,'&gt;');
540
+ },
541
+ unescapeHTML: function() {
542
+ return this.stripTags().replace(/&amp;/g,'&').replace(/&lt;/g,'<').replace(/&gt;/g,'>');
543
+ }
544
+ });
545
+
546
+ String.prototype.gsub.prepareReplacement = function(replacement) {
547
+ if (Object.isFunction(replacement)) return replacement;
548
+ var template = new Template(replacement);
549
+ return function(match) { return template.evaluate(match) };
550
+ };
551
+
552
+ String.prototype.parseQuery = String.prototype.toQueryParams;
553
+
554
+ Object.extend(String.prototype.escapeHTML, {
555
+ div: document.createElement('div'),
556
+ text: document.createTextNode('')
557
+ });
558
+
559
+ String.prototype.escapeHTML.div.appendChild(String.prototype.escapeHTML.text);
560
+
561
+ var Template = Class.create({
562
+ initialize: function(template, pattern) {
563
+ this.template = template.toString();
564
+ this.pattern = pattern || Template.Pattern;
565
+ },
566
+
567
+ evaluate: function(object) {
568
+ if (Object.isFunction(object.toTemplateReplacements))
569
+ object = object.toTemplateReplacements();
570
+
571
+ return this.template.gsub(this.pattern, function(match) {
572
+ if (object == null) return '';
573
+
574
+ var before = match[1] || '';
575
+ if (before == '\\') return match[2];
576
+
577
+ var ctx = object, expr = match[3];
578
+ var pattern = /^([^.[]+|\[((?:.*?[^\\])?)\])(\.|\[|$)/;
579
+ match = pattern.exec(expr);
580
+ if (match == null) return before;
581
+
582
+ while (match != null) {
583
+ var comp = match[1].startsWith('[') ? match[2].gsub('\\\\]', ']') : match[1];
584
+ ctx = ctx[comp];
585
+ if (null == ctx || '' == match[3]) break;
586
+ expr = expr.substring('[' == match[3] ? match[1].length : match[0].length);
587
+ match = pattern.exec(expr);
588
+ }
589
+
590
+ return before + String.interpret(ctx);
591
+ });
592
+ }
593
+ });
594
+ Template.Pattern = /(^|.|\r|\n)(#\{(.*?)\})/;
595
+
596
+ var $break = { };
597
+
598
+ var Enumerable = {
599
+ each: function(iterator, context) {
600
+ var index = 0;
601
+ try {
602
+ this._each(function(value) {
603
+ iterator.call(context, value, index++);
604
+ });
605
+ } catch (e) {
606
+ if (e != $break) throw e;
607
+ }
608
+ return this;
609
+ },
610
+
611
+ eachSlice: function(number, iterator, context) {
612
+ var index = -number, slices = [], array = this.toArray();
613
+ if (number < 1) return array;
614
+ while ((index += number) < array.length)
615
+ slices.push(array.slice(index, index+number));
616
+ return slices.collect(iterator, context);
617
+ },
618
+
619
+ all: function(iterator, context) {
620
+ iterator = iterator || Prototype.K;
621
+ var result = true;
622
+ this.each(function(value, index) {
623
+ result = result && !!iterator.call(context, value, index);
624
+ if (!result) throw $break;
625
+ });
626
+ return result;
627
+ },
628
+
629
+ any: function(iterator, context) {
630
+ iterator = iterator || Prototype.K;
631
+ var result = false;
632
+ this.each(function(value, index) {
633
+ if (result = !!iterator.call(context, value, index))
634
+ throw $break;
635
+ });
636
+ return result;
637
+ },
638
+
639
+ collect: function(iterator, context) {
640
+ iterator = iterator || Prototype.K;
641
+ var results = [];
642
+ this.each(function(value, index) {
643
+ results.push(iterator.call(context, value, index));
644
+ });
645
+ return results;
646
+ },
647
+
648
+ detect: function(iterator, context) {
649
+ var result;
650
+ this.each(function(value, index) {
651
+ if (iterator.call(context, value, index)) {
652
+ result = value;
653
+ throw $break;
654
+ }
655
+ });
656
+ return result;
657
+ },
658
+
659
+ findAll: function(iterator, context) {
660
+ var results = [];
661
+ this.each(function(value, index) {
662
+ if (iterator.call(context, value, index))
663
+ results.push(value);
664
+ });
665
+ return results;
666
+ },
667
+
668
+ grep: function(filter, iterator, context) {
669
+ iterator = iterator || Prototype.K;
670
+ var results = [];
671
+
672
+ if (Object.isString(filter))
673
+ filter = new RegExp(filter);
674
+
675
+ this.each(function(value, index) {
676
+ if (filter.match(value))
677
+ results.push(iterator.call(context, value, index));
678
+ });
679
+ return results;
680
+ },
681
+
682
+ include: function(object) {
683
+ if (Object.isFunction(this.indexOf))
684
+ if (this.indexOf(object) != -1) return true;
685
+
686
+ var found = false;
687
+ this.each(function(value) {
688
+ if (value == object) {
689
+ found = true;
690
+ throw $break;
691
+ }
692
+ });
693
+ return found;
694
+ },
695
+
696
+ inGroupsOf: function(number, fillWith) {
697
+ fillWith = Object.isUndefined(fillWith) ? null : fillWith;
698
+ return this.eachSlice(number, function(slice) {
699
+ while(slice.length < number) slice.push(fillWith);
700
+ return slice;
701
+ });
702
+ },
703
+
704
+ inject: function(memo, iterator, context) {
705
+ this.each(function(value, index) {
706
+ memo = iterator.call(context, memo, value, index);
707
+ });
708
+ return memo;
709
+ },
710
+
711
+ invoke: function(method) {
712
+ var args = $A(arguments).slice(1);
713
+ return this.map(function(value) {
714
+ return value[method].apply(value, args);
715
+ });
716
+ },
717
+
718
+ max: function(iterator, context) {
719
+ iterator = iterator || Prototype.K;
720
+ var result;
721
+ this.each(function(value, index) {
722
+ value = iterator.call(context, value, index);
723
+ if (result == null || value >= result)
724
+ result = value;
725
+ });
726
+ return result;
727
+ },
728
+
729
+ min: function(iterator, context) {
730
+ iterator = iterator || Prototype.K;
731
+ var result;
732
+ this.each(function(value, index) {
733
+ value = iterator.call(context, value, index);
734
+ if (result == null || value < result)
735
+ result = value;
736
+ });
737
+ return result;
738
+ },
739
+
740
+ partition: function(iterator, context) {
741
+ iterator = iterator || Prototype.K;
742
+ var trues = [], falses = [];
743
+ this.each(function(value, index) {
744
+ (iterator.call(context, value, index) ?
745
+ trues : falses).push(value);
746
+ });
747
+ return [trues, falses];
748
+ },
749
+
750
+ pluck: function(property) {
751
+ var results = [];
752
+ this.each(function(value) {
753
+ results.push(value[property]);
754
+ });
755
+ return results;
756
+ },
757
+
758
+ reject: function(iterator, context) {
759
+ var results = [];
760
+ this.each(function(value, index) {
761
+ if (!iterator.call(context, value, index))
762
+ results.push(value);
763
+ });
764
+ return results;
765
+ },
766
+
767
+ sortBy: function(iterator, context) {
768
+ return this.map(function(value, index) {
769
+ return {
770
+ value: value,
771
+ criteria: iterator.call(context, value, index)
772
+ };
773
+ }).sort(function(left, right) {
774
+ var a = left.criteria, b = right.criteria;
775
+ return a < b ? -1 : a > b ? 1 : 0;
776
+ }).pluck('value');
777
+ },
778
+
779
+ toArray: function() {
780
+ return this.map();
781
+ },
782
+
783
+ zip: function() {
784
+ var iterator = Prototype.K, args = $A(arguments);
785
+ if (Object.isFunction(args.last()))
786
+ iterator = args.pop();
787
+
788
+ var collections = [this].concat(args).map($A);
789
+ return this.map(function(value, index) {
790
+ return iterator(collections.pluck(index));
791
+ });
792
+ },
793
+
794
+ size: function() {
795
+ return this.toArray().length;
796
+ },
797
+
798
+ inspect: function() {
799
+ return '#<Enumerable:' + this.toArray().inspect() + '>';
800
+ }
801
+ };
802
+
803
+ Object.extend(Enumerable, {
804
+ map: Enumerable.collect,
805
+ find: Enumerable.detect,
806
+ select: Enumerable.findAll,
807
+ filter: Enumerable.findAll,
808
+ member: Enumerable.include,
809
+ entries: Enumerable.toArray,
810
+ every: Enumerable.all,
811
+ some: Enumerable.any
812
+ });
813
+ function $A(iterable) {
814
+ if (!iterable) return [];
815
+ if (iterable.toArray) return iterable.toArray();
816
+ var length = iterable.length || 0, results = new Array(length);
817
+ while (length--) results[length] = iterable[length];
818
+ return results;
819
+ }
820
+
821
+ if (Prototype.Browser.WebKit) {
822
+ $A = function(iterable) {
823
+ if (!iterable) return [];
824
+ // In Safari, only use the `toArray` method if it's not a NodeList.
825
+ // A NodeList is a function, has an function `item` property, and a numeric
826
+ // `length` property. Adapted from Google Doctype.
827
+ if (!(typeof iterable === 'function' && typeof iterable.length ===
828
+ 'number' && typeof iterable.item === 'function') && iterable.toArray)
829
+ return iterable.toArray();
830
+ var length = iterable.length || 0, results = new Array(length);
831
+ while (length--) results[length] = iterable[length];
832
+ return results;
833
+ };
834
+ }
835
+
836
+ Array.from = $A;
837
+
838
+ Object.extend(Array.prototype, Enumerable);
839
+
840
+ if (!Array.prototype._reverse) Array.prototype._reverse = Array.prototype.reverse;
841
+
842
+ Object.extend(Array.prototype, {
843
+ _each: function(iterator) {
844
+ for (var i = 0, length = this.length; i < length; i++)
845
+ iterator(this[i]);
846
+ },
847
+
848
+ clear: function() {
849
+ this.length = 0;
850
+ return this;
851
+ },
852
+
853
+ first: function() {
854
+ return this[0];
855
+ },
856
+
857
+ last: function() {
858
+ return this[this.length - 1];
859
+ },
860
+
861
+ compact: function() {
862
+ return this.select(function(value) {
863
+ return value != null;
864
+ });
865
+ },
866
+
867
+ flatten: function() {
868
+ return this.inject([], function(array, value) {
869
+ return array.concat(Object.isArray(value) ?
870
+ value.flatten() : [value]);
871
+ });
872
+ },
873
+
874
+ without: function() {
875
+ var values = $A(arguments);
876
+ return this.select(function(value) {
877
+ return !values.include(value);
878
+ });
879
+ },
880
+
881
+ reverse: function(inline) {
882
+ return (inline !== false ? this : this.toArray())._reverse();
883
+ },
884
+
885
+ reduce: function() {
886
+ return this.length > 1 ? this : this[0];
887
+ },
888
+
889
+ uniq: function(sorted) {
890
+ return this.inject([], function(array, value, index) {
891
+ if (0 == index || (sorted ? array.last() != value : !array.include(value)))
892
+ array.push(value);
893
+ return array;
894
+ });
895
+ },
896
+
897
+ intersect: function(array) {
898
+ return this.uniq().findAll(function(item) {
899
+ return array.detect(function(value) { return item === value });
900
+ });
901
+ },
902
+
903
+ clone: function() {
904
+ return [].concat(this);
905
+ },
906
+
907
+ size: function() {
908
+ return this.length;
909
+ },
910
+
911
+ inspect: function() {
912
+ return '[' + this.map(Object.inspect).join(', ') + ']';
913
+ },
914
+
915
+ toJSON: function() {
916
+ var results = [];
917
+ this.each(function(object) {
918
+ var value = Object.toJSON(object);
919
+ if (!Object.isUndefined(value)) results.push(value);
920
+ });
921
+ return '[' + results.join(', ') + ']';
922
+ }
923
+ });
924
+
925
+ // use native browser JS 1.6 implementation if available
926
+ if (Object.isFunction(Array.prototype.forEach))
927
+ Array.prototype._each = Array.prototype.forEach;
928
+
929
+ if (!Array.prototype.indexOf) Array.prototype.indexOf = function(item, i) {
930
+ i || (i = 0);
931
+ var length = this.length;
932
+ if (i < 0) i = length + i;
933
+ for (; i < length; i++)
934
+ if (this[i] === item) return i;
935
+ return -1;
936
+ };
937
+
938
+ if (!Array.prototype.lastIndexOf) Array.prototype.lastIndexOf = function(item, i) {
939
+ i = isNaN(i) ? this.length : (i < 0 ? this.length + i : i) + 1;
940
+ var n = this.slice(0, i).reverse().indexOf(item);
941
+ return (n < 0) ? n : i - n - 1;
942
+ };
943
+
944
+ Array.prototype.toArray = Array.prototype.clone;
945
+
946
+ function $w(string) {
947
+ if (!Object.isString(string)) return [];
948
+ string = string.strip();
949
+ return string ? string.split(/\s+/) : [];
950
+ }
951
+
952
+ if (Prototype.Browser.Opera){
953
+ Array.prototype.concat = function() {
954
+ var array = [];
955
+ for (var i = 0, length = this.length; i < length; i++) array.push(this[i]);
956
+ for (var i = 0, length = arguments.length; i < length; i++) {
957
+ if (Object.isArray(arguments[i])) {
958
+ for (var j = 0, arrayLength = arguments[i].length; j < arrayLength; j++)
959
+ array.push(arguments[i][j]);
960
+ } else {
961
+ array.push(arguments[i]);
962
+ }
963
+ }
964
+ return array;
965
+ };
966
+ }
967
+ Object.extend(Number.prototype, {
968
+ toColorPart: function() {
969
+ return this.toPaddedString(2, 16);
970
+ },
971
+
972
+ succ: function() {
973
+ return this + 1;
974
+ },
975
+
976
+ times: function(iterator, context) {
977
+ $R(0, this, true).each(iterator, context);
978
+ return this;
979
+ },
980
+
981
+ toPaddedString: function(length, radix) {
982
+ var string = this.toString(radix || 10);
983
+ return '0'.times(length - string.length) + string;
984
+ },
985
+
986
+ toJSON: function() {
987
+ return isFinite(this) ? this.toString() : 'null';
988
+ }
989
+ });
990
+
991
+ $w('abs round ceil floor').each(function(method){
992
+ Number.prototype[method] = Math[method].methodize();
993
+ });
994
+ function $H(object) {
995
+ return new Hash(object);
996
+ };
997
+
998
+ var Hash = Class.create(Enumerable, (function() {
999
+
1000
+ function toQueryPair(key, value) {
1001
+ if (Object.isUndefined(value)) return key;
1002
+ return key + '=' + encodeURIComponent(String.interpret(value));
1003
+ }
1004
+
1005
+ return {
1006
+ initialize: function(object) {
1007
+ this._object = Object.isHash(object) ? object.toObject() : Object.clone(object);
1008
+ },
1009
+
1010
+ _each: function(iterator) {
1011
+ for (var key in this._object) {
1012
+ var value = this._object[key], pair = [key, value];
1013
+ pair.key = key;
1014
+ pair.value = value;
1015
+ iterator(pair);
1016
+ }
1017
+ },
1018
+
1019
+ set: function(key, value) {
1020
+ return this._object[key] = value;
1021
+ },
1022
+
1023
+ get: function(key) {
1024
+ // simulating poorly supported hasOwnProperty
1025
+ if (this._object[key] !== Object.prototype[key])
1026
+ return this._object[key];
1027
+ },
1028
+
1029
+ unset: function(key) {
1030
+ var value = this._object[key];
1031
+ delete this._object[key];
1032
+ return value;
1033
+ },
1034
+
1035
+ toObject: function() {
1036
+ return Object.clone(this._object);
1037
+ },
1038
+
1039
+ keys: function() {
1040
+ return this.pluck('key');
1041
+ },
1042
+
1043
+ values: function() {
1044
+ return this.pluck('value');
1045
+ },
1046
+
1047
+ index: function(value) {
1048
+ var match = this.detect(function(pair) {
1049
+ return pair.value === value;
1050
+ });
1051
+ return match && match.key;
1052
+ },
1053
+
1054
+ merge: function(object) {
1055
+ return this.clone().update(object);
1056
+ },
1057
+
1058
+ update: function(object) {
1059
+ return new Hash(object).inject(this, function(result, pair) {
1060
+ result.set(pair.key, pair.value);
1061
+ return result;
1062
+ });
1063
+ },
1064
+
1065
+ toQueryString: function() {
1066
+ return this.inject([], function(results, pair) {
1067
+ var key = encodeURIComponent(pair.key), values = pair.value;
1068
+
1069
+ if (values && typeof values == 'object') {
1070
+ if (Object.isArray(values))
1071
+ return results.concat(values.map(toQueryPair.curry(key)));
1072
+ } else results.push(toQueryPair(key, values));
1073
+ return results;
1074
+ }).join('&');
1075
+ },
1076
+
1077
+ inspect: function() {
1078
+ return '#<Hash:{' + this.map(function(pair) {
1079
+ return pair.map(Object.inspect).join(': ');
1080
+ }).join(', ') + '}>';
1081
+ },
1082
+
1083
+ toJSON: function() {
1084
+ return Object.toJSON(this.toObject());
1085
+ },
1086
+
1087
+ clone: function() {
1088
+ return new Hash(this);
1089
+ }
1090
+ }
1091
+ })());
1092
+
1093
+ Hash.prototype.toTemplateReplacements = Hash.prototype.toObject;
1094
+ Hash.from = $H;
1095
+ var ObjectRange = Class.create(Enumerable, {
1096
+ initialize: function(start, end, exclusive) {
1097
+ this.start = start;
1098
+ this.end = end;
1099
+ this.exclusive = exclusive;
1100
+ },
1101
+
1102
+ _each: function(iterator) {
1103
+ var value = this.start;
1104
+ while (this.include(value)) {
1105
+ iterator(value);
1106
+ value = value.succ();
1107
+ }
1108
+ },
1109
+
1110
+ include: function(value) {
1111
+ if (value < this.start)
1112
+ return false;
1113
+ if (this.exclusive)
1114
+ return value < this.end;
1115
+ return value <= this.end;
1116
+ }
1117
+ });
1118
+
1119
+ var $R = function(start, end, exclusive) {
1120
+ return new ObjectRange(start, end, exclusive);
1121
+ };
1122
+
1123
+ var Ajax = {
1124
+ getTransport: function() {
1125
+ return Try.these(
1126
+ function() {return new XMLHttpRequest()},
1127
+ function() {return new ActiveXObject('Msxml2.XMLHTTP')},
1128
+ function() {return new ActiveXObject('Microsoft.XMLHTTP')}
1129
+ ) || false;
1130
+ },
1131
+
1132
+ activeRequestCount: 0
1133
+ };
1134
+
1135
+ Ajax.Responders = {
1136
+ responders: [],
1137
+
1138
+ _each: function(iterator) {
1139
+ this.responders._each(iterator);
1140
+ },
1141
+
1142
+ register: function(responder) {
1143
+ if (!this.include(responder))
1144
+ this.responders.push(responder);
1145
+ },
1146
+
1147
+ unregister: function(responder) {
1148
+ this.responders = this.responders.without(responder);
1149
+ },
1150
+
1151
+ dispatch: function(callback, request, transport, json) {
1152
+ this.each(function(responder) {
1153
+ if (Object.isFunction(responder[callback])) {
1154
+ try {
1155
+ responder[callback].apply(responder, [request, transport, json]);
1156
+ } catch (e) { }
1157
+ }
1158
+ });
1159
+ }
1160
+ };
1161
+
1162
+ Object.extend(Ajax.Responders, Enumerable);
1163
+
1164
+ Ajax.Responders.register({
1165
+ onCreate: function() { Ajax.activeRequestCount++ },
1166
+ onComplete: function() { Ajax.activeRequestCount-- }
1167
+ });
1168
+
1169
+ Ajax.Base = Class.create({
1170
+ initialize: function(options) {
1171
+ this.options = {
1172
+ method: 'post',
1173
+ asynchronous: true,
1174
+ contentType: 'application/x-www-form-urlencoded',
1175
+ encoding: 'UTF-8',
1176
+ parameters: '',
1177
+ evalJSON: true,
1178
+ evalJS: true
1179
+ };
1180
+ Object.extend(this.options, options || { });
1181
+
1182
+ this.options.method = this.options.method.toLowerCase();
1183
+
1184
+ if (Object.isString(this.options.parameters))
1185
+ this.options.parameters = this.options.parameters.toQueryParams();
1186
+ else if (Object.isHash(this.options.parameters))
1187
+ this.options.parameters = this.options.parameters.toObject();
1188
+ }
1189
+ });
1190
+
1191
+ Ajax.Request = Class.create(Ajax.Base, {
1192
+ _complete: false,
1193
+
1194
+ initialize: function($super, url, options) {
1195
+ $super(options);
1196
+ this.transport = Ajax.getTransport();
1197
+ this.request(url);
1198
+ },
1199
+
1200
+ request: function(url) {
1201
+ this.url = url;
1202
+ this.method = this.options.method;
1203
+ var params = Object.clone(this.options.parameters);
1204
+
1205
+ if (!['get', 'post'].include(this.method)) {
1206
+ // simulate other verbs over post
1207
+ params['_method'] = this.method;
1208
+ this.method = 'post';
1209
+ }
1210
+
1211
+ this.parameters = params;
1212
+
1213
+ if (params = Object.toQueryString(params)) {
1214
+ // when GET, append parameters to URL
1215
+ if (this.method == 'get')
1216
+ this.url += (this.url.include('?') ? '&' : '?') + params;
1217
+ else if (/Konqueror|Safari|KHTML/.test(navigator.userAgent))
1218
+ params += '&_=';
1219
+ }
1220
+
1221
+ try {
1222
+ var response = new Ajax.Response(this);
1223
+ if (this.options.onCreate) this.options.onCreate(response);
1224
+ Ajax.Responders.dispatch('onCreate', this, response);
1225
+
1226
+ this.transport.open(this.method.toUpperCase(), this.url,
1227
+ this.options.asynchronous);
1228
+
1229
+ if (this.options.asynchronous) this.respondToReadyState.bind(this).defer(1);
1230
+
1231
+ this.transport.onreadystatechange = this.onStateChange.bind(this);
1232
+ this.setRequestHeaders();
1233
+
1234
+ this.body = this.method == 'post' ? (this.options.postBody || params) : null;
1235
+ this.transport.send(this.body);
1236
+
1237
+ /* Force Firefox to handle ready state 4 for synchronous requests */
1238
+ if (!this.options.asynchronous && this.transport.overrideMimeType)
1239
+ this.onStateChange();
1240
+
1241
+ }
1242
+ catch (e) {
1243
+ this.dispatchException(e);
1244
+ }
1245
+ },
1246
+
1247
+ onStateChange: function() {
1248
+ var readyState = this.transport.readyState;
1249
+ if (readyState > 1 && !((readyState == 4) && this._complete))
1250
+ this.respondToReadyState(this.transport.readyState);
1251
+ },
1252
+
1253
+ setRequestHeaders: function() {
1254
+ var headers = {
1255
+ 'X-Requested-With': 'XMLHttpRequest',
1256
+ 'X-Prototype-Version': Prototype.Version,
1257
+ 'Accept': 'text/javascript, text/html, application/xml, text/xml, */*'
1258
+ };
1259
+
1260
+ if (this.method == 'post') {
1261
+ headers['Content-type'] = this.options.contentType +
1262
+ (this.options.encoding ? '; charset=' + this.options.encoding : '');
1263
+
1264
+ /* Force "Connection: close" for older Mozilla browsers to work
1265
+ * around a bug where XMLHttpRequest sends an incorrect
1266
+ * Content-length header. See Mozilla Bugzilla #246651.
1267
+ */
1268
+ if (this.transport.overrideMimeType &&
1269
+ (navigator.userAgent.match(/Gecko\/(\d{4})/) || [0,2005])[1] < 2005)
1270
+ headers['Connection'] = 'close';
1271
+ }
1272
+
1273
+ // user-defined headers
1274
+ if (typeof this.options.requestHeaders == 'object') {
1275
+ var extras = this.options.requestHeaders;
1276
+
1277
+ if (Object.isFunction(extras.push))
1278
+ for (var i = 0, length = extras.length; i < length; i += 2)
1279
+ headers[extras[i]] = extras[i+1];
1280
+ else
1281
+ $H(extras).each(function(pair) { headers[pair.key] = pair.value });
1282
+ }
1283
+
1284
+ for (var name in headers)
1285
+ this.transport.setRequestHeader(name, headers[name]);
1286
+ },
1287
+
1288
+ success: function() {
1289
+ var status = this.getStatus();
1290
+ return !status || (status >= 200 && status < 300);
1291
+ },
1292
+
1293
+ getStatus: function() {
1294
+ try {
1295
+ return this.transport.status || 0;
1296
+ } catch (e) { return 0 }
1297
+ },
1298
+
1299
+ respondToReadyState: function(readyState) {
1300
+ var state = Ajax.Request.Events[readyState], response = new Ajax.Response(this);
1301
+
1302
+ if (state == 'Complete') {
1303
+ try {
1304
+ this._complete = true;
1305
+ (this.options['on' + response.status]
1306
+ || this.options['on' + (this.success() ? 'Success' : 'Failure')]
1307
+ || Prototype.emptyFunction)(response, response.headerJSON);
1308
+ } catch (e) {
1309
+ this.dispatchException(e);
1310
+ }
1311
+
1312
+ var contentType = response.getHeader('Content-type');
1313
+ if (this.options.evalJS == 'force'
1314
+ || (this.options.evalJS && this.isSameOrigin() && contentType
1315
+ && contentType.match(/^\s*(text|application)\/(x-)?(java|ecma)script(;.*)?\s*$/i)))
1316
+ this.evalResponse();
1317
+ }
1318
+
1319
+ try {
1320
+ (this.options['on' + state] || Prototype.emptyFunction)(response, response.headerJSON);
1321
+ Ajax.Responders.dispatch('on' + state, this, response, response.headerJSON);
1322
+ } catch (e) {
1323
+ this.dispatchException(e);
1324
+ }
1325
+
1326
+ if (state == 'Complete') {
1327
+ // avoid memory leak in MSIE: clean up
1328
+ this.transport.onreadystatechange = Prototype.emptyFunction;
1329
+ }
1330
+ },
1331
+
1332
+ isSameOrigin: function() {
1333
+ var m = this.url.match(/^\s*https?:\/\/[^\/]*/);
1334
+ return !m || (m[0] == '#{protocol}//#{domain}#{port}'.interpolate({
1335
+ protocol: location.protocol,
1336
+ domain: document.domain,
1337
+ port: location.port ? ':' + location.port : ''
1338
+ }));
1339
+ },
1340
+
1341
+ getHeader: function(name) {
1342
+ try {
1343
+ return this.transport.getResponseHeader(name) || null;
1344
+ } catch (e) { return null }
1345
+ },
1346
+
1347
+ evalResponse: function() {
1348
+ try {
1349
+ return eval((this.transport.responseText || '').unfilterJSON());
1350
+ } catch (e) {
1351
+ this.dispatchException(e);
1352
+ }
1353
+ },
1354
+
1355
+ dispatchException: function(exception) {
1356
+ (this.options.onException || Prototype.emptyFunction)(this, exception);
1357
+ Ajax.Responders.dispatch('onException', this, exception);
1358
+ }
1359
+ });
1360
+
1361
+ Ajax.Request.Events =
1362
+ ['Uninitialized', 'Loading', 'Loaded', 'Interactive', 'Complete'];
1363
+
1364
+ Ajax.Response = Class.create({
1365
+ initialize: function(request){
1366
+ this.request = request;
1367
+ var transport = this.transport = request.transport,
1368
+ readyState = this.readyState = transport.readyState;
1369
+
1370
+ if((readyState > 2 && !Prototype.Browser.IE) || readyState == 4) {
1371
+ this.status = this.getStatus();
1372
+ this.statusText = this.getStatusText();
1373
+ this.responseText = String.interpret(transport.responseText);
1374
+ this.headerJSON = this._getHeaderJSON();
1375
+ }
1376
+
1377
+ if(readyState == 4) {
1378
+ var xml = transport.responseXML;
1379
+ this.responseXML = Object.isUndefined(xml) ? null : xml;
1380
+ this.responseJSON = this._getResponseJSON();
1381
+ }
1382
+ },
1383
+
1384
+ status: 0,
1385
+ statusText: '',
1386
+
1387
+ getStatus: Ajax.Request.prototype.getStatus,
1388
+
1389
+ getStatusText: function() {
1390
+ try {
1391
+ return this.transport.statusText || '';
1392
+ } catch (e) { return '' }
1393
+ },
1394
+
1395
+ getHeader: Ajax.Request.prototype.getHeader,
1396
+
1397
+ getAllHeaders: function() {
1398
+ try {
1399
+ return this.getAllResponseHeaders();
1400
+ } catch (e) { return null }
1401
+ },
1402
+
1403
+ getResponseHeader: function(name) {
1404
+ return this.transport.getResponseHeader(name);
1405
+ },
1406
+
1407
+ getAllResponseHeaders: function() {
1408
+ return this.transport.getAllResponseHeaders();
1409
+ },
1410
+
1411
+ _getHeaderJSON: function() {
1412
+ var json = this.getHeader('X-JSON');
1413
+ if (!json) return null;
1414
+ json = decodeURIComponent(escape(json));
1415
+ try {
1416
+ return json.evalJSON(this.request.options.sanitizeJSON ||
1417
+ !this.request.isSameOrigin());
1418
+ } catch (e) {
1419
+ this.request.dispatchException(e);
1420
+ }
1421
+ },
1422
+
1423
+ _getResponseJSON: function() {
1424
+ var options = this.request.options;
1425
+ if (!options.evalJSON || (options.evalJSON != 'force' &&
1426
+ !(this.getHeader('Content-type') || '').include('application/json')) ||
1427
+ this.responseText.blank())
1428
+ return null;
1429
+ try {
1430
+ return this.responseText.evalJSON(options.sanitizeJSON ||
1431
+ !this.request.isSameOrigin());
1432
+ } catch (e) {
1433
+ this.request.dispatchException(e);
1434
+ }
1435
+ }
1436
+ });
1437
+
1438
+ Ajax.Updater = Class.create(Ajax.Request, {
1439
+ initialize: function($super, container, url, options) {
1440
+ this.container = {
1441
+ success: (container.success || container),
1442
+ failure: (container.failure || (container.success ? null : container))
1443
+ };
1444
+
1445
+ options = Object.clone(options);
1446
+ var onComplete = options.onComplete;
1447
+ options.onComplete = (function(response, json) {
1448
+ this.updateContent(response.responseText);
1449
+ if (Object.isFunction(onComplete)) onComplete(response, json);
1450
+ }).bind(this);
1451
+
1452
+ $super(url, options);
1453
+ },
1454
+
1455
+ updateContent: function(responseText) {
1456
+ var receiver = this.container[this.success() ? 'success' : 'failure'],
1457
+ options = this.options;
1458
+
1459
+ if (!options.evalScripts) responseText = responseText.stripScripts();
1460
+
1461
+ if (receiver = $(receiver)) {
1462
+ if (options.insertion) {
1463
+ if (Object.isString(options.insertion)) {
1464
+ var insertion = { }; insertion[options.insertion] = responseText;
1465
+ receiver.insert(insertion);
1466
+ }
1467
+ else options.insertion(receiver, responseText);
1468
+ }
1469
+ else receiver.update(responseText);
1470
+ }
1471
+ }
1472
+ });
1473
+
1474
+ Ajax.PeriodicalUpdater = Class.create(Ajax.Base, {
1475
+ initialize: function($super, container, url, options) {
1476
+ $super(options);
1477
+ this.onComplete = this.options.onComplete;
1478
+
1479
+ this.frequency = (this.options.frequency || 2);
1480
+ this.decay = (this.options.decay || 1);
1481
+
1482
+ this.updater = { };
1483
+ this.container = container;
1484
+ this.url = url;
1485
+
1486
+ this.start();
1487
+ },
1488
+
1489
+ start: function() {
1490
+ this.options.onComplete = this.updateComplete.bind(this);
1491
+ this.onTimerEvent();
1492
+ },
1493
+
1494
+ stop: function() {
1495
+ this.updater.options.onComplete = undefined;
1496
+ clearTimeout(this.timer);
1497
+ (this.onComplete || Prototype.emptyFunction).apply(this, arguments);
1498
+ },
1499
+
1500
+ updateComplete: function(response) {
1501
+ if (this.options.decay) {
1502
+ this.decay = (response.responseText == this.lastText ?
1503
+ this.decay * this.options.decay : 1);
1504
+
1505
+ this.lastText = response.responseText;
1506
+ }
1507
+ this.timer = this.onTimerEvent.bind(this).delay(this.decay * this.frequency);
1508
+ },
1509
+
1510
+ onTimerEvent: function() {
1511
+ this.updater = new Ajax.Updater(this.container, this.url, this.options);
1512
+ }
1513
+ });
1514
+ function $(element) {
1515
+ if (arguments.length > 1) {
1516
+ for (var i = 0, elements = [], length = arguments.length; i < length; i++)
1517
+ elements.push($(arguments[i]));
1518
+ return elements;
1519
+ }
1520
+ if (Object.isString(element))
1521
+ element = document.getElementById(element);
1522
+ return Element.extend(element);
1523
+ }
1524
+
1525
+ if (Prototype.BrowserFeatures.XPath) {
1526
+ document._getElementsByXPath = function(expression, parentElement) {
1527
+ var results = [];
1528
+ var query = document.evaluate(expression, $(parentElement) || document,
1529
+ null, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);
1530
+ for (var i = 0, length = query.snapshotLength; i < length; i++)
1531
+ results.push(Element.extend(query.snapshotItem(i)));
1532
+ return results;
1533
+ };
1534
+ }
1535
+
1536
+ /*--------------------------------------------------------------------------*/
1537
+
1538
+ if (!window.Node) var Node = { };
1539
+
1540
+ if (!Node.ELEMENT_NODE) {
1541
+ // DOM level 2 ECMAScript Language Binding
1542
+ Object.extend(Node, {
1543
+ ELEMENT_NODE: 1,
1544
+ ATTRIBUTE_NODE: 2,
1545
+ TEXT_NODE: 3,
1546
+ CDATA_SECTION_NODE: 4,
1547
+ ENTITY_REFERENCE_NODE: 5,
1548
+ ENTITY_NODE: 6,
1549
+ PROCESSING_INSTRUCTION_NODE: 7,
1550
+ COMMENT_NODE: 8,
1551
+ DOCUMENT_NODE: 9,
1552
+ DOCUMENT_TYPE_NODE: 10,
1553
+ DOCUMENT_FRAGMENT_NODE: 11,
1554
+ NOTATION_NODE: 12
1555
+ });
1556
+ }
1557
+
1558
+ (function() {
1559
+ var element = this.Element;
1560
+ this.Element = function(tagName, attributes) {
1561
+ attributes = attributes || { };
1562
+ tagName = tagName.toLowerCase();
1563
+ var cache = Element.cache;
1564
+ if (Prototype.Browser.IE && attributes.name) {
1565
+ tagName = '<' + tagName + ' name="' + attributes.name + '">';
1566
+ delete attributes.name;
1567
+ return Element.writeAttribute(document.createElement(tagName), attributes);
1568
+ }
1569
+ if (!cache[tagName]) cache[tagName] = Element.extend(document.createElement(tagName));
1570
+ return Element.writeAttribute(cache[tagName].cloneNode(false), attributes);
1571
+ };
1572
+ Object.extend(this.Element, element || { });
1573
+ if (element) this.Element.prototype = element.prototype;
1574
+ }).call(window);
1575
+
1576
+ Element.cache = { };
1577
+
1578
+ Element.Methods = {
1579
+ visible: function(element) {
1580
+ return $(element).style.display != 'none';
1581
+ },
1582
+
1583
+ toggle: function(element) {
1584
+ element = $(element);
1585
+ Element[Element.visible(element) ? 'hide' : 'show'](element);
1586
+ return element;
1587
+ },
1588
+
1589
+ hide: function(element) {
1590
+ element = $(element);
1591
+ element.style.display = 'none';
1592
+ return element;
1593
+ },
1594
+
1595
+ show: function(element) {
1596
+ element = $(element);
1597
+ element.style.display = '';
1598
+ return element;
1599
+ },
1600
+
1601
+ remove: function(element) {
1602
+ element = $(element);
1603
+ element.parentNode.removeChild(element);
1604
+ return element;
1605
+ },
1606
+
1607
+ update: function(element, content) {
1608
+ element = $(element);
1609
+ if (content && content.toElement) content = content.toElement();
1610
+ if (Object.isElement(content)) return element.update().insert(content);
1611
+ content = Object.toHTML(content);
1612
+ element.innerHTML = content.stripScripts();
1613
+ content.evalScripts.bind(content).defer();
1614
+ return element;
1615
+ },
1616
+
1617
+ replace: function(element, content) {
1618
+ element = $(element);
1619
+ if (content && content.toElement) content = content.toElement();
1620
+ else if (!Object.isElement(content)) {
1621
+ content = Object.toHTML(content);
1622
+ var range = element.ownerDocument.createRange();
1623
+ range.selectNode(element);
1624
+ content.evalScripts.bind(content).defer();
1625
+ content = range.createContextualFragment(content.stripScripts());
1626
+ }
1627
+ element.parentNode.replaceChild(content, element);
1628
+ return element;
1629
+ },
1630
+
1631
+ insert: function(element, insertions) {
1632
+ element = $(element);
1633
+
1634
+ if (Object.isString(insertions) || Object.isNumber(insertions) ||
1635
+ Object.isElement(insertions) || (insertions && (insertions.toElement || insertions.toHTML)))
1636
+ insertions = {bottom:insertions};
1637
+
1638
+ var content, insert, tagName, childNodes;
1639
+
1640
+ for (var position in insertions) {
1641
+ content = insertions[position];
1642
+ position = position.toLowerCase();
1643
+ insert = Element._insertionTranslations[position];
1644
+
1645
+ if (content && content.toElement) content = content.toElement();
1646
+ if (Object.isElement(content)) {
1647
+ insert(element, content);
1648
+ continue;
1649
+ }
1650
+
1651
+ content = Object.toHTML(content);
1652
+
1653
+ tagName = ((position == 'before' || position == 'after')
1654
+ ? element.parentNode : element).tagName.toUpperCase();
1655
+
1656
+ childNodes = Element._getContentFromAnonymousElement(tagName, content.stripScripts());
1657
+
1658
+ if (position == 'top' || position == 'after') childNodes.reverse();
1659
+ childNodes.each(insert.curry(element));
1660
+
1661
+ content.evalScripts.bind(content).defer();
1662
+ }
1663
+
1664
+ return element;
1665
+ },
1666
+
1667
+ wrap: function(element, wrapper, attributes) {
1668
+ element = $(element);
1669
+ if (Object.isElement(wrapper))
1670
+ $(wrapper).writeAttribute(attributes || { });
1671
+ else if (Object.isString(wrapper)) wrapper = new Element(wrapper, attributes);
1672
+ else wrapper = new Element('div', wrapper);
1673
+ if (element.parentNode)
1674
+ element.parentNode.replaceChild(wrapper, element);
1675
+ wrapper.appendChild(element);
1676
+ return wrapper;
1677
+ },
1678
+
1679
+ inspect: function(element) {
1680
+ element = $(element);
1681
+ var result = '<' + element.tagName.toLowerCase();
1682
+ $H({'id': 'id', 'className': 'class'}).each(function(pair) {
1683
+ var property = pair.first(), attribute = pair.last();
1684
+ var value = (element[property] || '').toString();
1685
+ if (value) result += ' ' + attribute + '=' + value.inspect(true);
1686
+ });
1687
+ return result + '>';
1688
+ },
1689
+
1690
+ recursivelyCollect: function(element, property) {
1691
+ element = $(element);
1692
+ var elements = [];
1693
+ while (element = element[property])
1694
+ if (element.nodeType == 1)
1695
+ elements.push(Element.extend(element));
1696
+ return elements;
1697
+ },
1698
+
1699
+ ancestors: function(element) {
1700
+ return $(element).recursivelyCollect('parentNode');
1701
+ },
1702
+
1703
+ descendants: function(element) {
1704
+ return $(element).select("*");
1705
+ },
1706
+
1707
+ firstDescendant: function(element) {
1708
+ element = $(element).firstChild;
1709
+ while (element && element.nodeType != 1) element = element.nextSibling;
1710
+ return $(element);
1711
+ },
1712
+
1713
+ immediateDescendants: function(element) {
1714
+ if (!(element = $(element).firstChild)) return [];
1715
+ while (element && element.nodeType != 1) element = element.nextSibling;
1716
+ if (element) return [element].concat($(element).nextSiblings());
1717
+ return [];
1718
+ },
1719
+
1720
+ previousSiblings: function(element) {
1721
+ return $(element).recursivelyCollect('previousSibling');
1722
+ },
1723
+
1724
+ nextSiblings: function(element) {
1725
+ return $(element).recursivelyCollect('nextSibling');
1726
+ },
1727
+
1728
+ siblings: function(element) {
1729
+ element = $(element);
1730
+ return element.previousSiblings().reverse().concat(element.nextSiblings());
1731
+ },
1732
+
1733
+ match: function(element, selector) {
1734
+ if (Object.isString(selector))
1735
+ selector = new Selector(selector);
1736
+ return selector.match($(element));
1737
+ },
1738
+
1739
+ up: function(element, expression, index) {
1740
+ element = $(element);
1741
+ if (arguments.length == 1) return $(element.parentNode);
1742
+ var ancestors = element.ancestors();
1743
+ return Object.isNumber(expression) ? ancestors[expression] :
1744
+ Selector.findElement(ancestors, expression, index);
1745
+ },
1746
+
1747
+ down: function(element, expression, index) {
1748
+ element = $(element);
1749
+ if (arguments.length == 1) return element.firstDescendant();
1750
+ return Object.isNumber(expression) ? element.descendants()[expression] :
1751
+ Element.select(element, expression)[index || 0];
1752
+ },
1753
+
1754
+ previous: function(element, expression, index) {
1755
+ element = $(element);
1756
+ if (arguments.length == 1) return $(Selector.handlers.previousElementSibling(element));
1757
+ var previousSiblings = element.previousSiblings();
1758
+ return Object.isNumber(expression) ? previousSiblings[expression] :
1759
+ Selector.findElement(previousSiblings, expression, index);
1760
+ },
1761
+
1762
+ next: function(element, expression, index) {
1763
+ element = $(element);
1764
+ if (arguments.length == 1) return $(Selector.handlers.nextElementSibling(element));
1765
+ var nextSiblings = element.nextSiblings();
1766
+ return Object.isNumber(expression) ? nextSiblings[expression] :
1767
+ Selector.findElement(nextSiblings, expression, index);
1768
+ },
1769
+
1770
+ select: function() {
1771
+ var args = $A(arguments), element = $(args.shift());
1772
+ return Selector.findChildElements(element, args);
1773
+ },
1774
+
1775
+ adjacent: function() {
1776
+ var args = $A(arguments), element = $(args.shift());
1777
+ return Selector.findChildElements(element.parentNode, args).without(element);
1778
+ },
1779
+
1780
+ identify: function(element) {
1781
+ element = $(element);
1782
+ var id = element.readAttribute('id'), self = arguments.callee;
1783
+ if (id) return id;
1784
+ do { id = 'anonymous_element_' + self.counter++ } while ($(id));
1785
+ element.writeAttribute('id', id);
1786
+ return id;
1787
+ },
1788
+
1789
+ readAttribute: function(element, name) {
1790
+ element = $(element);
1791
+ if (Prototype.Browser.IE) {
1792
+ var t = Element._attributeTranslations.read;
1793
+ if (t.values[name]) return t.values[name](element, name);
1794
+ if (t.names[name]) name = t.names[name];
1795
+ if (name.include(':')) {
1796
+ return (!element.attributes || !element.attributes[name]) ? null :
1797
+ element.attributes[name].value;
1798
+ }
1799
+ }
1800
+ return element.getAttribute(name);
1801
+ },
1802
+
1803
+ writeAttribute: function(element, name, value) {
1804
+ element = $(element);
1805
+ var attributes = { }, t = Element._attributeTranslations.write;
1806
+
1807
+ if (typeof name == 'object') attributes = name;
1808
+ else attributes[name] = Object.isUndefined(value) ? true : value;
1809
+
1810
+ for (var attr in attributes) {
1811
+ name = t.names[attr] || attr;
1812
+ value = attributes[attr];
1813
+ if (t.values[attr]) name = t.values[attr](element, value);
1814
+ if (value === false || value === null)
1815
+ element.removeAttribute(name);
1816
+ else if (value === true)
1817
+ element.setAttribute(name, name);
1818
+ else element.setAttribute(name, value);
1819
+ }
1820
+ return element;
1821
+ },
1822
+
1823
+ getHeight: function(element) {
1824
+ return $(element).getDimensions().height;
1825
+ },
1826
+
1827
+ getWidth: function(element) {
1828
+ return $(element).getDimensions().width;
1829
+ },
1830
+
1831
+ classNames: function(element) {
1832
+ return new Element.ClassNames(element);
1833
+ },
1834
+
1835
+ hasClassName: function(element, className) {
1836
+ if (!(element = $(element))) return;
1837
+ var elementClassName = element.className;
1838
+ return (elementClassName.length > 0 && (elementClassName == className ||
1839
+ new RegExp("(^|\\s)" + className + "(\\s|$)").test(elementClassName)));
1840
+ },
1841
+
1842
+ addClassName: function(element, className) {
1843
+ if (!(element = $(element))) return;
1844
+ if (!element.hasClassName(className))
1845
+ element.className += (element.className ? ' ' : '') + className;
1846
+ return element;
1847
+ },
1848
+
1849
+ removeClassName: function(element, className) {
1850
+ if (!(element = $(element))) return;
1851
+ element.className = element.className.replace(
1852
+ new RegExp("(^|\\s+)" + className + "(\\s+|$)"), ' ').strip();
1853
+ return element;
1854
+ },
1855
+
1856
+ toggleClassName: function(element, className) {
1857
+ if (!(element = $(element))) return;
1858
+ return element[element.hasClassName(className) ?
1859
+ 'removeClassName' : 'addClassName'](className);
1860
+ },
1861
+
1862
+ // removes whitespace-only text node children
1863
+ cleanWhitespace: function(element) {
1864
+ element = $(element);
1865
+ var node = element.firstChild;
1866
+ while (node) {
1867
+ var nextNode = node.nextSibling;
1868
+ if (node.nodeType == 3 && !/\S/.test(node.nodeValue))
1869
+ element.removeChild(node);
1870
+ node = nextNode;
1871
+ }
1872
+ return element;
1873
+ },
1874
+
1875
+ empty: function(element) {
1876
+ return $(element).innerHTML.blank();
1877
+ },
1878
+
1879
+ descendantOf: function(element, ancestor) {
1880
+ element = $(element), ancestor = $(ancestor);
1881
+
1882
+ if (element.compareDocumentPosition)
1883
+ return (element.compareDocumentPosition(ancestor) & 8) === 8;
1884
+
1885
+ if (ancestor.contains)
1886
+ return ancestor.contains(element) && ancestor !== element;
1887
+
1888
+ while (element = element.parentNode)
1889
+ if (element == ancestor) return true;
1890
+
1891
+ return false;
1892
+ },
1893
+
1894
+ scrollTo: function(element) {
1895
+ element = $(element);
1896
+ var pos = element.cumulativeOffset();
1897
+ window.scrollTo(pos[0], pos[1]);
1898
+ return element;
1899
+ },
1900
+
1901
+ getStyle: function(element, style) {
1902
+ element = $(element);
1903
+ style = style == 'float' ? 'cssFloat' : style.camelize();
1904
+ var value = element.style[style];
1905
+ if (!value || value == 'auto') {
1906
+ var css = document.defaultView.getComputedStyle(element, null);
1907
+ value = css ? css[style] : null;
1908
+ }
1909
+ if (style == 'opacity') return value ? parseFloat(value) : 1.0;
1910
+ return value == 'auto' ? null : value;
1911
+ },
1912
+
1913
+ getOpacity: function(element) {
1914
+ return $(element).getStyle('opacity');
1915
+ },
1916
+
1917
+ setStyle: function(element, styles) {
1918
+ element = $(element);
1919
+ var elementStyle = element.style, match;
1920
+ if (Object.isString(styles)) {
1921
+ element.style.cssText += ';' + styles;
1922
+ return styles.include('opacity') ?
1923
+ element.setOpacity(styles.match(/opacity:\s*(\d?\.?\d*)/)[1]) : element;
1924
+ }
1925
+ for (var property in styles)
1926
+ if (property == 'opacity') element.setOpacity(styles[property]);
1927
+ else
1928
+ elementStyle[(property == 'float' || property == 'cssFloat') ?
1929
+ (Object.isUndefined(elementStyle.styleFloat) ? 'cssFloat' : 'styleFloat') :
1930
+ property] = styles[property];
1931
+
1932
+ return element;
1933
+ },
1934
+
1935
+ setOpacity: function(element, value) {
1936
+ element = $(element);
1937
+ element.style.opacity = (value == 1 || value === '') ? '' :
1938
+ (value < 0.00001) ? 0 : value;
1939
+ return element;
1940
+ },
1941
+
1942
+ getDimensions: function(element) {
1943
+ element = $(element);
1944
+ var display = element.getStyle('display');
1945
+ if (display != 'none' && display != null) // Safari bug
1946
+ return {width: element.offsetWidth, height: element.offsetHeight};
1947
+
1948
+ // All *Width and *Height properties give 0 on elements with display none,
1949
+ // so enable the element temporarily
1950
+ var els = element.style;
1951
+ var originalVisibility = els.visibility;
1952
+ var originalPosition = els.position;
1953
+ var originalDisplay = els.display;
1954
+ els.visibility = 'hidden';
1955
+ els.position = 'absolute';
1956
+ els.display = 'block';
1957
+ var originalWidth = element.clientWidth;
1958
+ var originalHeight = element.clientHeight;
1959
+ els.display = originalDisplay;
1960
+ els.position = originalPosition;
1961
+ els.visibility = originalVisibility;
1962
+ return {width: originalWidth, height: originalHeight};
1963
+ },
1964
+
1965
+ makePositioned: function(element) {
1966
+ element = $(element);
1967
+ var pos = Element.getStyle(element, 'position');
1968
+ if (pos == 'static' || !pos) {
1969
+ element._madePositioned = true;
1970
+ element.style.position = 'relative';
1971
+ // Opera returns the offset relative to the positioning context, when an
1972
+ // element is position relative but top and left have not been defined
1973
+ if (Prototype.Browser.Opera) {
1974
+ element.style.top = 0;
1975
+ element.style.left = 0;
1976
+ }
1977
+ }
1978
+ return element;
1979
+ },
1980
+
1981
+ undoPositioned: function(element) {
1982
+ element = $(element);
1983
+ if (element._madePositioned) {
1984
+ element._madePositioned = undefined;
1985
+ element.style.position =
1986
+ element.style.top =
1987
+ element.style.left =
1988
+ element.style.bottom =
1989
+ element.style.right = '';
1990
+ }
1991
+ return element;
1992
+ },
1993
+
1994
+ makeClipping: function(element) {
1995
+ element = $(element);
1996
+ if (element._overflow) return element;
1997
+ element._overflow = Element.getStyle(element, 'overflow') || 'auto';
1998
+ if (element._overflow !== 'hidden')
1999
+ element.style.overflow = 'hidden';
2000
+ return element;
2001
+ },
2002
+
2003
+ undoClipping: function(element) {
2004
+ element = $(element);
2005
+ if (!element._overflow) return element;
2006
+ element.style.overflow = element._overflow == 'auto' ? '' : element._overflow;
2007
+ element._overflow = null;
2008
+ return element;
2009
+ },
2010
+
2011
+ cumulativeOffset: function(element) {
2012
+ var valueT = 0, valueL = 0;
2013
+ do {
2014
+ valueT += element.offsetTop || 0;
2015
+ valueL += element.offsetLeft || 0;
2016
+ element = element.offsetParent;
2017
+ } while (element);
2018
+ return Element._returnOffset(valueL, valueT);
2019
+ },
2020
+
2021
+ positionedOffset: function(element) {
2022
+ var valueT = 0, valueL = 0;
2023
+ do {
2024
+ valueT += element.offsetTop || 0;
2025
+ valueL += element.offsetLeft || 0;
2026
+ element = element.offsetParent;
2027
+ if (element) {
2028
+ if (element.tagName.toUpperCase() == 'BODY') break;
2029
+ var p = Element.getStyle(element, 'position');
2030
+ if (p !== 'static') break;
2031
+ }
2032
+ } while (element);
2033
+ return Element._returnOffset(valueL, valueT);
2034
+ },
2035
+
2036
+ absolutize: function(element) {
2037
+ element = $(element);
2038
+ if (element.getStyle('position') == 'absolute') return element;
2039
+ // Position.prepare(); // To be done manually by Scripty when it needs it.
2040
+
2041
+ var offsets = element.positionedOffset();
2042
+ var top = offsets[1];
2043
+ var left = offsets[0];
2044
+ var width = element.clientWidth;
2045
+ var height = element.clientHeight;
2046
+
2047
+ element._originalLeft = left - parseFloat(element.style.left || 0);
2048
+ element._originalTop = top - parseFloat(element.style.top || 0);
2049
+ element._originalWidth = element.style.width;
2050
+ element._originalHeight = element.style.height;
2051
+
2052
+ element.style.position = 'absolute';
2053
+ element.style.top = top + 'px';
2054
+ element.style.left = left + 'px';
2055
+ element.style.width = width + 'px';
2056
+ element.style.height = height + 'px';
2057
+ return element;
2058
+ },
2059
+
2060
+ relativize: function(element) {
2061
+ element = $(element);
2062
+ if (element.getStyle('position') == 'relative') return element;
2063
+ // Position.prepare(); // To be done manually by Scripty when it needs it.
2064
+
2065
+ element.style.position = 'relative';
2066
+ var top = parseFloat(element.style.top || 0) - (element._originalTop || 0);
2067
+ var left = parseFloat(element.style.left || 0) - (element._originalLeft || 0);
2068
+
2069
+ element.style.top = top + 'px';
2070
+ element.style.left = left + 'px';
2071
+ element.style.height = element._originalHeight;
2072
+ element.style.width = element._originalWidth;
2073
+ return element;
2074
+ },
2075
+
2076
+ cumulativeScrollOffset: function(element) {
2077
+ var valueT = 0, valueL = 0;
2078
+ do {
2079
+ valueT += element.scrollTop || 0;
2080
+ valueL += element.scrollLeft || 0;
2081
+ element = element.parentNode;
2082
+ } while (element);
2083
+ return Element._returnOffset(valueL, valueT);
2084
+ },
2085
+
2086
+ getOffsetParent: function(element) {
2087
+ if (element.offsetParent) return $(element.offsetParent);
2088
+ if (element == document.body) return $(element);
2089
+
2090
+ while ((element = element.parentNode) && element != document.body)
2091
+ if (Element.getStyle(element, 'position') != 'static')
2092
+ return $(element);
2093
+
2094
+ return $(document.body);
2095
+ },
2096
+
2097
+ viewportOffset: function(forElement) {
2098
+ var valueT = 0, valueL = 0;
2099
+
2100
+ var element = forElement;
2101
+ do {
2102
+ valueT += element.offsetTop || 0;
2103
+ valueL += element.offsetLeft || 0;
2104
+
2105
+ // Safari fix
2106
+ if (element.offsetParent == document.body &&
2107
+ Element.getStyle(element, 'position') == 'absolute') break;
2108
+
2109
+ } while (element = element.offsetParent);
2110
+
2111
+ element = forElement;
2112
+ do {
2113
+ if (!Prototype.Browser.Opera || (element.tagName && (element.tagName.toUpperCase() == 'BODY'))) {
2114
+ valueT -= element.scrollTop || 0;
2115
+ valueL -= element.scrollLeft || 0;
2116
+ }
2117
+ } while (element = element.parentNode);
2118
+
2119
+ return Element._returnOffset(valueL, valueT);
2120
+ },
2121
+
2122
+ clonePosition: function(element, source) {
2123
+ var options = Object.extend({
2124
+ setLeft: true,
2125
+ setTop: true,
2126
+ setWidth: true,
2127
+ setHeight: true,
2128
+ offsetTop: 0,
2129
+ offsetLeft: 0
2130
+ }, arguments[2] || { });
2131
+
2132
+ // find page position of source
2133
+ source = $(source);
2134
+ var p = source.viewportOffset();
2135
+
2136
+ // find coordinate system to use
2137
+ element = $(element);
2138
+ var delta = [0, 0];
2139
+ var parent = null;
2140
+ // delta [0,0] will do fine with position: fixed elements,
2141
+ // position:absolute needs offsetParent deltas
2142
+ if (Element.getStyle(element, 'position') == 'absolute') {
2143
+ parent = element.getOffsetParent();
2144
+ delta = parent.viewportOffset();
2145
+ }
2146
+
2147
+ // correct by body offsets (fixes Safari)
2148
+ if (parent == document.body) {
2149
+ delta[0] -= document.body.offsetLeft;
2150
+ delta[1] -= document.body.offsetTop;
2151
+ }
2152
+
2153
+ // set position
2154
+ if (options.setLeft) element.style.left = (p[0] - delta[0] + options.offsetLeft) + 'px';
2155
+ if (options.setTop) element.style.top = (p[1] - delta[1] + options.offsetTop) + 'px';
2156
+ if (options.setWidth) element.style.width = source.offsetWidth + 'px';
2157
+ if (options.setHeight) element.style.height = source.offsetHeight + 'px';
2158
+ return element;
2159
+ }
2160
+ };
2161
+
2162
+ Element.Methods.identify.counter = 1;
2163
+
2164
+ Object.extend(Element.Methods, {
2165
+ getElementsBySelector: Element.Methods.select,
2166
+ childElements: Element.Methods.immediateDescendants
2167
+ });
2168
+
2169
+ Element._attributeTranslations = {
2170
+ write: {
2171
+ names: {
2172
+ className: 'class',
2173
+ htmlFor: 'for'
2174
+ },
2175
+ values: { }
2176
+ }
2177
+ };
2178
+
2179
+ if (Prototype.Browser.Opera) {
2180
+ Element.Methods.getStyle = Element.Methods.getStyle.wrap(
2181
+ function(proceed, element, style) {
2182
+ switch (style) {
2183
+ case 'left': case 'top': case 'right': case 'bottom':
2184
+ if (proceed(element, 'position') === 'static') return null;
2185
+ case 'height': case 'width':
2186
+ // returns '0px' for hidden elements; we want it to return null
2187
+ if (!Element.visible(element)) return null;
2188
+
2189
+ // returns the border-box dimensions rather than the content-box
2190
+ // dimensions, so we subtract padding and borders from the value
2191
+ var dim = parseInt(proceed(element, style), 10);
2192
+
2193
+ if (dim !== element['offset' + style.capitalize()])
2194
+ return dim + 'px';
2195
+
2196
+ var properties;
2197
+ if (style === 'height') {
2198
+ properties = ['border-top-width', 'padding-top',
2199
+ 'padding-bottom', 'border-bottom-width'];
2200
+ }
2201
+ else {
2202
+ properties = ['border-left-width', 'padding-left',
2203
+ 'padding-right', 'border-right-width'];
2204
+ }
2205
+ return properties.inject(dim, function(memo, property) {
2206
+ var val = proceed(element, property);
2207
+ return val === null ? memo : memo - parseInt(val, 10);
2208
+ }) + 'px';
2209
+ default: return proceed(element, style);
2210
+ }
2211
+ }
2212
+ );
2213
+
2214
+ Element.Methods.readAttribute = Element.Methods.readAttribute.wrap(
2215
+ function(proceed, element, attribute) {
2216
+ if (attribute === 'title') return element.title;
2217
+ return proceed(element, attribute);
2218
+ }
2219
+ );
2220
+ }
2221
+
2222
+ else if (Prototype.Browser.IE) {
2223
+ // IE doesn't report offsets correctly for static elements, so we change them
2224
+ // to "relative" to get the values, then change them back.
2225
+ Element.Methods.getOffsetParent = Element.Methods.getOffsetParent.wrap(
2226
+ function(proceed, element) {
2227
+ element = $(element);
2228
+ // IE throws an error if element is not in document
2229
+ try { element.offsetParent }
2230
+ catch(e) { return $(document.body) }
2231
+ var position = element.getStyle('position');
2232
+ if (position !== 'static') return proceed(element);
2233
+ element.setStyle({ position: 'relative' });
2234
+ var value = proceed(element);
2235
+ element.setStyle({ position: position });
2236
+ return value;
2237
+ }
2238
+ );
2239
+
2240
+ $w('positionedOffset viewportOffset').each(function(method) {
2241
+ Element.Methods[method] = Element.Methods[method].wrap(
2242
+ function(proceed, element) {
2243
+ element = $(element);
2244
+ try { element.offsetParent }
2245
+ catch(e) { return Element._returnOffset(0,0) }
2246
+ var position = element.getStyle('position');
2247
+ if (position !== 'static') return proceed(element);
2248
+ // Trigger hasLayout on the offset parent so that IE6 reports
2249
+ // accurate offsetTop and offsetLeft values for position: fixed.
2250
+ var offsetParent = element.getOffsetParent();
2251
+ if (offsetParent && offsetParent.getStyle('position') === 'fixed')
2252
+ offsetParent.setStyle({ zoom: 1 });
2253
+ element.setStyle({ position: 'relative' });
2254
+ var value = proceed(element);
2255
+ element.setStyle({ position: position });
2256
+ return value;
2257
+ }
2258
+ );
2259
+ });
2260
+
2261
+ Element.Methods.cumulativeOffset = Element.Methods.cumulativeOffset.wrap(
2262
+ function(proceed, element) {
2263
+ try { element.offsetParent }
2264
+ catch(e) { return Element._returnOffset(0,0) }
2265
+ return proceed(element);
2266
+ }
2267
+ );
2268
+
2269
+ Element.Methods.getStyle = function(element, style) {
2270
+ element = $(element);
2271
+ style = (style == 'float' || style == 'cssFloat') ? 'styleFloat' : style.camelize();
2272
+ var value = element.style[style];
2273
+ if (!value && element.currentStyle) value = element.currentStyle[style];
2274
+
2275
+ if (style == 'opacity') {
2276
+ if (value = (element.getStyle('filter') || '').match(/alpha\(opacity=(.*)\)/))
2277
+ if (value[1]) return parseFloat(value[1]) / 100;
2278
+ return 1.0;
2279
+ }
2280
+
2281
+ if (value == 'auto') {
2282
+ if ((style == 'width' || style == 'height') && (element.getStyle('display') != 'none'))
2283
+ return element['offset' + style.capitalize()] + 'px';
2284
+ return null;
2285
+ }
2286
+ return value;
2287
+ };
2288
+
2289
+ Element.Methods.setOpacity = function(element, value) {
2290
+ function stripAlpha(filter){
2291
+ return filter.replace(/alpha\([^\)]*\)/gi,'');
2292
+ }
2293
+ element = $(element);
2294
+ var currentStyle = element.currentStyle;
2295
+ if ((currentStyle && !currentStyle.hasLayout) ||
2296
+ (!currentStyle && element.style.zoom == 'normal'))
2297
+ element.style.zoom = 1;
2298
+
2299
+ var filter = element.getStyle('filter'), style = element.style;
2300
+ if (value == 1 || value === '') {
2301
+ (filter = stripAlpha(filter)) ?
2302
+ style.filter = filter : style.removeAttribute('filter');
2303
+ return element;
2304
+ } else if (value < 0.00001) value = 0;
2305
+ style.filter = stripAlpha(filter) +
2306
+ 'alpha(opacity=' + (value * 100) + ')';
2307
+ return element;
2308
+ };
2309
+
2310
+ Element._attributeTranslations = {
2311
+ read: {
2312
+ names: {
2313
+ 'class': 'className',
2314
+ 'for': 'htmlFor'
2315
+ },
2316
+ values: {
2317
+ _getAttr: function(element, attribute) {
2318
+ return element.getAttribute(attribute, 2);
2319
+ },
2320
+ _getAttrNode: function(element, attribute) {
2321
+ var node = element.getAttributeNode(attribute);
2322
+ return node ? node.value : "";
2323
+ },
2324
+ _getEv: function(element, attribute) {
2325
+ attribute = element.getAttribute(attribute);
2326
+ return attribute ? attribute.toString().slice(23, -2) : null;
2327
+ },
2328
+ _flag: function(element, attribute) {
2329
+ return $(element).hasAttribute(attribute) ? attribute : null;
2330
+ },
2331
+ style: function(element) {
2332
+ return element.style.cssText.toLowerCase();
2333
+ },
2334
+ title: function(element) {
2335
+ return element.title;
2336
+ }
2337
+ }
2338
+ }
2339
+ };
2340
+
2341
+ Element._attributeTranslations.write = {
2342
+ names: Object.extend({
2343
+ cellpadding: 'cellPadding',
2344
+ cellspacing: 'cellSpacing'
2345
+ }, Element._attributeTranslations.read.names),
2346
+ values: {
2347
+ checked: function(element, value) {
2348
+ element.checked = !!value;
2349
+ },
2350
+
2351
+ style: function(element, value) {
2352
+ element.style.cssText = value ? value : '';
2353
+ }
2354
+ }
2355
+ };
2356
+
2357
+ Element._attributeTranslations.has = {};
2358
+
2359
+ $w('colSpan rowSpan vAlign dateTime accessKey tabIndex ' +
2360
+ 'encType maxLength readOnly longDesc frameBorder').each(function(attr) {
2361
+ Element._attributeTranslations.write.names[attr.toLowerCase()] = attr;
2362
+ Element._attributeTranslations.has[attr.toLowerCase()] = attr;
2363
+ });
2364
+
2365
+ (function(v) {
2366
+ Object.extend(v, {
2367
+ href: v._getAttr,
2368
+ src: v._getAttr,
2369
+ type: v._getAttr,
2370
+ action: v._getAttrNode,
2371
+ disabled: v._flag,
2372
+ checked: v._flag,
2373
+ readonly: v._flag,
2374
+ multiple: v._flag,
2375
+ onload: v._getEv,
2376
+ onunload: v._getEv,
2377
+ onclick: v._getEv,
2378
+ ondblclick: v._getEv,
2379
+ onmousedown: v._getEv,
2380
+ onmouseup: v._getEv,
2381
+ onmouseover: v._getEv,
2382
+ onmousemove: v._getEv,
2383
+ onmouseout: v._getEv,
2384
+ onfocus: v._getEv,
2385
+ onblur: v._getEv,
2386
+ onkeypress: v._getEv,
2387
+ onkeydown: v._getEv,
2388
+ onkeyup: v._getEv,
2389
+ onsubmit: v._getEv,
2390
+ onreset: v._getEv,
2391
+ onselect: v._getEv,
2392
+ onchange: v._getEv
2393
+ });
2394
+ })(Element._attributeTranslations.read.values);
2395
+ }
2396
+
2397
+ else if (Prototype.Browser.Gecko && /rv:1\.8\.0/.test(navigator.userAgent)) {
2398
+ Element.Methods.setOpacity = function(element, value) {
2399
+ element = $(element);
2400
+ element.style.opacity = (value == 1) ? 0.999999 :
2401
+ (value === '') ? '' : (value < 0.00001) ? 0 : value;
2402
+ return element;
2403
+ };
2404
+ }
2405
+
2406
+ else if (Prototype.Browser.WebKit) {
2407
+ Element.Methods.setOpacity = function(element, value) {
2408
+ element = $(element);
2409
+ element.style.opacity = (value == 1 || value === '') ? '' :
2410
+ (value < 0.00001) ? 0 : value;
2411
+
2412
+ if (value == 1)
2413
+ if(element.tagName.toUpperCase() == 'IMG' && element.width) {
2414
+ element.width++; element.width--;
2415
+ } else try {
2416
+ var n = document.createTextNode(' ');
2417
+ element.appendChild(n);
2418
+ element.removeChild(n);
2419
+ } catch (e) { }
2420
+
2421
+ return element;
2422
+ };
2423
+
2424
+ // Safari returns margins on body which is incorrect if the child is absolutely
2425
+ // positioned. For performance reasons, redefine Element#cumulativeOffset for
2426
+ // KHTML/WebKit only.
2427
+ Element.Methods.cumulativeOffset = function(element) {
2428
+ var valueT = 0, valueL = 0;
2429
+ do {
2430
+ valueT += element.offsetTop || 0;
2431
+ valueL += element.offsetLeft || 0;
2432
+ if (element.offsetParent == document.body)
2433
+ if (Element.getStyle(element, 'position') == 'absolute') break;
2434
+
2435
+ element = element.offsetParent;
2436
+ } while (element);
2437
+
2438
+ return Element._returnOffset(valueL, valueT);
2439
+ };
2440
+ }
2441
+
2442
+ if (Prototype.Browser.IE || Prototype.Browser.Opera) {
2443
+ // IE and Opera are missing .innerHTML support for TABLE-related and SELECT elements
2444
+ Element.Methods.update = function(element, content) {
2445
+ element = $(element);
2446
+
2447
+ if (content && content.toElement) content = content.toElement();
2448
+ if (Object.isElement(content)) return element.update().insert(content);
2449
+
2450
+ content = Object.toHTML(content);
2451
+ var tagName = element.tagName.toUpperCase();
2452
+
2453
+ if (tagName in Element._insertionTranslations.tags) {
2454
+ $A(element.childNodes).each(function(node) { element.removeChild(node) });
2455
+ Element._getContentFromAnonymousElement(tagName, content.stripScripts())
2456
+ .each(function(node) { element.appendChild(node) });
2457
+ }
2458
+ else element.innerHTML = content.stripScripts();
2459
+
2460
+ content.evalScripts.bind(content).defer();
2461
+ return element;
2462
+ };
2463
+ }
2464
+
2465
+ if ('outerHTML' in document.createElement('div')) {
2466
+ Element.Methods.replace = function(element, content) {
2467
+ element = $(element);
2468
+
2469
+ if (content && content.toElement) content = content.toElement();
2470
+ if (Object.isElement(content)) {
2471
+ element.parentNode.replaceChild(content, element);
2472
+ return element;
2473
+ }
2474
+
2475
+ content = Object.toHTML(content);
2476
+ var parent = element.parentNode, tagName = parent.tagName.toUpperCase();
2477
+
2478
+ if (Element._insertionTranslations.tags[tagName]) {
2479
+ var nextSibling = element.next();
2480
+ var fragments = Element._getContentFromAnonymousElement(tagName, content.stripScripts());
2481
+ parent.removeChild(element);
2482
+ if (nextSibling)
2483
+ fragments.each(function(node) { parent.insertBefore(node, nextSibling) });
2484
+ else
2485
+ fragments.each(function(node) { parent.appendChild(node) });
2486
+ }
2487
+ else element.outerHTML = content.stripScripts();
2488
+
2489
+ content.evalScripts.bind(content).defer();
2490
+ return element;
2491
+ };
2492
+ }
2493
+
2494
+ Element._returnOffset = function(l, t) {
2495
+ var result = [l, t];
2496
+ result.left = l;
2497
+ result.top = t;
2498
+ return result;
2499
+ };
2500
+
2501
+ Element._getContentFromAnonymousElement = function(tagName, html) {
2502
+ var div = new Element('div'), t = Element._insertionTranslations.tags[tagName];
2503
+ if (t) {
2504
+ div.innerHTML = t[0] + html + t[1];
2505
+ t[2].times(function() { div = div.firstChild });
2506
+ } else div.innerHTML = html;
2507
+ return $A(div.childNodes);
2508
+ };
2509
+
2510
+ Element._insertionTranslations = {
2511
+ before: function(element, node) {
2512
+ element.parentNode.insertBefore(node, element);
2513
+ },
2514
+ top: function(element, node) {
2515
+ element.insertBefore(node, element.firstChild);
2516
+ },
2517
+ bottom: function(element, node) {
2518
+ element.appendChild(node);
2519
+ },
2520
+ after: function(element, node) {
2521
+ element.parentNode.insertBefore(node, element.nextSibling);
2522
+ },
2523
+ tags: {
2524
+ TABLE: ['<table>', '</table>', 1],
2525
+ TBODY: ['<table><tbody>', '</tbody></table>', 2],
2526
+ TR: ['<table><tbody><tr>', '</tr></tbody></table>', 3],
2527
+ TD: ['<table><tbody><tr><td>', '</td></tr></tbody></table>', 4],
2528
+ SELECT: ['<select>', '</select>', 1]
2529
+ }
2530
+ };
2531
+
2532
+ (function() {
2533
+ Object.extend(this.tags, {
2534
+ THEAD: this.tags.TBODY,
2535
+ TFOOT: this.tags.TBODY,
2536
+ TH: this.tags.TD
2537
+ });
2538
+ }).call(Element._insertionTranslations);
2539
+
2540
+ Element.Methods.Simulated = {
2541
+ hasAttribute: function(element, attribute) {
2542
+ attribute = Element._attributeTranslations.has[attribute] || attribute;
2543
+ var node = $(element).getAttributeNode(attribute);
2544
+ return !!(node && node.specified);
2545
+ }
2546
+ };
2547
+
2548
+ Element.Methods.ByTag = { };
2549
+
2550
+ Object.extend(Element, Element.Methods);
2551
+
2552
+ if (!Prototype.BrowserFeatures.ElementExtensions &&
2553
+ document.createElement('div')['__proto__']) {
2554
+ window.HTMLElement = { };
2555
+ window.HTMLElement.prototype = document.createElement('div')['__proto__'];
2556
+ Prototype.BrowserFeatures.ElementExtensions = true;
2557
+ }
2558
+
2559
+ Element.extend = (function() {
2560
+ if (Prototype.BrowserFeatures.SpecificElementExtensions)
2561
+ return Prototype.K;
2562
+
2563
+ var Methods = { }, ByTag = Element.Methods.ByTag;
2564
+
2565
+ var extend = Object.extend(function(element) {
2566
+ if (!element || element._extendedByPrototype ||
2567
+ element.nodeType != 1 || element == window) return element;
2568
+
2569
+ var methods = Object.clone(Methods),
2570
+ tagName = element.tagName.toUpperCase(), property, value;
2571
+
2572
+ // extend methods for specific tags
2573
+ if (ByTag[tagName]) Object.extend(methods, ByTag[tagName]);
2574
+
2575
+ for (property in methods) {
2576
+ value = methods[property];
2577
+ if (Object.isFunction(value) && !(property in element))
2578
+ element[property] = value.methodize();
2579
+ }
2580
+
2581
+ element._extendedByPrototype = Prototype.emptyFunction;
2582
+ return element;
2583
+
2584
+ }, {
2585
+ refresh: function() {
2586
+ // extend methods for all tags (Safari doesn't need this)
2587
+ if (!Prototype.BrowserFeatures.ElementExtensions) {
2588
+ Object.extend(Methods, Element.Methods);
2589
+ Object.extend(Methods, Element.Methods.Simulated);
2590
+ }
2591
+ }
2592
+ });
2593
+
2594
+ extend.refresh();
2595
+ return extend;
2596
+ })();
2597
+
2598
+ Element.hasAttribute = function(element, attribute) {
2599
+ if (element.hasAttribute) return element.hasAttribute(attribute);
2600
+ return Element.Methods.Simulated.hasAttribute(element, attribute);
2601
+ };
2602
+
2603
+ Element.addMethods = function(methods) {
2604
+ var F = Prototype.BrowserFeatures, T = Element.Methods.ByTag;
2605
+
2606
+ if (!methods) {
2607
+ Object.extend(Form, Form.Methods);
2608
+ Object.extend(Form.Element, Form.Element.Methods);
2609
+ Object.extend(Element.Methods.ByTag, {
2610
+ "FORM": Object.clone(Form.Methods),
2611
+ "INPUT": Object.clone(Form.Element.Methods),
2612
+ "SELECT": Object.clone(Form.Element.Methods),
2613
+ "TEXTAREA": Object.clone(Form.Element.Methods)
2614
+ });
2615
+ }
2616
+
2617
+ if (arguments.length == 2) {
2618
+ var tagName = methods;
2619
+ methods = arguments[1];
2620
+ }
2621
+
2622
+ if (!tagName) Object.extend(Element.Methods, methods || { });
2623
+ else {
2624
+ if (Object.isArray(tagName)) tagName.each(extend);
2625
+ else extend(tagName);
2626
+ }
2627
+
2628
+ function extend(tagName) {
2629
+ tagName = tagName.toUpperCase();
2630
+ if (!Element.Methods.ByTag[tagName])
2631
+ Element.Methods.ByTag[tagName] = { };
2632
+ Object.extend(Element.Methods.ByTag[tagName], methods);
2633
+ }
2634
+
2635
+ function copy(methods, destination, onlyIfAbsent) {
2636
+ onlyIfAbsent = onlyIfAbsent || false;
2637
+ for (var property in methods) {
2638
+ var value = methods[property];
2639
+ if (!Object.isFunction(value)) continue;
2640
+ if (!onlyIfAbsent || !(property in destination))
2641
+ destination[property] = value.methodize();
2642
+ }
2643
+ }
2644
+
2645
+ function findDOMClass(tagName) {
2646
+ var klass;
2647
+ var trans = {
2648
+ "OPTGROUP": "OptGroup", "TEXTAREA": "TextArea", "P": "Paragraph",
2649
+ "FIELDSET": "FieldSet", "UL": "UList", "OL": "OList", "DL": "DList",
2650
+ "DIR": "Directory", "H1": "Heading", "H2": "Heading", "H3": "Heading",
2651
+ "H4": "Heading", "H5": "Heading", "H6": "Heading", "Q": "Quote",
2652
+ "INS": "Mod", "DEL": "Mod", "A": "Anchor", "IMG": "Image", "CAPTION":
2653
+ "TableCaption", "COL": "TableCol", "COLGROUP": "TableCol", "THEAD":
2654
+ "TableSection", "TFOOT": "TableSection", "TBODY": "TableSection", "TR":
2655
+ "TableRow", "TH": "TableCell", "TD": "TableCell", "FRAMESET":
2656
+ "FrameSet", "IFRAME": "IFrame"
2657
+ };
2658
+ if (trans[tagName]) klass = 'HTML' + trans[tagName] + 'Element';
2659
+ if (window[klass]) return window[klass];
2660
+ klass = 'HTML' + tagName + 'Element';
2661
+ if (window[klass]) return window[klass];
2662
+ klass = 'HTML' + tagName.capitalize() + 'Element';
2663
+ if (window[klass]) return window[klass];
2664
+
2665
+ window[klass] = { };
2666
+ window[klass].prototype = document.createElement(tagName)['__proto__'];
2667
+ return window[klass];
2668
+ }
2669
+
2670
+ if (F.ElementExtensions) {
2671
+ copy(Element.Methods, HTMLElement.prototype);
2672
+ copy(Element.Methods.Simulated, HTMLElement.prototype, true);
2673
+ }
2674
+
2675
+ if (F.SpecificElementExtensions) {
2676
+ for (var tag in Element.Methods.ByTag) {
2677
+ var klass = findDOMClass(tag);
2678
+ if (Object.isUndefined(klass)) continue;
2679
+ copy(T[tag], klass.prototype);
2680
+ }
2681
+ }
2682
+
2683
+ Object.extend(Element, Element.Methods);
2684
+ delete Element.ByTag;
2685
+
2686
+ if (Element.extend.refresh) Element.extend.refresh();
2687
+ Element.cache = { };
2688
+ };
2689
+
2690
+ document.viewport = {
2691
+ getDimensions: function() {
2692
+ var dimensions = { }, B = Prototype.Browser;
2693
+ $w('width height').each(function(d) {
2694
+ var D = d.capitalize();
2695
+ if (B.WebKit && !document.evaluate) {
2696
+ // Safari <3.0 needs self.innerWidth/Height
2697
+ dimensions[d] = self['inner' + D];
2698
+ } else if (B.Opera && parseFloat(window.opera.version()) < 9.5) {
2699
+ // Opera <9.5 needs document.body.clientWidth/Height
2700
+ dimensions[d] = document.body['client' + D]
2701
+ } else {
2702
+ dimensions[d] = document.documentElement['client' + D];
2703
+ }
2704
+ });
2705
+ return dimensions;
2706
+ },
2707
+
2708
+ getWidth: function() {
2709
+ return this.getDimensions().width;
2710
+ },
2711
+
2712
+ getHeight: function() {
2713
+ return this.getDimensions().height;
2714
+ },
2715
+
2716
+ getScrollOffsets: function() {
2717
+ return Element._returnOffset(
2718
+ window.pageXOffset || document.documentElement.scrollLeft || document.body.scrollLeft,
2719
+ window.pageYOffset || document.documentElement.scrollTop || document.body.scrollTop);
2720
+ }
2721
+ };
2722
+ /* Portions of the Selector class are derived from Jack Slocum's DomQuery,
2723
+ * part of YUI-Ext version 0.40, distributed under the terms of an MIT-style
2724
+ * license. Please see http://www.yui-ext.com/ for more information. */
2725
+
2726
+ var Selector = Class.create({
2727
+ initialize: function(expression) {
2728
+ this.expression = expression.strip();
2729
+
2730
+ if (this.shouldUseSelectorsAPI()) {
2731
+ this.mode = 'selectorsAPI';
2732
+ } else if (this.shouldUseXPath()) {
2733
+ this.mode = 'xpath';
2734
+ this.compileXPathMatcher();
2735
+ } else {
2736
+ this.mode = "normal";
2737
+ this.compileMatcher();
2738
+ }
2739
+
2740
+ },
2741
+
2742
+ shouldUseXPath: function() {
2743
+ if (!Prototype.BrowserFeatures.XPath) return false;
2744
+
2745
+ var e = this.expression;
2746
+
2747
+ // Safari 3 chokes on :*-of-type and :empty
2748
+ if (Prototype.Browser.WebKit &&
2749
+ (e.include("-of-type") || e.include(":empty")))
2750
+ return false;
2751
+
2752
+ // XPath can't do namespaced attributes, nor can it read
2753
+ // the "checked" property from DOM nodes
2754
+ if ((/(\[[\w-]*?:|:checked)/).test(e))
2755
+ return false;
2756
+
2757
+ return true;
2758
+ },
2759
+
2760
+ shouldUseSelectorsAPI: function() {
2761
+ if (!Prototype.BrowserFeatures.SelectorsAPI) return false;
2762
+
2763
+ if (!Selector._div) Selector._div = new Element('div');
2764
+
2765
+ // Make sure the browser treats the selector as valid. Test on an
2766
+ // isolated element to minimize cost of this check.
2767
+ try {
2768
+ Selector._div.querySelector(this.expression);
2769
+ } catch(e) {
2770
+ return false;
2771
+ }
2772
+
2773
+ return true;
2774
+ },
2775
+
2776
+ compileMatcher: function() {
2777
+ var e = this.expression, ps = Selector.patterns, h = Selector.handlers,
2778
+ c = Selector.criteria, le, p, m;
2779
+
2780
+ if (Selector._cache[e]) {
2781
+ this.matcher = Selector._cache[e];
2782
+ return;
2783
+ }
2784
+
2785
+ this.matcher = ["this.matcher = function(root) {",
2786
+ "var r = root, h = Selector.handlers, c = false, n;"];
2787
+
2788
+ while (e && le != e && (/\S/).test(e)) {
2789
+ le = e;
2790
+ for (var i in ps) {
2791
+ p = ps[i];
2792
+ if (m = e.match(p)) {
2793
+ this.matcher.push(Object.isFunction(c[i]) ? c[i](m) :
2794
+ new Template(c[i]).evaluate(m));
2795
+ e = e.replace(m[0], '');
2796
+ break;
2797
+ }
2798
+ }
2799
+ }
2800
+
2801
+ this.matcher.push("return h.unique(n);\n}");
2802
+ eval(this.matcher.join('\n'));
2803
+ Selector._cache[this.expression] = this.matcher;
2804
+ },
2805
+
2806
+ compileXPathMatcher: function() {
2807
+ var e = this.expression, ps = Selector.patterns,
2808
+ x = Selector.xpath, le, m;
2809
+
2810
+ if (Selector._cache[e]) {
2811
+ this.xpath = Selector._cache[e]; return;
2812
+ }
2813
+
2814
+ this.matcher = ['.//*'];
2815
+ while (e && le != e && (/\S/).test(e)) {
2816
+ le = e;
2817
+ for (var i in ps) {
2818
+ if (m = e.match(ps[i])) {
2819
+ this.matcher.push(Object.isFunction(x[i]) ? x[i](m) :
2820
+ new Template(x[i]).evaluate(m));
2821
+ e = e.replace(m[0], '');
2822
+ break;
2823
+ }
2824
+ }
2825
+ }
2826
+
2827
+ this.xpath = this.matcher.join('');
2828
+ Selector._cache[this.expression] = this.xpath;
2829
+ },
2830
+
2831
+ findElements: function(root) {
2832
+ root = root || document;
2833
+ var e = this.expression, results;
2834
+
2835
+ switch (this.mode) {
2836
+ case 'selectorsAPI':
2837
+ // removed the id trickery from here since it failed when built-in
2838
+ results = $A(root.querySelectorAll(e));
2839
+ return results;
2840
+ case 'xpath':
2841
+ return document._getElementsByXPath(this.xpath, root);
2842
+ default:
2843
+ return this.matcher(root);
2844
+ }
2845
+ },
2846
+
2847
+ match: function(element) {
2848
+ this.tokens = [];
2849
+
2850
+ var e = this.expression, ps = Selector.patterns, as = Selector.assertions;
2851
+ var le, p, m;
2852
+
2853
+ while (e && le !== e && (/\S/).test(e)) {
2854
+ le = e;
2855
+ for (var i in ps) {
2856
+ p = ps[i];
2857
+ if (m = e.match(p)) {
2858
+ // use the Selector.assertions methods unless the selector
2859
+ // is too complex.
2860
+ if (as[i]) {
2861
+ this.tokens.push([i, Object.clone(m)]);
2862
+ e = e.replace(m[0], '');
2863
+ } else {
2864
+ // reluctantly do a document-wide search
2865
+ // and look for a match in the array
2866
+ return this.findElements(document).include(element);
2867
+ }
2868
+ }
2869
+ }
2870
+ }
2871
+
2872
+ var match = true, name, matches;
2873
+ for (var i = 0, token; token = this.tokens[i]; i++) {
2874
+ name = token[0], matches = token[1];
2875
+ if (!Selector.assertions[name](element, matches)) {
2876
+ match = false; break;
2877
+ }
2878
+ }
2879
+
2880
+ return match;
2881
+ },
2882
+
2883
+ toString: function() {
2884
+ return this.expression;
2885
+ },
2886
+
2887
+ inspect: function() {
2888
+ return "#<Selector:" + this.expression.inspect() + ">";
2889
+ }
2890
+ });
2891
+
2892
+ Object.extend(Selector, {
2893
+ _cache: { },
2894
+
2895
+ xpath: {
2896
+ descendant: "//*",
2897
+ child: "/*",
2898
+ adjacent: "/following-sibling::*[1]",
2899
+ laterSibling: '/following-sibling::*',
2900
+ tagName: function(m) {
2901
+ if (m[1] == '*') return '';
2902
+ return "[local-name()='" + m[1].toLowerCase() +
2903
+ "' or local-name()='" + m[1].toUpperCase() + "']";
2904
+ },
2905
+ className: "[contains(concat(' ', @class, ' '), ' #{1} ')]",
2906
+ id: "[@id='#{1}']",
2907
+ attrPresence: function(m) {
2908
+ m[1] = m[1].toLowerCase();
2909
+ return new Template("[@#{1}]").evaluate(m);
2910
+ },
2911
+ attr: function(m) {
2912
+ m[1] = m[1].toLowerCase();
2913
+ m[3] = m[5] || m[6];
2914
+ return new Template(Selector.xpath.operators[m[2]]).evaluate(m);
2915
+ },
2916
+ pseudo: function(m) {
2917
+ var h = Selector.xpath.pseudos[m[1]];
2918
+ if (!h) return '';
2919
+ if (Object.isFunction(h)) return h(m);
2920
+ return new Template(Selector.xpath.pseudos[m[1]]).evaluate(m);
2921
+ },
2922
+ operators: {
2923
+ '=': "[@#{1}='#{3}']",
2924
+ '!=': "[@#{1}!='#{3}']",
2925
+ '^=': "[starts-with(@#{1}, '#{3}')]",
2926
+ '$=': "[substring(@#{1}, (string-length(@#{1}) - string-length('#{3}') + 1))='#{3}']",
2927
+ '*=': "[contains(@#{1}, '#{3}')]",
2928
+ '~=': "[contains(concat(' ', @#{1}, ' '), ' #{3} ')]",
2929
+ '|=': "[contains(concat('-', @#{1}, '-'), '-#{3}-')]"
2930
+ },
2931
+ pseudos: {
2932
+ 'first-child': '[not(preceding-sibling::*)]',
2933
+ 'last-child': '[not(following-sibling::*)]',
2934
+ 'only-child': '[not(preceding-sibling::* or following-sibling::*)]',
2935
+ 'empty': "[count(*) = 0 and (count(text()) = 0)]",
2936
+ 'checked': "[@checked]",
2937
+ 'disabled': "[(@disabled) and (@type!='hidden')]",
2938
+ 'enabled': "[not(@disabled) and (@type!='hidden')]",
2939
+ 'not': function(m) {
2940
+ var e = m[6], p = Selector.patterns,
2941
+ x = Selector.xpath, le, v;
2942
+
2943
+ var exclusion = [];
2944
+ while (e && le != e && (/\S/).test(e)) {
2945
+ le = e;
2946
+ for (var i in p) {
2947
+ if (m = e.match(p[i])) {
2948
+ v = Object.isFunction(x[i]) ? x[i](m) : new Template(x[i]).evaluate(m);
2949
+ exclusion.push("(" + v.substring(1, v.length - 1) + ")");
2950
+ e = e.replace(m[0], '');
2951
+ break;
2952
+ }
2953
+ }
2954
+ }
2955
+ return "[not(" + exclusion.join(" and ") + ")]";
2956
+ },
2957
+ 'nth-child': function(m) {
2958
+ return Selector.xpath.pseudos.nth("(count(./preceding-sibling::*) + 1) ", m);
2959
+ },
2960
+ 'nth-last-child': function(m) {
2961
+ return Selector.xpath.pseudos.nth("(count(./following-sibling::*) + 1) ", m);
2962
+ },
2963
+ 'nth-of-type': function(m) {
2964
+ return Selector.xpath.pseudos.nth("position() ", m);
2965
+ },
2966
+ 'nth-last-of-type': function(m) {
2967
+ return Selector.xpath.pseudos.nth("(last() + 1 - position()) ", m);
2968
+ },
2969
+ 'first-of-type': function(m) {
2970
+ m[6] = "1"; return Selector.xpath.pseudos['nth-of-type'](m);
2971
+ },
2972
+ 'last-of-type': function(m) {
2973
+ m[6] = "1"; return Selector.xpath.pseudos['nth-last-of-type'](m);
2974
+ },
2975
+ 'only-of-type': function(m) {
2976
+ var p = Selector.xpath.pseudos; return p['first-of-type'](m) + p['last-of-type'](m);
2977
+ },
2978
+ nth: function(fragment, m) {
2979
+ var mm, formula = m[6], predicate;
2980
+ if (formula == 'even') formula = '2n+0';
2981
+ if (formula == 'odd') formula = '2n+1';
2982
+ if (mm = formula.match(/^(\d+)$/)) // digit only
2983
+ return '[' + fragment + "= " + mm[1] + ']';
2984
+ if (mm = formula.match(/^(-?\d*)?n(([+-])(\d+))?/)) { // an+b
2985
+ if (mm[1] == "-") mm[1] = -1;
2986
+ var a = mm[1] ? Number(mm[1]) : 1;
2987
+ var b = mm[2] ? Number(mm[2]) : 0;
2988
+ predicate = "[((#{fragment} - #{b}) mod #{a} = 0) and " +
2989
+ "((#{fragment} - #{b}) div #{a} >= 0)]";
2990
+ return new Template(predicate).evaluate({
2991
+ fragment: fragment, a: a, b: b });
2992
+ }
2993
+ }
2994
+ }
2995
+ },
2996
+
2997
+ criteria: {
2998
+ tagName: 'n = h.tagName(n, r, "#{1}", c); c = false;',
2999
+ className: 'n = h.className(n, r, "#{1}", c); c = false;',
3000
+ id: 'n = h.id(n, r, "#{1}", c); c = false;',
3001
+ attrPresence: 'n = h.attrPresence(n, r, "#{1}", c); c = false;',
3002
+ attr: function(m) {
3003
+ m[3] = (m[5] || m[6]);
3004
+ return new Template('n = h.attr(n, r, "#{1}", "#{3}", "#{2}", c); c = false;').evaluate(m);
3005
+ },
3006
+ pseudo: function(m) {
3007
+ if (m[6]) m[6] = m[6].replace(/"/g, '\\"');
3008
+ return new Template('n = h.pseudo(n, "#{1}", "#{6}", r, c); c = false;').evaluate(m);
3009
+ },
3010
+ descendant: 'c = "descendant";',
3011
+ child: 'c = "child";',
3012
+ adjacent: 'c = "adjacent";',
3013
+ laterSibling: 'c = "laterSibling";'
3014
+ },
3015
+
3016
+ patterns: {
3017
+ // combinators must be listed first
3018
+ // (and descendant needs to be last combinator)
3019
+ laterSibling: /^\s*~\s*/,
3020
+ child: /^\s*>\s*/,
3021
+ adjacent: /^\s*\+\s*/,
3022
+ descendant: /^\s/,
3023
+
3024
+ // selectors follow
3025
+ tagName: /^\s*(\*|[\w\-]+)(\b|$)?/,
3026
+ id: /^#([\w\-\*]+)(\b|$)/,
3027
+ className: /^\.([\w\-\*]+)(\b|$)/,
3028
+ pseudo:
3029
+ /^:((first|last|nth|nth-last|only)(-child|-of-type)|empty|checked|(en|dis)abled|not)(\((.*?)\))?(\b|$|(?=\s|[:+~>]))/,
3030
+ attrPresence: /^\[((?:[\w]+:)?[\w]+)\]/,
3031
+ attr: /\[((?:[\w-]*:)?[\w-]+)\s*(?:([!^$*~|]?=)\s*((['"])([^\4]*?)\4|([^'"][^\]]*?)))?\]/
3032
+ },
3033
+
3034
+ // for Selector.match and Element#match
3035
+ assertions: {
3036
+ tagName: function(element, matches) {
3037
+ return matches[1].toUpperCase() == element.tagName.toUpperCase();
3038
+ },
3039
+
3040
+ className: function(element, matches) {
3041
+ return Element.hasClassName(element, matches[1]);
3042
+ },
3043
+
3044
+ id: function(element, matches) {
3045
+ return element.id === matches[1];
3046
+ },
3047
+
3048
+ attrPresence: function(element, matches) {
3049
+ return Element.hasAttribute(element, matches[1]);
3050
+ },
3051
+
3052
+ attr: function(element, matches) {
3053
+ var nodeValue = Element.readAttribute(element, matches[1]);
3054
+ return nodeValue && Selector.operators[matches[2]](nodeValue, matches[5] || matches[6]);
3055
+ }
3056
+ },
3057
+
3058
+ handlers: {
3059
+ // UTILITY FUNCTIONS
3060
+ // joins two collections
3061
+ concat: function(a, b) {
3062
+ for (var i = 0, node; node = b[i]; i++)
3063
+ a.push(node);
3064
+ return a;
3065
+ },
3066
+
3067
+ // marks an array of nodes for counting
3068
+ mark: function(nodes) {
3069
+ var _true = Prototype.emptyFunction;
3070
+ for (var i = 0, node; node = nodes[i]; i++)
3071
+ node._countedByPrototype = _true;
3072
+ return nodes;
3073
+ },
3074
+
3075
+ unmark: function(nodes) {
3076
+ for (var i = 0, node; node = nodes[i]; i++)
3077
+ node._countedByPrototype = undefined;
3078
+ return nodes;
3079
+ },
3080
+
3081
+ // mark each child node with its position (for nth calls)
3082
+ // "ofType" flag indicates whether we're indexing for nth-of-type
3083
+ // rather than nth-child
3084
+ index: function(parentNode, reverse, ofType) {
3085
+ parentNode._countedByPrototype = Prototype.emptyFunction;
3086
+ if (reverse) {
3087
+ for (var nodes = parentNode.childNodes, i = nodes.length - 1, j = 1; i >= 0; i--) {
3088
+ var node = nodes[i];
3089
+ if (node.nodeType == 1 && (!ofType || node._countedByPrototype)) node.nodeIndex = j++;
3090
+ }
3091
+ } else {
3092
+ for (var i = 0, j = 1, nodes = parentNode.childNodes; node = nodes[i]; i++)
3093
+ if (node.nodeType == 1 && (!ofType || node._countedByPrototype)) node.nodeIndex = j++;
3094
+ }
3095
+ },
3096
+
3097
+ // filters out duplicates and extends all nodes
3098
+ unique: function(nodes) {
3099
+ if (nodes.length == 0) return nodes;
3100
+ var results = [], n;
3101
+ for (var i = 0, l = nodes.length; i < l; i++)
3102
+ if (!(n = nodes[i])._countedByPrototype) {
3103
+ n._countedByPrototype = Prototype.emptyFunction;
3104
+ results.push(Element.extend(n));
3105
+ }
3106
+ return Selector.handlers.unmark(results);
3107
+ },
3108
+
3109
+ // COMBINATOR FUNCTIONS
3110
+ descendant: function(nodes) {
3111
+ var h = Selector.handlers;
3112
+ for (var i = 0, results = [], node; node = nodes[i]; i++)
3113
+ h.concat(results, node.getElementsByTagName('*'));
3114
+ return results;
3115
+ },
3116
+
3117
+ child: function(nodes) {
3118
+ var h = Selector.handlers;
3119
+ for (var i = 0, results = [], node; node = nodes[i]; i++) {
3120
+ for (var j = 0, child; child = node.childNodes[j]; j++)
3121
+ if (child.nodeType == 1 && child.tagName != '!') results.push(child);
3122
+ }
3123
+ return results;
3124
+ },
3125
+
3126
+ adjacent: function(nodes) {
3127
+ for (var i = 0, results = [], node; node = nodes[i]; i++) {
3128
+ var next = this.nextElementSibling(node);
3129
+ if (next) results.push(next);
3130
+ }
3131
+ return results;
3132
+ },
3133
+
3134
+ laterSibling: function(nodes) {
3135
+ var h = Selector.handlers;
3136
+ for (var i = 0, results = [], node; node = nodes[i]; i++)
3137
+ h.concat(results, Element.nextSiblings(node));
3138
+ return results;
3139
+ },
3140
+
3141
+ nextElementSibling: function(node) {
3142
+ while (node = node.nextSibling)
3143
+ if (node.nodeType == 1) return node;
3144
+ return null;
3145
+ },
3146
+
3147
+ previousElementSibling: function(node) {
3148
+ while (node = node.previousSibling)
3149
+ if (node.nodeType == 1) return node;
3150
+ return null;
3151
+ },
3152
+
3153
+ // TOKEN FUNCTIONS
3154
+ tagName: function(nodes, root, tagName, combinator) {
3155
+ var uTagName = tagName.toUpperCase();
3156
+ var results = [], h = Selector.handlers;
3157
+ if (nodes) {
3158
+ if (combinator) {
3159
+ // fastlane for ordinary descendant combinators
3160
+ if (combinator == "descendant") {
3161
+ for (var i = 0, node; node = nodes[i]; i++)
3162
+ h.concat(results, node.getElementsByTagName(tagName));
3163
+ return results;
3164
+ } else nodes = this[combinator](nodes);
3165
+ if (tagName == "*") return nodes;
3166
+ }
3167
+ for (var i = 0, node; node = nodes[i]; i++)
3168
+ if (node.tagName.toUpperCase() === uTagName) results.push(node);
3169
+ return results;
3170
+ } else return root.getElementsByTagName(tagName);
3171
+ },
3172
+
3173
+ id: function(nodes, root, id, combinator) {
3174
+ var targetNode = $(id), h = Selector.handlers;
3175
+ if (!targetNode) return [];
3176
+ if (!nodes && root == document) return [targetNode];
3177
+ if (nodes) {
3178
+ if (combinator) {
3179
+ if (combinator == 'child') {
3180
+ for (var i = 0, node; node = nodes[i]; i++)
3181
+ if (targetNode.parentNode == node) return [targetNode];
3182
+ } else if (combinator == 'descendant') {
3183
+ for (var i = 0, node; node = nodes[i]; i++)
3184
+ if (Element.descendantOf(targetNode, node)) return [targetNode];
3185
+ } else if (combinator == 'adjacent') {
3186
+ for (var i = 0, node; node = nodes[i]; i++)
3187
+ if (Selector.handlers.previousElementSibling(targetNode) == node)
3188
+ return [targetNode];
3189
+ } else nodes = h[combinator](nodes);
3190
+ }
3191
+ for (var i = 0, node; node = nodes[i]; i++)
3192
+ if (node == targetNode) return [targetNode];
3193
+ return [];
3194
+ }
3195
+ return (targetNode && Element.descendantOf(targetNode, root)) ? [targetNode] : [];
3196
+ },
3197
+
3198
+ className: function(nodes, root, className, combinator) {
3199
+ if (nodes && combinator) nodes = this[combinator](nodes);
3200
+ return Selector.handlers.byClassName(nodes, root, className);
3201
+ },
3202
+
3203
+ byClassName: function(nodes, root, className) {
3204
+ if (!nodes) nodes = Selector.handlers.descendant([root]);
3205
+ var needle = ' ' + className + ' ';
3206
+ for (var i = 0, results = [], node, nodeClassName; node = nodes[i]; i++) {
3207
+ nodeClassName = node.className;
3208
+ if (nodeClassName.length == 0) continue;
3209
+ if (nodeClassName == className || (' ' + nodeClassName + ' ').include(needle))
3210
+ results.push(node);
3211
+ }
3212
+ return results;
3213
+ },
3214
+
3215
+ attrPresence: function(nodes, root, attr, combinator) {
3216
+ if (!nodes) nodes = root.getElementsByTagName("*");
3217
+ if (nodes && combinator) nodes = this[combinator](nodes);
3218
+ var results = [];
3219
+ for (var i = 0, node; node = nodes[i]; i++)
3220
+ if (Element.hasAttribute(node, attr)) results.push(node);
3221
+ return results;
3222
+ },
3223
+
3224
+ attr: function(nodes, root, attr, value, operator, combinator) {
3225
+ if (!nodes) nodes = root.getElementsByTagName("*");
3226
+ if (nodes && combinator) nodes = this[combinator](nodes);
3227
+ var handler = Selector.operators[operator], results = [];
3228
+ for (var i = 0, node; node = nodes[i]; i++) {
3229
+ var nodeValue = Element.readAttribute(node, attr);
3230
+ if (nodeValue === null) continue;
3231
+ if (handler(nodeValue, value)) results.push(node);
3232
+ }
3233
+ return results;
3234
+ },
3235
+
3236
+ pseudo: function(nodes, name, value, root, combinator) {
3237
+ if (nodes && combinator) nodes = this[combinator](nodes);
3238
+ if (!nodes) nodes = root.getElementsByTagName("*");
3239
+ return Selector.pseudos[name](nodes, value, root);
3240
+ }
3241
+ },
3242
+
3243
+ pseudos: {
3244
+ 'first-child': function(nodes, value, root) {
3245
+ for (var i = 0, results = [], node; node = nodes[i]; i++) {
3246
+ if (Selector.handlers.previousElementSibling(node)) continue;
3247
+ results.push(node);
3248
+ }
3249
+ return results;
3250
+ },
3251
+ 'last-child': function(nodes, value, root) {
3252
+ for (var i = 0, results = [], node; node = nodes[i]; i++) {
3253
+ if (Selector.handlers.nextElementSibling(node)) continue;
3254
+ results.push(node);
3255
+ }
3256
+ return results;
3257
+ },
3258
+ 'only-child': function(nodes, value, root) {
3259
+ var h = Selector.handlers;
3260
+ for (var i = 0, results = [], node; node = nodes[i]; i++)
3261
+ if (!h.previousElementSibling(node) && !h.nextElementSibling(node))
3262
+ results.push(node);
3263
+ return results;
3264
+ },
3265
+ 'nth-child': function(nodes, formula, root) {
3266
+ return Selector.pseudos.nth(nodes, formula, root);
3267
+ },
3268
+ 'nth-last-child': function(nodes, formula, root) {
3269
+ return Selector.pseudos.nth(nodes, formula, root, true);
3270
+ },
3271
+ 'nth-of-type': function(nodes, formula, root) {
3272
+ return Selector.pseudos.nth(nodes, formula, root, false, true);
3273
+ },
3274
+ 'nth-last-of-type': function(nodes, formula, root) {
3275
+ return Selector.pseudos.nth(nodes, formula, root, true, true);
3276
+ },
3277
+ 'first-of-type': function(nodes, formula, root) {
3278
+ return Selector.pseudos.nth(nodes, "1", root, false, true);
3279
+ },
3280
+ 'last-of-type': function(nodes, formula, root) {
3281
+ return Selector.pseudos.nth(nodes, "1", root, true, true);
3282
+ },
3283
+ 'only-of-type': function(nodes, formula, root) {
3284
+ var p = Selector.pseudos;
3285
+ return p['last-of-type'](p['first-of-type'](nodes, formula, root), formula, root);
3286
+ },
3287
+
3288
+ // handles the an+b logic
3289
+ getIndices: function(a, b, total) {
3290
+ if (a == 0) return b > 0 ? [b] : [];
3291
+ return $R(1, total).inject([], function(memo, i) {
3292
+ if (0 == (i - b) % a && (i - b) / a >= 0) memo.push(i);
3293
+ return memo;
3294
+ });
3295
+ },
3296
+
3297
+ // handles nth(-last)-child, nth(-last)-of-type, and (first|last)-of-type
3298
+ nth: function(nodes, formula, root, reverse, ofType) {
3299
+ if (nodes.length == 0) return [];
3300
+ if (formula == 'even') formula = '2n+0';
3301
+ if (formula == 'odd') formula = '2n+1';
3302
+ var h = Selector.handlers, results = [], indexed = [], m;
3303
+ h.mark(nodes);
3304
+ for (var i = 0, node; node = nodes[i]; i++) {
3305
+ if (!node.parentNode._countedByPrototype) {
3306
+ h.index(node.parentNode, reverse, ofType);
3307
+ indexed.push(node.parentNode);
3308
+ }
3309
+ }
3310
+ if (formula.match(/^\d+$/)) { // just a number
3311
+ formula = Number(formula);
3312
+ for (var i = 0, node; node = nodes[i]; i++)
3313
+ if (node.nodeIndex == formula) results.push(node);
3314
+ } else if (m = formula.match(/^(-?\d*)?n(([+-])(\d+))?/)) { // an+b
3315
+ if (m[1] == "-") m[1] = -1;
3316
+ var a = m[1] ? Number(m[1]) : 1;
3317
+ var b = m[2] ? Number(m[2]) : 0;
3318
+ var indices = Selector.pseudos.getIndices(a, b, nodes.length);
3319
+ for (var i = 0, node, l = indices.length; node = nodes[i]; i++) {
3320
+ for (var j = 0; j < l; j++)
3321
+ if (node.nodeIndex == indices[j]) results.push(node);
3322
+ }
3323
+ }
3324
+ h.unmark(nodes);
3325
+ h.unmark(indexed);
3326
+ return results;
3327
+ },
3328
+
3329
+ 'empty': function(nodes, value, root) {
3330
+ for (var i = 0, results = [], node; node = nodes[i]; i++) {
3331
+ // IE treats comments as element nodes
3332
+ if (node.tagName == '!' || node.firstChild) continue;
3333
+ results.push(node);
3334
+ }
3335
+ return results;
3336
+ },
3337
+
3338
+ 'not': function(nodes, selector, root) {
3339
+ var h = Selector.handlers, selectorType, m;
3340
+ var exclusions = new Selector(selector).findElements(root);
3341
+ h.mark(exclusions);
3342
+ for (var i = 0, results = [], node; node = nodes[i]; i++)
3343
+ if (!node._countedByPrototype) results.push(node);
3344
+ h.unmark(exclusions);
3345
+ return results;
3346
+ },
3347
+
3348
+ 'enabled': function(nodes, value, root) {
3349
+ for (var i = 0, results = [], node; node = nodes[i]; i++)
3350
+ if (!node.disabled && (!node.type || node.type !== 'hidden'))
3351
+ results.push(node);
3352
+ return results;
3353
+ },
3354
+
3355
+ 'disabled': function(nodes, value, root) {
3356
+ for (var i = 0, results = [], node; node = nodes[i]; i++)
3357
+ if (node.disabled) results.push(node);
3358
+ return results;
3359
+ },
3360
+
3361
+ 'checked': function(nodes, value, root) {
3362
+ for (var i = 0, results = [], node; node = nodes[i]; i++)
3363
+ if (node.checked) results.push(node);
3364
+ return results;
3365
+ }
3366
+ },
3367
+
3368
+ operators: {
3369
+ '=': function(nv, v) { return nv == v; },
3370
+ '!=': function(nv, v) { return nv != v; },
3371
+ '^=': function(nv, v) { return nv == v || nv && nv.startsWith(v); },
3372
+ '$=': function(nv, v) { return nv == v || nv && nv.endsWith(v); },
3373
+ '*=': function(nv, v) { return nv == v || nv && nv.include(v); },
3374
+ '$=': function(nv, v) { return nv.endsWith(v); },
3375
+ '*=': function(nv, v) { return nv.include(v); },
3376
+ '~=': function(nv, v) { return (' ' + nv + ' ').include(' ' + v + ' '); },
3377
+ '|=': function(nv, v) { return ('-' + (nv || "").toUpperCase() +
3378
+ '-').include('-' + (v || "").toUpperCase() + '-'); }
3379
+ },
3380
+
3381
+ split: function(expression) {
3382
+ var expressions = [];
3383
+ expression.scan(/(([\w#:.~>+()\s-]+|\*|\[.*?\])+)\s*(,|$)/, function(m) {
3384
+ expressions.push(m[1].strip());
3385
+ });
3386
+ return expressions;
3387
+ },
3388
+
3389
+ matchElements: function(elements, expression) {
3390
+ var matches = $$(expression), h = Selector.handlers;
3391
+ h.mark(matches);
3392
+ for (var i = 0, results = [], element; element = elements[i]; i++)
3393
+ if (element._countedByPrototype) results.push(element);
3394
+ h.unmark(matches);
3395
+ return results;
3396
+ },
3397
+
3398
+ findElement: function(elements, expression, index) {
3399
+ if (Object.isNumber(expression)) {
3400
+ index = expression; expression = false;
3401
+ }
3402
+ return Selector.matchElements(elements, expression || '*')[index || 0];
3403
+ },
3404
+
3405
+ findChildElements: function(element, expressions) {
3406
+ expressions = Selector.split(expressions.join(','));
3407
+ var results = [], h = Selector.handlers;
3408
+ for (var i = 0, l = expressions.length, selector; i < l; i++) {
3409
+ selector = new Selector(expressions[i].strip());
3410
+ h.concat(results, selector.findElements(element));
3411
+ }
3412
+ return (l > 1) ? h.unique(results) : results;
3413
+ }
3414
+ });
3415
+
3416
+ if (Prototype.Browser.IE) {
3417
+ Object.extend(Selector.handlers, {
3418
+ // IE returns comment nodes on getElementsByTagName("*").
3419
+ // Filter them out.
3420
+ concat: function(a, b) {
3421
+ for (var i = 0, node; node = b[i]; i++)
3422
+ if (node.tagName !== "!") a.push(node);
3423
+ return a;
3424
+ },
3425
+
3426
+ // IE improperly serializes _countedByPrototype in (inner|outer)HTML.
3427
+ unmark: function(nodes) {
3428
+ for (var i = 0, node; node = nodes[i]; i++)
3429
+ node.removeAttribute('_countedByPrototype');
3430
+ return nodes;
3431
+ }
3432
+ });
3433
+ }
3434
+
3435
+ function $$() {
3436
+ return Selector.findChildElements(document, $A(arguments));
3437
+ }
3438
+ var Form = {
3439
+ reset: function(form) {
3440
+ $(form).reset();
3441
+ return form;
3442
+ },
3443
+
3444
+ serializeElements: function(elements, options) {
3445
+ if (typeof options != 'object') options = { hash: !!options };
3446
+ else if (Object.isUndefined(options.hash)) options.hash = true;
3447
+ var key, value, submitted = false, submit = options.submit;
3448
+
3449
+ var data = elements.inject({ }, function(result, element) {
3450
+ if (!element.disabled && element.name) {
3451
+ key = element.name; value = $(element).getValue();
3452
+ if (value != null && element.type != 'file' && (element.type != 'submit' || (!submitted &&
3453
+ submit !== false && (!submit || key == submit) && (submitted = true)))) {
3454
+ if (key in result) {
3455
+ // a key is already present; construct an array of values
3456
+ if (!Object.isArray(result[key])) result[key] = [result[key]];
3457
+ result[key].push(value);
3458
+ }
3459
+ else result[key] = value;
3460
+ }
3461
+ }
3462
+ return result;
3463
+ });
3464
+
3465
+ return options.hash ? data : Object.toQueryString(data);
3466
+ }
3467
+ };
3468
+
3469
+ Form.Methods = {
3470
+ serialize: function(form, options) {
3471
+ return Form.serializeElements(Form.getElements(form), options);
3472
+ },
3473
+
3474
+ getElements: function(form) {
3475
+ return $A($(form).getElementsByTagName('*')).inject([],
3476
+ function(elements, child) {
3477
+ if (Form.Element.Serializers[child.tagName.toLowerCase()])
3478
+ elements.push(Element.extend(child));
3479
+ return elements;
3480
+ }
3481
+ );
3482
+ },
3483
+
3484
+ getInputs: function(form, typeName, name) {
3485
+ form = $(form);
3486
+ var inputs = form.getElementsByTagName('input');
3487
+
3488
+ if (!typeName && !name) return $A(inputs).map(Element.extend);
3489
+
3490
+ for (var i = 0, matchingInputs = [], length = inputs.length; i < length; i++) {
3491
+ var input = inputs[i];
3492
+ if ((typeName && input.type != typeName) || (name && input.name != name))
3493
+ continue;
3494
+ matchingInputs.push(Element.extend(input));
3495
+ }
3496
+
3497
+ return matchingInputs;
3498
+ },
3499
+
3500
+ disable: function(form) {
3501
+ form = $(form);
3502
+ Form.getElements(form).invoke('disable');
3503
+ return form;
3504
+ },
3505
+
3506
+ enable: function(form) {
3507
+ form = $(form);
3508
+ Form.getElements(form).invoke('enable');
3509
+ return form;
3510
+ },
3511
+
3512
+ findFirstElement: function(form) {
3513
+ var elements = $(form).getElements().findAll(function(element) {
3514
+ return 'hidden' != element.type && !element.disabled;
3515
+ });
3516
+ var firstByIndex = elements.findAll(function(element) {
3517
+ return element.hasAttribute('tabIndex') && element.tabIndex >= 0;
3518
+ }).sortBy(function(element) { return element.tabIndex }).first();
3519
+
3520
+ return firstByIndex ? firstByIndex : elements.find(function(element) {
3521
+ return ['input', 'select', 'textarea'].include(element.tagName.toLowerCase());
3522
+ });
3523
+ },
3524
+
3525
+ focusFirstElement: function(form) {
3526
+ form = $(form);
3527
+ form.findFirstElement().activate();
3528
+ return form;
3529
+ },
3530
+
3531
+ request: function(form, options) {
3532
+ form = $(form), options = Object.clone(options || { });
3533
+
3534
+ var params = options.parameters, action = form.readAttribute('action') || '';
3535
+ if (action.blank()) action = window.location.href;
3536
+ options.parameters = form.serialize(true);
3537
+
3538
+ if (params) {
3539
+ if (Object.isString(params)) params = params.toQueryParams();
3540
+ Object.extend(options.parameters, params);
3541
+ }
3542
+
3543
+ if (form.hasAttribute('method') && !options.method)
3544
+ options.method = form.method;
3545
+
3546
+ return new Ajax.Request(action, options);
3547
+ }
3548
+ };
3549
+
3550
+ /*--------------------------------------------------------------------------*/
3551
+
3552
+ Form.Element = {
3553
+ focus: function(element) {
3554
+ $(element).focus();
3555
+ return element;
3556
+ },
3557
+
3558
+ select: function(element) {
3559
+ $(element).select();
3560
+ return element;
3561
+ }
3562
+ };
3563
+
3564
+ Form.Element.Methods = {
3565
+ serialize: function(element) {
3566
+ element = $(element);
3567
+ if (!element.disabled && element.name) {
3568
+ var value = element.getValue();
3569
+ if (value != undefined) {
3570
+ var pair = { };
3571
+ pair[element.name] = value;
3572
+ return Object.toQueryString(pair);
3573
+ }
3574
+ }
3575
+ return '';
3576
+ },
3577
+
3578
+ getValue: function(element) {
3579
+ element = $(element);
3580
+ var method = element.tagName.toLowerCase();
3581
+ return Form.Element.Serializers[method](element);
3582
+ },
3583
+
3584
+ setValue: function(element, value) {
3585
+ element = $(element);
3586
+ var method = element.tagName.toLowerCase();
3587
+ Form.Element.Serializers[method](element, value);
3588
+ return element;
3589
+ },
3590
+
3591
+ clear: function(element) {
3592
+ $(element).value = '';
3593
+ return element;
3594
+ },
3595
+
3596
+ present: function(element) {
3597
+ return $(element).value != '';
3598
+ },
3599
+
3600
+ activate: function(element) {
3601
+ element = $(element);
3602
+ try {
3603
+ element.focus();
3604
+ if (element.select && (element.tagName.toLowerCase() != 'input' ||
3605
+ !['button', 'reset', 'submit'].include(element.type)))
3606
+ element.select();
3607
+ } catch (e) { }
3608
+ return element;
3609
+ },
3610
+
3611
+ disable: function(element) {
3612
+ element = $(element);
3613
+ element.disabled = true;
3614
+ return element;
3615
+ },
3616
+
3617
+ enable: function(element) {
3618
+ element = $(element);
3619
+ element.disabled = false;
3620
+ return element;
3621
+ }
3622
+ };
3623
+
3624
+ /*--------------------------------------------------------------------------*/
3625
+
3626
+ var Field = Form.Element;
3627
+ var $F = Form.Element.Methods.getValue;
3628
+
3629
+ /*--------------------------------------------------------------------------*/
3630
+
3631
+ Form.Element.Serializers = {
3632
+ input: function(element, value) {
3633
+ switch (element.type.toLowerCase()) {
3634
+ case 'checkbox':
3635
+ case 'radio':
3636
+ return Form.Element.Serializers.inputSelector(element, value);
3637
+ default:
3638
+ return Form.Element.Serializers.textarea(element, value);
3639
+ }
3640
+ },
3641
+
3642
+ inputSelector: function(element, value) {
3643
+ if (Object.isUndefined(value)) return element.checked ? element.value : null;
3644
+ else element.checked = !!value;
3645
+ },
3646
+
3647
+ textarea: function(element, value) {
3648
+ if (Object.isUndefined(value)) return element.value;
3649
+ else element.value = value;
3650
+ },
3651
+
3652
+ select: function(element, value) {
3653
+ if (Object.isUndefined(value))
3654
+ return this[element.type == 'select-one' ?
3655
+ 'selectOne' : 'selectMany'](element);
3656
+ else {
3657
+ var opt, currentValue, single = !Object.isArray(value);
3658
+ for (var i = 0, length = element.length; i < length; i++) {
3659
+ opt = element.options[i];
3660
+ currentValue = this.optionValue(opt);
3661
+ if (single) {
3662
+ if (currentValue == value) {
3663
+ opt.selected = true;
3664
+ return;
3665
+ }
3666
+ }
3667
+ else opt.selected = value.include(currentValue);
3668
+ }
3669
+ }
3670
+ },
3671
+
3672
+ selectOne: function(element) {
3673
+ var index = element.selectedIndex;
3674
+ return index >= 0 ? this.optionValue(element.options[index]) : null;
3675
+ },
3676
+
3677
+ selectMany: function(element) {
3678
+ var values, length = element.length;
3679
+ if (!length) return null;
3680
+
3681
+ for (var i = 0, values = []; i < length; i++) {
3682
+ var opt = element.options[i];
3683
+ if (opt.selected) values.push(this.optionValue(opt));
3684
+ }
3685
+ return values;
3686
+ },
3687
+
3688
+ optionValue: function(opt) {
3689
+ // extend element because hasAttribute may not be native
3690
+ return Element.extend(opt).hasAttribute('value') ? opt.value : opt.text;
3691
+ }
3692
+ };
3693
+
3694
+ /*--------------------------------------------------------------------------*/
3695
+
3696
+ Abstract.TimedObserver = Class.create(PeriodicalExecuter, {
3697
+ initialize: function($super, element, frequency, callback) {
3698
+ $super(callback, frequency);
3699
+ this.element = $(element);
3700
+ this.lastValue = this.getValue();
3701
+ },
3702
+
3703
+ execute: function() {
3704
+ var value = this.getValue();
3705
+ if (Object.isString(this.lastValue) && Object.isString(value) ?
3706
+ this.lastValue != value : String(this.lastValue) != String(value)) {
3707
+ this.callback(this.element, value);
3708
+ this.lastValue = value;
3709
+ }
3710
+ }
3711
+ });
3712
+
3713
+ Form.Element.Observer = Class.create(Abstract.TimedObserver, {
3714
+ getValue: function() {
3715
+ return Form.Element.getValue(this.element);
3716
+ }
3717
+ });
3718
+
3719
+ Form.Observer = Class.create(Abstract.TimedObserver, {
3720
+ getValue: function() {
3721
+ return Form.serialize(this.element);
3722
+ }
3723
+ });
3724
+
3725
+ /*--------------------------------------------------------------------------*/
3726
+
3727
+ Abstract.EventObserver = Class.create({
3728
+ initialize: function(element, callback) {
3729
+ this.element = $(element);
3730
+ this.callback = callback;
3731
+
3732
+ this.lastValue = this.getValue();
3733
+ if (this.element.tagName.toLowerCase() == 'form')
3734
+ this.registerFormCallbacks();
3735
+ else
3736
+ this.registerCallback(this.element);
3737
+ },
3738
+
3739
+ onElementEvent: function() {
3740
+ var value = this.getValue();
3741
+ if (this.lastValue != value) {
3742
+ this.callback(this.element, value);
3743
+ this.lastValue = value;
3744
+ }
3745
+ },
3746
+
3747
+ registerFormCallbacks: function() {
3748
+ Form.getElements(this.element).each(this.registerCallback, this);
3749
+ },
3750
+
3751
+ registerCallback: function(element) {
3752
+ if (element.type) {
3753
+ switch (element.type.toLowerCase()) {
3754
+ case 'checkbox':
3755
+ case 'radio':
3756
+ Event.observe(element, 'click', this.onElementEvent.bind(this));
3757
+ break;
3758
+ default:
3759
+ Event.observe(element, 'change', this.onElementEvent.bind(this));
3760
+ break;
3761
+ }
3762
+ }
3763
+ }
3764
+ });
3765
+
3766
+ Form.Element.EventObserver = Class.create(Abstract.EventObserver, {
3767
+ getValue: function() {
3768
+ return Form.Element.getValue(this.element);
3769
+ }
3770
+ });
3771
+
3772
+ Form.EventObserver = Class.create(Abstract.EventObserver, {
3773
+ getValue: function() {
3774
+ return Form.serialize(this.element);
3775
+ }
3776
+ });
3777
+ if (!window.Event) var Event = { };
3778
+
3779
+ Object.extend(Event, {
3780
+ KEY_BACKSPACE: 8,
3781
+ KEY_TAB: 9,
3782
+ KEY_RETURN: 13,
3783
+ KEY_ESC: 27,
3784
+ KEY_LEFT: 37,
3785
+ KEY_UP: 38,
3786
+ KEY_RIGHT: 39,
3787
+ KEY_DOWN: 40,
3788
+ KEY_DELETE: 46,
3789
+ KEY_HOME: 36,
3790
+ KEY_END: 35,
3791
+ KEY_PAGEUP: 33,
3792
+ KEY_PAGEDOWN: 34,
3793
+ KEY_INSERT: 45,
3794
+
3795
+ cache: { },
3796
+
3797
+ relatedTarget: function(event) {
3798
+ var element;
3799
+ switch(event.type) {
3800
+ case 'mouseover': element = event.fromElement; break;
3801
+ case 'mouseout': element = event.toElement; break;
3802
+ default: return null;
3803
+ }
3804
+ return Element.extend(element);
3805
+ }
3806
+ });
3807
+
3808
+ Event.Methods = (function() {
3809
+ var isButton;
3810
+
3811
+ if (Prototype.Browser.IE) {
3812
+ var buttonMap = { 0: 1, 1: 4, 2: 2 };
3813
+ isButton = function(event, code) {
3814
+ return event.button == buttonMap[code];
3815
+ };
3816
+
3817
+ } else if (Prototype.Browser.WebKit) {
3818
+ isButton = function(event, code) {
3819
+ switch (code) {
3820
+ case 0: return event.which == 1 && !event.metaKey;
3821
+ case 1: return event.which == 1 && event.metaKey;
3822
+ default: return false;
3823
+ }
3824
+ };
3825
+
3826
+ } else {
3827
+ isButton = function(event, code) {
3828
+ return event.which ? (event.which === code + 1) : (event.button === code);
3829
+ };
3830
+ }
3831
+
3832
+ return {
3833
+ isLeftClick: function(event) { return isButton(event, 0) },
3834
+ isMiddleClick: function(event) { return isButton(event, 1) },
3835
+ isRightClick: function(event) { return isButton(event, 2) },
3836
+
3837
+ element: function(event) {
3838
+ event = Event.extend(event);
3839
+
3840
+ var node = event.target,
3841
+ type = event.type,
3842
+ currentTarget = event.currentTarget;
3843
+
3844
+ if (currentTarget && currentTarget.tagName) {
3845
+ // Firefox screws up the "click" event when moving between radio buttons
3846
+ // via arrow keys. It also screws up the "load" and "error" events on images,
3847
+ // reporting the document as the target instead of the original image.
3848
+ if (type === 'load' || type === 'error' ||
3849
+ (type === 'click' && currentTarget.tagName.toLowerCase() === 'input'
3850
+ && currentTarget.type === 'radio'))
3851
+ node = currentTarget;
3852
+ }
3853
+ if (node.nodeType == Node.TEXT_NODE) node = node.parentNode;
3854
+ return Element.extend(node);
3855
+ },
3856
+
3857
+ findElement: function(event, expression) {
3858
+ var element = Event.element(event);
3859
+ if (!expression) return element;
3860
+ var elements = [element].concat(element.ancestors());
3861
+ return Selector.findElement(elements, expression, 0);
3862
+ },
3863
+
3864
+ pointer: function(event) {
3865
+ var docElement = document.documentElement,
3866
+ body = document.body || { scrollLeft: 0, scrollTop: 0 };
3867
+ return {
3868
+ x: event.pageX || (event.clientX +
3869
+ (docElement.scrollLeft || body.scrollLeft) -
3870
+ (docElement.clientLeft || 0)),
3871
+ y: event.pageY || (event.clientY +
3872
+ (docElement.scrollTop || body.scrollTop) -
3873
+ (docElement.clientTop || 0))
3874
+ };
3875
+ },
3876
+
3877
+ pointerX: function(event) { return Event.pointer(event).x },
3878
+ pointerY: function(event) { return Event.pointer(event).y },
3879
+
3880
+ stop: function(event) {
3881
+ Event.extend(event);
3882
+ event.preventDefault();
3883
+ event.stopPropagation();
3884
+ event.stopped = true;
3885
+ }
3886
+ };
3887
+ })();
3888
+
3889
+ Event.extend = (function() {
3890
+ var methods = Object.keys(Event.Methods).inject({ }, function(m, name) {
3891
+ m[name] = Event.Methods[name].methodize();
3892
+ return m;
3893
+ });
3894
+
3895
+ if (Prototype.Browser.IE) {
3896
+ Object.extend(methods, {
3897
+ stopPropagation: function() { this.cancelBubble = true },
3898
+ preventDefault: function() { this.returnValue = false },
3899
+ inspect: function() { return "[object Event]" }
3900
+ });
3901
+
3902
+ return function(event) {
3903
+ if (!event) return false;
3904
+ if (event._extendedByPrototype) return event;
3905
+
3906
+ event._extendedByPrototype = Prototype.emptyFunction;
3907
+ var pointer = Event.pointer(event);
3908
+ Object.extend(event, {
3909
+ target: event.srcElement,
3910
+ relatedTarget: Event.relatedTarget(event),
3911
+ pageX: pointer.x,
3912
+ pageY: pointer.y
3913
+ });
3914
+ return Object.extend(event, methods);
3915
+ };
3916
+
3917
+ } else {
3918
+ Event.prototype = Event.prototype || document.createEvent("HTMLEvents")['__proto__'];
3919
+ Object.extend(Event.prototype, methods);
3920
+ return Prototype.K;
3921
+ }
3922
+ })();
3923
+
3924
+ Object.extend(Event, (function() {
3925
+ var cache = Event.cache;
3926
+
3927
+ function getEventID(element) {
3928
+ if (element._prototypeEventID) return element._prototypeEventID[0];
3929
+ arguments.callee.id = arguments.callee.id || 1;
3930
+ return element._prototypeEventID = [++arguments.callee.id];
3931
+ }
3932
+
3933
+ function getDOMEventName(eventName) {
3934
+ if (eventName && eventName.include(':')) return "dataavailable";
3935
+ return eventName;
3936
+ }
3937
+
3938
+ function getCacheForID(id) {
3939
+ return cache[id] = cache[id] || { };
3940
+ }
3941
+
3942
+ function getWrappersForEventName(id, eventName) {
3943
+ var c = getCacheForID(id);
3944
+ return c[eventName] = c[eventName] || [];
3945
+ }
3946
+
3947
+ function createWrapper(element, eventName, handler) {
3948
+ var id = getEventID(element);
3949
+ var c = getWrappersForEventName(id, eventName);
3950
+ if (c.pluck("handler").include(handler)) return false;
3951
+
3952
+ var wrapper = function(event) {
3953
+ if (!Event || !Event.extend ||
3954
+ (event.eventName && event.eventName != eventName))
3955
+ return false;
3956
+
3957
+ Event.extend(event);
3958
+ handler.call(element, event);
3959
+ };
3960
+
3961
+ wrapper.handler = handler;
3962
+ c.push(wrapper);
3963
+ return wrapper;
3964
+ }
3965
+
3966
+ function findWrapper(id, eventName, handler) {
3967
+ var c = getWrappersForEventName(id, eventName);
3968
+ return c.find(function(wrapper) { return wrapper.handler == handler });
3969
+ }
3970
+
3971
+ function destroyWrapper(id, eventName, handler) {
3972
+ var c = getCacheForID(id);
3973
+ if (!c[eventName]) return false;
3974
+ c[eventName] = c[eventName].without(findWrapper(id, eventName, handler));
3975
+ }
3976
+
3977
+ function destroyCache() {
3978
+ for (var id in cache)
3979
+ for (var eventName in cache[id])
3980
+ cache[id][eventName] = null;
3981
+ }
3982
+
3983
+
3984
+ // Internet Explorer needs to remove event handlers on page unload
3985
+ // in order to avoid memory leaks.
3986
+ if (window.attachEvent) {
3987
+ window.attachEvent("onunload", destroyCache);
3988
+ }
3989
+
3990
+ // Safari has a dummy event handler on page unload so that it won't
3991
+ // use its bfcache. Safari <= 3.1 has an issue with restoring the "document"
3992
+ // object when page is returned to via the back button using its bfcache.
3993
+ if (Prototype.Browser.WebKit) {
3994
+ window.addEventListener('unload', Prototype.emptyFunction, false);
3995
+ }
3996
+
3997
+ return {
3998
+ observe: function(element, eventName, handler, onCapture) {
3999
+ element = $(element);
4000
+ var name = getDOMEventName(eventName);
4001
+ element.addEventListener(name, handler, onCapture);
4002
+
4003
+ return element;
4004
+ },
4005
+
4006
+ stopObserving: function(element, eventName, handler, onCapture) {
4007
+ element = $(element);
4008
+ var name = getDOMEventName(eventName);
4009
+ element.removeEventListener(name, handler, onCapture);
4010
+
4011
+ return element;
4012
+ },
4013
+
4014
+ fire: function(element, eventName, memo) {
4015
+ element = $(element);
4016
+ if (element == document && document.createEvent && !element.dispatchEvent)
4017
+ element = document.documentElement;
4018
+
4019
+ var event;
4020
+ if (document.createEvent) {
4021
+ event = document.createEvent("HTMLEvents");
4022
+ event.initEvent("dataavailable", true, true);
4023
+ } else {
4024
+ event = document.createEventObject();
4025
+ event.eventType = "ondataavailable";
4026
+ }
4027
+
4028
+ event.eventName = eventName;
4029
+ event.memo = memo || { };
4030
+
4031
+ if (document.createEvent) {
4032
+ element.dispatchEvent(event);
4033
+ } else {
4034
+ element.fireEvent(event.eventType, event);
4035
+ }
4036
+
4037
+ return Event.extend(event);
4038
+ }
4039
+ };
4040
+ })());
4041
+
4042
+ Object.extend(Event, Event.Methods);
4043
+
4044
+ Element.addMethods({
4045
+ fire: Event.fire,
4046
+ observe: Event.observe,
4047
+ stopObserving: Event.stopObserving
4048
+ });
4049
+
4050
+ Object.extend(document, {
4051
+ fire: Element.Methods.fire.methodize(),
4052
+ observe: Element.Methods.observe.methodize(),
4053
+ stopObserving: Element.Methods.stopObserving.methodize(),
4054
+ loaded: false
4055
+ });
4056
+
4057
+ (function() {
4058
+ /* Support for the DOMContentLoaded event is based on work by Dan Webb,
4059
+ Matthias Miller, Dean Edwards and John Resig. */
4060
+
4061
+ var timer;
4062
+
4063
+ function fireContentLoadedEvent() {
4064
+ if (document.loaded) return;
4065
+ if (timer) window.clearInterval(timer);
4066
+ document.fire("dom:loaded");
4067
+ document.loaded = true;
4068
+ }
4069
+
4070
+ if (document.addEventListener) {
4071
+ if (Prototype.Browser.WebKit) {
4072
+ timer = window.setInterval(function() {
4073
+ if (/loaded|complete/.test(document.readyState))
4074
+ fireContentLoadedEvent();
4075
+ }, 0);
4076
+
4077
+ Event.observe(window, "load", fireContentLoadedEvent);
4078
+
4079
+ } else {
4080
+ document.addEventListener("DOMContentLoaded",
4081
+ fireContentLoadedEvent, false);
4082
+ }
4083
+
4084
+ } else {
4085
+ document.write("<script id=__onDOMContentLoaded defer src=//:><\/script>");
4086
+ $("__onDOMContentLoaded").onreadystatechange = function() {
4087
+ if (this.readyState == "complete") {
4088
+ this.onreadystatechange = null;
4089
+ fireContentLoadedEvent();
4090
+ }
4091
+ };
4092
+ }
4093
+ })();
4094
+ /*------------------------------- DEPRECATED -------------------------------*/
4095
+
4096
+ Hash.toQueryString = Object.toQueryString;
4097
+
4098
+ var Toggle = { display: Element.toggle };
4099
+
4100
+ Element.Methods.childOf = Element.Methods.descendantOf;
4101
+
4102
+ var Insertion = {
4103
+ Before: function(element, content) {
4104
+ return Element.insert(element, {before:content});
4105
+ },
4106
+
4107
+ Top: function(element, content) {
4108
+ return Element.insert(element, {top:content});
4109
+ },
4110
+
4111
+ Bottom: function(element, content) {
4112
+ return Element.insert(element, {bottom:content});
4113
+ },
4114
+
4115
+ After: function(element, content) {
4116
+ return Element.insert(element, {after:content});
4117
+ }
4118
+ };
4119
+
4120
+ var $continue = new Error('"throw $continue" is deprecated, use "return" instead');
4121
+
4122
+ // This should be moved to script.aculo.us; notice the deprecated methods
4123
+ // further below, that map to the newer Element methods.
4124
+ var Position = {
4125
+ // set to true if needed, warning: firefox performance problems
4126
+ // NOT neeeded for page scrolling, only if draggable contained in
4127
+ // scrollable elements
4128
+ includeScrollOffsets: false,
4129
+
4130
+ // must be called before calling withinIncludingScrolloffset, every time the
4131
+ // page is scrolled
4132
+ prepare: function() {
4133
+ this.deltaX = window.pageXOffset
4134
+ || document.documentElement.scrollLeft
4135
+ || document.body.scrollLeft
4136
+ || 0;
4137
+ this.deltaY = window.pageYOffset
4138
+ || document.documentElement.scrollTop
4139
+ || document.body.scrollTop
4140
+ || 0;
4141
+ },
4142
+
4143
+ // caches x/y coordinate pair to use with overlap
4144
+ within: function(element, x, y) {
4145
+ if (this.includeScrollOffsets)
4146
+ return this.withinIncludingScrolloffsets(element, x, y);
4147
+ this.xcomp = x;
4148
+ this.ycomp = y;
4149
+ this.offset = Element.cumulativeOffset(element);
4150
+
4151
+ return (y >= this.offset[1] &&
4152
+ y < this.offset[1] + element.offsetHeight &&
4153
+ x >= this.offset[0] &&
4154
+ x < this.offset[0] + element.offsetWidth);
4155
+ },
4156
+
4157
+ withinIncludingScrolloffsets: function(element, x, y) {
4158
+ var offsetcache = Element.cumulativeScrollOffset(element);
4159
+
4160
+ this.xcomp = x + offsetcache[0] - this.deltaX;
4161
+ this.ycomp = y + offsetcache[1] - this.deltaY;
4162
+ this.offset = Element.cumulativeOffset(element);
4163
+
4164
+ return (this.ycomp >= this.offset[1] &&
4165
+ this.ycomp < this.offset[1] + element.offsetHeight &&
4166
+ this.xcomp >= this.offset[0] &&
4167
+ this.xcomp < this.offset[0] + element.offsetWidth);
4168
+ },
4169
+
4170
+ // within must be called directly before
4171
+ overlap: function(mode, element) {
4172
+ if (!mode) return 0;
4173
+ if (mode == 'vertical')
4174
+ return ((this.offset[1] + element.offsetHeight) - this.ycomp) /
4175
+ element.offsetHeight;
4176
+ if (mode == 'horizontal')
4177
+ return ((this.offset[0] + element.offsetWidth) - this.xcomp) /
4178
+ element.offsetWidth;
4179
+ },
4180
+
4181
+ // Deprecation layer -- use newer Element methods now (1.5.2).
4182
+
4183
+ cumulativeOffset: Element.Methods.cumulativeOffset,
4184
+
4185
+ positionedOffset: Element.Methods.positionedOffset,
4186
+
4187
+ absolutize: function(element) {
4188
+ Position.prepare();
4189
+ return Element.absolutize(element);
4190
+ },
4191
+
4192
+ relativize: function(element) {
4193
+ Position.prepare();
4194
+ return Element.relativize(element);
4195
+ },
4196
+
4197
+ realOffset: Element.Methods.cumulativeScrollOffset,
4198
+
4199
+ offsetParent: Element.Methods.getOffsetParent,
4200
+
4201
+ page: Element.Methods.viewportOffset,
4202
+
4203
+ clone: function(source, target, options) {
4204
+ options = options || { };
4205
+ return Element.clonePosition(target, source, options);
4206
+ }
4207
+ };
4208
+
4209
+ /*--------------------------------------------------------------------------*/
4210
+
4211
+ if (!document.getElementsByClassName) document.getElementsByClassName = function(instanceMethods){
4212
+ function iter(name) {
4213
+ return name.blank() ? null : "[contains(concat(' ', @class, ' '), ' " + name + " ')]";
4214
+ }
4215
+
4216
+ instanceMethods.getElementsByClassName = Prototype.BrowserFeatures.XPath ?
4217
+ function(element, className) {
4218
+ className = className.toString().strip();
4219
+ var cond = /\s/.test(className) ? $w(className).map(iter).join('') : iter(className);
4220
+ return cond ? document._getElementsByXPath('.//*' + cond, element) : [];
4221
+ } : function(element, className) {
4222
+ className = className.toString().strip();
4223
+ var elements = [], classNames = (/\s/.test(className) ? $w(className) : null);
4224
+ if (!classNames && !className) return elements;
4225
+
4226
+ var nodes = $(element).getElementsByTagName('*');
4227
+ className = ' ' + className + ' ';
4228
+
4229
+ for (var i = 0, child, cn; child = nodes[i]; i++) {
4230
+ if (child.className && (cn = ' ' + child.className + ' ') && (cn.include(className) ||
4231
+ (classNames && classNames.all(function(name) {
4232
+ return !name.toString().blank() && cn.include(' ' + name + ' ');
4233
+ }))))
4234
+ elements.push(Element.extend(child));
4235
+ }
4236
+ return elements;
4237
+ };
4238
+
4239
+ return function(className, parentElement) {
4240
+ return $(parentElement || document.body).getElementsByClassName(className);
4241
+ };
4242
+ }(Element.Methods);
4243
+
4244
+ /*--------------------------------------------------------------------------*/
4245
+
4246
+ Element.ClassNames = Class.create();
4247
+ Element.ClassNames.prototype = {
4248
+ initialize: function(element) {
4249
+ this.element = $(element);
4250
+ },
4251
+
4252
+ _each: function(iterator) {
4253
+ this.element.className.split(/\s+/).select(function(name) {
4254
+ return name.length > 0;
4255
+ })._each(iterator);
4256
+ },
4257
+
4258
+ set: function(className) {
4259
+ this.element.className = className;
4260
+ },
4261
+
4262
+ add: function(classNameToAdd) {
4263
+ if (this.include(classNameToAdd)) return;
4264
+ this.set($A(this).concat(classNameToAdd).join(' '));
4265
+ },
4266
+
4267
+ remove: function(classNameToRemove) {
4268
+ if (!this.include(classNameToRemove)) return;
4269
+ this.set($A(this).without(classNameToRemove).join(' '));
4270
+ },
4271
+
4272
+ toString: function() {
4273
+ return $A(this).join(' ');
4274
+ }
4275
+ };
4276
+
4277
+ Object.extend(Element.ClassNames.prototype, Enumerable);
4278
+
4279
+ /*--------------------------------------------------------------------------*/
4280
+
4281
+ Element.addMethods();