Description:
more updated rails git-svn-id: http://theory.cpe.ku.ac.th/grader/web/trunk@360 6386c4cd-e34a-4fa8-8920-d93eb39b512e
Commit status:
[Not Reviewed]
References:
Comments:
0 Commit comments 0 Inline Comments
Unresolved TODOs:
There are no unresolved TODOs
Add another comment

r163:74e3afe899a3 - - 5 files changed: 433 inserted, 328 deleted

@@ -1,109 +1,110
1 # Don't change this file!
1 # Don't change this file!
2 # Configure your app in config/environment.rb and config/environments/*.rb
2 # Configure your app in config/environment.rb and config/environments/*.rb
3
3
4 RAILS_ROOT = "#{File.dirname(__FILE__)}/.." unless defined?(RAILS_ROOT)
4 RAILS_ROOT = "#{File.dirname(__FILE__)}/.." unless defined?(RAILS_ROOT)
5
5
6 module Rails
6 module Rails
7 class << self
7 class << self
8 def boot!
8 def boot!
9 unless booted?
9 unless booted?
10 preinitialize
10 preinitialize
11 pick_boot.run
11 pick_boot.run
12 end
12 end
13 end
13 end
14
14
15 def booted?
15 def booted?
16 defined? Rails::Initializer
16 defined? Rails::Initializer
17 end
17 end
18
18
19 def pick_boot
19 def pick_boot
20 (vendor_rails? ? VendorBoot : GemBoot).new
20 (vendor_rails? ? VendorBoot : GemBoot).new
21 end
21 end
22
22
23 def vendor_rails?
23 def vendor_rails?
24 File.exist?("#{RAILS_ROOT}/vendor/rails")
24 File.exist?("#{RAILS_ROOT}/vendor/rails")
25 end
25 end
26
26
27 def preinitialize
27 def preinitialize
28 load(preinitializer_path) if File.exist?(preinitializer_path)
28 load(preinitializer_path) if File.exist?(preinitializer_path)
29 end
29 end
30
30
31 def preinitializer_path
31 def preinitializer_path
32 "#{RAILS_ROOT}/config/preinitializer.rb"
32 "#{RAILS_ROOT}/config/preinitializer.rb"
33 end
33 end
34 end
34 end
35
35
36 class Boot
36 class Boot
37 def run
37 def run
38 load_initializer
38 load_initializer
39 Rails::Initializer.run(:set_load_path)
39 Rails::Initializer.run(:set_load_path)
40 end
40 end
41 end
41 end
42
42
43 class VendorBoot < Boot
43 class VendorBoot < Boot
44 def load_initializer
44 def load_initializer
45 require "#{RAILS_ROOT}/vendor/rails/railties/lib/initializer"
45 require "#{RAILS_ROOT}/vendor/rails/railties/lib/initializer"
46 Rails::Initializer.run(:install_gem_spec_stubs)
46 Rails::Initializer.run(:install_gem_spec_stubs)
47 + Rails::GemDependency.add_frozen_gem_path
47 end
48 end
48 end
49 end
49
50
50 class GemBoot < Boot
51 class GemBoot < Boot
51 def load_initializer
52 def load_initializer
52 self.class.load_rubygems
53 self.class.load_rubygems
53 load_rails_gem
54 load_rails_gem
54 require 'initializer'
55 require 'initializer'
55 end
56 end
56
57
57 def load_rails_gem
58 def load_rails_gem
58 if version = self.class.gem_version
59 if version = self.class.gem_version
59 gem 'rails', version
60 gem 'rails', version
60 else
61 else
61 gem 'rails'
62 gem 'rails'
62 end
63 end
63 rescue Gem::LoadError => load_error
64 rescue Gem::LoadError => load_error
64 $stderr.puts %(Missing the Rails #{version} gem. Please `gem install -v=#{version} rails`, update your RAILS_GEM_VERSION setting in config/environment.rb for the Rails version you do have installed, or comment out RAILS_GEM_VERSION to use the latest version installed.)
65 $stderr.puts %(Missing the Rails #{version} gem. Please `gem install -v=#{version} rails`, update your RAILS_GEM_VERSION setting in config/environment.rb for the Rails version you do have installed, or comment out RAILS_GEM_VERSION to use the latest version installed.)
65 exit 1
66 exit 1
66 end
67 end
67
68
68 class << self
69 class << self
69 def rubygems_version
70 def rubygems_version
70 - Gem::RubyGemsVersion if defined? Gem::RubyGemsVersion
71 + Gem::RubyGemsVersion rescue nil
71 end
72 end
72
73
73 def gem_version
74 def gem_version
74 if defined? RAILS_GEM_VERSION
75 if defined? RAILS_GEM_VERSION
75 RAILS_GEM_VERSION
76 RAILS_GEM_VERSION
76 elsif ENV.include?('RAILS_GEM_VERSION')
77 elsif ENV.include?('RAILS_GEM_VERSION')
77 ENV['RAILS_GEM_VERSION']
78 ENV['RAILS_GEM_VERSION']
78 else
79 else
79 parse_gem_version(read_environment_rb)
80 parse_gem_version(read_environment_rb)
80 end
81 end
81 end
82 end
82
83
83 def load_rubygems
84 def load_rubygems
84 require 'rubygems'
85 require 'rubygems'
85 - min_version = '1.1.1'
86 + min_version = '1.3.1'
86 unless rubygems_version >= min_version
87 unless rubygems_version >= min_version
87 $stderr.puts %Q(Rails requires RubyGems >= #{min_version} (you have #{rubygems_version}). Please `gem update --system` and try again.)
88 $stderr.puts %Q(Rails requires RubyGems >= #{min_version} (you have #{rubygems_version}). Please `gem update --system` and try again.)
88 exit 1
89 exit 1
89 end
90 end
90
91
91 rescue LoadError
92 rescue LoadError
92 $stderr.puts %Q(Rails requires RubyGems >= #{min_version}. Please install RubyGems and try again: http://rubygems.rubyforge.org)
93 $stderr.puts %Q(Rails requires RubyGems >= #{min_version}. Please install RubyGems and try again: http://rubygems.rubyforge.org)
93 exit 1
94 exit 1
94 end
95 end
95
96
96 def parse_gem_version(text)
97 def parse_gem_version(text)
97 $1 if text =~ /^[^#]*RAILS_GEM_VERSION\s*=\s*["']([!~<>=]*\s*[\d.]+)["']/
98 $1 if text =~ /^[^#]*RAILS_GEM_VERSION\s*=\s*["']([!~<>=]*\s*[\d.]+)["']/
98 end
99 end
99
100
100 private
101 private
101 def read_environment_rb
102 def read_environment_rb
102 File.read("#{RAILS_ROOT}/config/environment.rb")
103 File.read("#{RAILS_ROOT}/config/environment.rb")
103 end
104 end
104 end
105 end
105 end
106 end
106 end
107 end
107
108
108 # All that for this:
109 # All that for this:
109 Rails.boot!
110 Rails.boot!
@@ -1,91 +1,91
1 // Copyright (c) 2005-2008 Thomas Fuchs (http://script.aculo.us, http://mir.aculo.us)
1 // Copyright (c) 2005-2008 Thomas Fuchs (http://script.aculo.us, http://mir.aculo.us)
2 - // (c) 2005-2007 Ivan Krstic (http://blogs.law.harvard.edu/ivan)
2 + // (c) 2005-2008 Ivan Krstic (http://blogs.law.harvard.edu/ivan)
3 - // (c) 2005-2007 Jon Tirsen (http://www.tirsen.com)
3 + // (c) 2005-2008 Jon Tirsen (http://www.tirsen.com)
4 // Contributors:
4 // Contributors:
5 // Richard Livsey
5 // Richard Livsey
6 // Rahul Bhargava
6 // Rahul Bhargava
7 // Rob Wills
7 // Rob Wills
8 //
8 //
9 // script.aculo.us is freely distributable under the terms of an MIT-style license.
9 // script.aculo.us is freely distributable under the terms of an MIT-style license.
10 // For details, see the script.aculo.us web site: http://script.aculo.us/
10 // For details, see the script.aculo.us web site: http://script.aculo.us/
11
11
12 // Autocompleter.Base handles all the autocompletion functionality
12 // Autocompleter.Base handles all the autocompletion functionality
13 // that's independent of the data source for autocompletion. This
13 // that's independent of the data source for autocompletion. This
14 // includes drawing the autocompletion menu, observing keyboard
14 // includes drawing the autocompletion menu, observing keyboard
15 // and mouse events, and similar.
15 // and mouse events, and similar.
16 //
16 //
17 // Specific autocompleters need to provide, at the very least,
17 // Specific autocompleters need to provide, at the very least,
18 // a getUpdatedChoices function that will be invoked every time
18 // a getUpdatedChoices function that will be invoked every time
19 // the text inside the monitored textbox changes. This method
19 // the text inside the monitored textbox changes. This method
20 // should get the text for which to provide autocompletion by
20 // should get the text for which to provide autocompletion by
21 // invoking this.getToken(), NOT by directly accessing
21 // invoking this.getToken(), NOT by directly accessing
22 // this.element.value. This is to allow incremental tokenized
22 // this.element.value. This is to allow incremental tokenized
23 // autocompletion. Specific auto-completion logic (AJAX, etc)
23 // autocompletion. Specific auto-completion logic (AJAX, etc)
24 // belongs in getUpdatedChoices.
24 // belongs in getUpdatedChoices.
25 //
25 //
26 // Tokenized incremental autocompletion is enabled automatically
26 // Tokenized incremental autocompletion is enabled automatically
27 // when an autocompleter is instantiated with the 'tokens' option
27 // when an autocompleter is instantiated with the 'tokens' option
28 // in the options parameter, e.g.:
28 // in the options parameter, e.g.:
29 // new Ajax.Autocompleter('id','upd', '/url/', { tokens: ',' });
29 // new Ajax.Autocompleter('id','upd', '/url/', { tokens: ',' });
30 // will incrementally autocomplete with a comma as the token.
30 // will incrementally autocomplete with a comma as the token.
31 // Additionally, ',' in the above example can be replaced with
31 // Additionally, ',' in the above example can be replaced with
32 // a token array, e.g. { tokens: [',', '\n'] } which
32 // a token array, e.g. { tokens: [',', '\n'] } which
33 // enables autocompletion on multiple tokens. This is most
33 // enables autocompletion on multiple tokens. This is most
34 // useful when one of the tokens is \n (a newline), as it
34 // useful when one of the tokens is \n (a newline), as it
35 // allows smart autocompletion after linebreaks.
35 // allows smart autocompletion after linebreaks.
36
36
37 if(typeof Effect == 'undefined')
37 if(typeof Effect == 'undefined')
38 throw("controls.js requires including script.aculo.us' effects.js library");
38 throw("controls.js requires including script.aculo.us' effects.js library");
39
39
40 - var Autocompleter = { }
40 + var Autocompleter = { };
41 Autocompleter.Base = Class.create({
41 Autocompleter.Base = Class.create({
42 baseInitialize: function(element, update, options) {
42 baseInitialize: function(element, update, options) {
43 - element = $(element)
43 + element = $(element);
44 this.element = element;
44 this.element = element;
45 this.update = $(update);
45 this.update = $(update);
46 this.hasFocus = false;
46 this.hasFocus = false;
47 this.changed = false;
47 this.changed = false;
48 this.active = false;
48 this.active = false;
49 this.index = 0;
49 this.index = 0;
50 this.entryCount = 0;
50 this.entryCount = 0;
51 this.oldElementValue = this.element.value;
51 this.oldElementValue = this.element.value;
52
52
53 if(this.setOptions)
53 if(this.setOptions)
54 this.setOptions(options);
54 this.setOptions(options);
55 else
55 else
56 this.options = options || { };
56 this.options = options || { };
57
57
58 this.options.paramName = this.options.paramName || this.element.name;
58 this.options.paramName = this.options.paramName || this.element.name;
59 this.options.tokens = this.options.tokens || [];
59 this.options.tokens = this.options.tokens || [];
60 this.options.frequency = this.options.frequency || 0.4;
60 this.options.frequency = this.options.frequency || 0.4;
61 this.options.minChars = this.options.minChars || 1;
61 this.options.minChars = this.options.minChars || 1;
62 this.options.onShow = this.options.onShow ||
62 this.options.onShow = this.options.onShow ||
63 function(element, update){
63 function(element, update){
64 if(!update.style.position || update.style.position=='absolute') {
64 if(!update.style.position || update.style.position=='absolute') {
65 update.style.position = 'absolute';
65 update.style.position = 'absolute';
66 Position.clone(element, update, {
66 Position.clone(element, update, {
67 setHeight: false,
67 setHeight: false,
68 offsetTop: element.offsetHeight
68 offsetTop: element.offsetHeight
69 });
69 });
70 }
70 }
71 Effect.Appear(update,{duration:0.15});
71 Effect.Appear(update,{duration:0.15});
72 };
72 };
73 this.options.onHide = this.options.onHide ||
73 this.options.onHide = this.options.onHide ||
74 function(element, update){ new Effect.Fade(update,{duration:0.15}) };
74 function(element, update){ new Effect.Fade(update,{duration:0.15}) };
75
75
76 if(typeof(this.options.tokens) == 'string')
76 if(typeof(this.options.tokens) == 'string')
77 this.options.tokens = new Array(this.options.tokens);
77 this.options.tokens = new Array(this.options.tokens);
78 // Force carriage returns as token delimiters anyway
78 // Force carriage returns as token delimiters anyway
79 if (!this.options.tokens.include('\n'))
79 if (!this.options.tokens.include('\n'))
80 this.options.tokens.push('\n');
80 this.options.tokens.push('\n');
81
81
82 this.observer = null;
82 this.observer = null;
83
83
84 this.element.setAttribute('autocomplete','off');
84 this.element.setAttribute('autocomplete','off');
85
85
86 Element.hide(this.update);
86 Element.hide(this.update);
87
87
88 Event.observe(this.element, 'blur', this.onBlur.bindAsEventListener(this));
88 Event.observe(this.element, 'blur', this.onBlur.bindAsEventListener(this));
89 Event.observe(this.element, 'keydown', this.onKeyPress.bindAsEventListener(this));
89 Event.observe(this.element, 'keydown', this.onKeyPress.bindAsEventListener(this));
90 },
90 },
91
91
@@ -164,103 +164,103
164
164
165 activate: function() {
165 activate: function() {
166 this.changed = false;
166 this.changed = false;
167 this.hasFocus = true;
167 this.hasFocus = true;
168 this.getUpdatedChoices();
168 this.getUpdatedChoices();
169 },
169 },
170
170
171 onHover: function(event) {
171 onHover: function(event) {
172 var element = Event.findElement(event, 'LI');
172 var element = Event.findElement(event, 'LI');
173 if(this.index != element.autocompleteIndex)
173 if(this.index != element.autocompleteIndex)
174 {
174 {
175 this.index = element.autocompleteIndex;
175 this.index = element.autocompleteIndex;
176 this.render();
176 this.render();
177 }
177 }
178 Event.stop(event);
178 Event.stop(event);
179 },
179 },
180
180
181 onClick: function(event) {
181 onClick: function(event) {
182 var element = Event.findElement(event, 'LI');
182 var element = Event.findElement(event, 'LI');
183 this.index = element.autocompleteIndex;
183 this.index = element.autocompleteIndex;
184 this.selectEntry();
184 this.selectEntry();
185 this.hide();
185 this.hide();
186 },
186 },
187
187
188 onBlur: function(event) {
188 onBlur: function(event) {
189 // needed to make click events working
189 // needed to make click events working
190 setTimeout(this.hide.bind(this), 250);
190 setTimeout(this.hide.bind(this), 250);
191 this.hasFocus = false;
191 this.hasFocus = false;
192 this.active = false;
192 this.active = false;
193 },
193 },
194
194
195 render: function() {
195 render: function() {
196 if(this.entryCount > 0) {
196 if(this.entryCount > 0) {
197 for (var i = 0; i < this.entryCount; i++)
197 for (var i = 0; i < this.entryCount; i++)
198 this.index==i ?
198 this.index==i ?
199 Element.addClassName(this.getEntry(i),"selected") :
199 Element.addClassName(this.getEntry(i),"selected") :
200 Element.removeClassName(this.getEntry(i),"selected");
200 Element.removeClassName(this.getEntry(i),"selected");
201 if(this.hasFocus) {
201 if(this.hasFocus) {
202 this.show();
202 this.show();
203 this.active = true;
203 this.active = true;
204 }
204 }
205 } else {
205 } else {
206 this.active = false;
206 this.active = false;
207 this.hide();
207 this.hide();
208 }
208 }
209 },
209 },
210
210
211 markPrevious: function() {
211 markPrevious: function() {
212 - if(this.index > 0) this.index--
212 + if(this.index > 0) this.index--;
213 else this.index = this.entryCount-1;
213 else this.index = this.entryCount-1;
214 this.getEntry(this.index).scrollIntoView(true);
214 this.getEntry(this.index).scrollIntoView(true);
215 },
215 },
216
216
217 markNext: function() {
217 markNext: function() {
218 - if(this.index < this.entryCount-1) this.index++
218 + if(this.index < this.entryCount-1) this.index++;
219 else this.index = 0;
219 else this.index = 0;
220 this.getEntry(this.index).scrollIntoView(false);
220 this.getEntry(this.index).scrollIntoView(false);
221 },
221 },
222
222
223 getEntry: function(index) {
223 getEntry: function(index) {
224 return this.update.firstChild.childNodes[index];
224 return this.update.firstChild.childNodes[index];
225 },
225 },
226
226
227 getCurrentEntry: function() {
227 getCurrentEntry: function() {
228 return this.getEntry(this.index);
228 return this.getEntry(this.index);
229 },
229 },
230
230
231 selectEntry: function() {
231 selectEntry: function() {
232 this.active = false;
232 this.active = false;
233 this.updateElement(this.getCurrentEntry());
233 this.updateElement(this.getCurrentEntry());
234 },
234 },
235
235
236 updateElement: function(selectedElement) {
236 updateElement: function(selectedElement) {
237 if (this.options.updateElement) {
237 if (this.options.updateElement) {
238 this.options.updateElement(selectedElement);
238 this.options.updateElement(selectedElement);
239 return;
239 return;
240 }
240 }
241 var value = '';
241 var value = '';
242 if (this.options.select) {
242 if (this.options.select) {
243 var nodes = $(selectedElement).select('.' + this.options.select) || [];
243 var nodes = $(selectedElement).select('.' + this.options.select) || [];
244 if(nodes.length>0) value = Element.collectTextNodes(nodes[0], this.options.select);
244 if(nodes.length>0) value = Element.collectTextNodes(nodes[0], this.options.select);
245 } else
245 } else
246 value = Element.collectTextNodesIgnoreClass(selectedElement, 'informal');
246 value = Element.collectTextNodesIgnoreClass(selectedElement, 'informal');
247
247
248 var bounds = this.getTokenBounds();
248 var bounds = this.getTokenBounds();
249 if (bounds[0] != -1) {
249 if (bounds[0] != -1) {
250 var newValue = this.element.value.substr(0, bounds[0]);
250 var newValue = this.element.value.substr(0, bounds[0]);
251 var whitespace = this.element.value.substr(bounds[0]).match(/^\s+/);
251 var whitespace = this.element.value.substr(bounds[0]).match(/^\s+/);
252 if (whitespace)
252 if (whitespace)
253 newValue += whitespace[0];
253 newValue += whitespace[0];
254 this.element.value = newValue + value + this.element.value.substr(bounds[1]);
254 this.element.value = newValue + value + this.element.value.substr(bounds[1]);
255 } else {
255 } else {
256 this.element.value = value;
256 this.element.value = value;
257 }
257 }
258 this.oldElementValue = this.element.value;
258 this.oldElementValue = this.element.value;
259 this.element.focus();
259 this.element.focus();
260
260
261 if (this.options.afterUpdateElement)
261 if (this.options.afterUpdateElement)
262 this.options.afterUpdateElement(this.element, selectedElement);
262 this.options.afterUpdateElement(this.element, selectedElement);
263 },
263 },
264
264
265 updateChoices: function(choices) {
265 updateChoices: function(choices) {
266 if(!this.changed && this.hasFocus) {
266 if(!this.changed && this.hasFocus) {
@@ -412,114 +412,114
412
412
413 getUpdatedChoices: function() {
413 getUpdatedChoices: function() {
414 this.updateChoices(this.options.selector(this));
414 this.updateChoices(this.options.selector(this));
415 },
415 },
416
416
417 setOptions: function(options) {
417 setOptions: function(options) {
418 this.options = Object.extend({
418 this.options = Object.extend({
419 choices: 10,
419 choices: 10,
420 partialSearch: true,
420 partialSearch: true,
421 partialChars: 2,
421 partialChars: 2,
422 ignoreCase: true,
422 ignoreCase: true,
423 fullSearch: false,
423 fullSearch: false,
424 selector: function(instance) {
424 selector: function(instance) {
425 var ret = []; // Beginning matches
425 var ret = []; // Beginning matches
426 var partial = []; // Inside matches
426 var partial = []; // Inside matches
427 var entry = instance.getToken();
427 var entry = instance.getToken();
428 var count = 0;
428 var count = 0;
429
429
430 for (var i = 0; i < instance.options.array.length &&
430 for (var i = 0; i < instance.options.array.length &&
431 ret.length < instance.options.choices ; i++) {
431 ret.length < instance.options.choices ; i++) {
432
432
433 var elem = instance.options.array[i];
433 var elem = instance.options.array[i];
434 var foundPos = instance.options.ignoreCase ?
434 var foundPos = instance.options.ignoreCase ?
435 elem.toLowerCase().indexOf(entry.toLowerCase()) :
435 elem.toLowerCase().indexOf(entry.toLowerCase()) :
436 elem.indexOf(entry);
436 elem.indexOf(entry);
437
437
438 while (foundPos != -1) {
438 while (foundPos != -1) {
439 if (foundPos == 0 && elem.length != entry.length) {
439 if (foundPos == 0 && elem.length != entry.length) {
440 ret.push("<li><strong>" + elem.substr(0, entry.length) + "</strong>" +
440 ret.push("<li><strong>" + elem.substr(0, entry.length) + "</strong>" +
441 elem.substr(entry.length) + "</li>");
441 elem.substr(entry.length) + "</li>");
442 break;
442 break;
443 } else if (entry.length >= instance.options.partialChars &&
443 } else if (entry.length >= instance.options.partialChars &&
444 instance.options.partialSearch && foundPos != -1) {
444 instance.options.partialSearch && foundPos != -1) {
445 if (instance.options.fullSearch || /\s/.test(elem.substr(foundPos-1,1))) {
445 if (instance.options.fullSearch || /\s/.test(elem.substr(foundPos-1,1))) {
446 partial.push("<li>" + elem.substr(0, foundPos) + "<strong>" +
446 partial.push("<li>" + elem.substr(0, foundPos) + "<strong>" +
447 elem.substr(foundPos, entry.length) + "</strong>" + elem.substr(
447 elem.substr(foundPos, entry.length) + "</strong>" + elem.substr(
448 foundPos + entry.length) + "</li>");
448 foundPos + entry.length) + "</li>");
449 break;
449 break;
450 }
450 }
451 }
451 }
452
452
453 foundPos = instance.options.ignoreCase ?
453 foundPos = instance.options.ignoreCase ?
454 elem.toLowerCase().indexOf(entry.toLowerCase(), foundPos + 1) :
454 elem.toLowerCase().indexOf(entry.toLowerCase(), foundPos + 1) :
455 elem.indexOf(entry, foundPos + 1);
455 elem.indexOf(entry, foundPos + 1);
456
456
457 }
457 }
458 }
458 }
459 if (partial.length)
459 if (partial.length)
460 - ret = ret.concat(partial.slice(0, instance.options.choices - ret.length))
460 + ret = ret.concat(partial.slice(0, instance.options.choices - ret.length));
461 return "<ul>" + ret.join('') + "</ul>";
461 return "<ul>" + ret.join('') + "</ul>";
462 }
462 }
463 }, options || { });
463 }, options || { });
464 }
464 }
465 });
465 });
466
466
467 // AJAX in-place editor and collection editor
467 // AJAX in-place editor and collection editor
468 // Full rewrite by Christophe Porteneuve <tdd@tddsworld.com> (April 2007).
468 // Full rewrite by Christophe Porteneuve <tdd@tddsworld.com> (April 2007).
469
469
470 // Use this if you notice weird scrolling problems on some browsers,
470 // Use this if you notice weird scrolling problems on some browsers,
471 // the DOM might be a bit confused when this gets called so do this
471 // the DOM might be a bit confused when this gets called so do this
472 // waits 1 ms (with setTimeout) until it does the activation
472 // waits 1 ms (with setTimeout) until it does the activation
473 Field.scrollFreeActivate = function(field) {
473 Field.scrollFreeActivate = function(field) {
474 setTimeout(function() {
474 setTimeout(function() {
475 Field.activate(field);
475 Field.activate(field);
476 }, 1);
476 }, 1);
477 - }
477 + };
478
478
479 Ajax.InPlaceEditor = Class.create({
479 Ajax.InPlaceEditor = Class.create({
480 initialize: function(element, url, options) {
480 initialize: function(element, url, options) {
481 this.url = url;
481 this.url = url;
482 this.element = element = $(element);
482 this.element = element = $(element);
483 this.prepareOptions();
483 this.prepareOptions();
484 this._controls = { };
484 this._controls = { };
485 arguments.callee.dealWithDeprecatedOptions(options); // DEPRECATION LAYER!!!
485 arguments.callee.dealWithDeprecatedOptions(options); // DEPRECATION LAYER!!!
486 Object.extend(this.options, options || { });
486 Object.extend(this.options, options || { });
487 if (!this.options.formId && this.element.id) {
487 if (!this.options.formId && this.element.id) {
488 this.options.formId = this.element.id + '-inplaceeditor';
488 this.options.formId = this.element.id + '-inplaceeditor';
489 if ($(this.options.formId))
489 if ($(this.options.formId))
490 this.options.formId = '';
490 this.options.formId = '';
491 }
491 }
492 if (this.options.externalControl)
492 if (this.options.externalControl)
493 this.options.externalControl = $(this.options.externalControl);
493 this.options.externalControl = $(this.options.externalControl);
494 if (!this.options.externalControl)
494 if (!this.options.externalControl)
495 this.options.externalControlOnly = false;
495 this.options.externalControlOnly = false;
496 this._originalBackground = this.element.getStyle('background-color') || 'transparent';
496 this._originalBackground = this.element.getStyle('background-color') || 'transparent';
497 this.element.title = this.options.clickToEditText;
497 this.element.title = this.options.clickToEditText;
498 this._boundCancelHandler = this.handleFormCancellation.bind(this);
498 this._boundCancelHandler = this.handleFormCancellation.bind(this);
499 this._boundComplete = (this.options.onComplete || Prototype.emptyFunction).bind(this);
499 this._boundComplete = (this.options.onComplete || Prototype.emptyFunction).bind(this);
500 this._boundFailureHandler = this.handleAJAXFailure.bind(this);
500 this._boundFailureHandler = this.handleAJAXFailure.bind(this);
501 this._boundSubmitHandler = this.handleFormSubmission.bind(this);
501 this._boundSubmitHandler = this.handleFormSubmission.bind(this);
502 this._boundWrapperHandler = this.wrapUp.bind(this);
502 this._boundWrapperHandler = this.wrapUp.bind(this);
503 this.registerListeners();
503 this.registerListeners();
504 },
504 },
505 checkForEscapeOrReturn: function(e) {
505 checkForEscapeOrReturn: function(e) {
506 if (!this._editing || e.ctrlKey || e.altKey || e.shiftKey) return;
506 if (!this._editing || e.ctrlKey || e.altKey || e.shiftKey) return;
507 if (Event.KEY_ESC == e.keyCode)
507 if (Event.KEY_ESC == e.keyCode)
508 this.handleFormCancellation(e);
508 this.handleFormCancellation(e);
509 else if (Event.KEY_RETURN == e.keyCode)
509 else if (Event.KEY_RETURN == e.keyCode)
510 this.handleFormSubmission(e);
510 this.handleFormSubmission(e);
511 },
511 },
512 createControl: function(mode, handler, extraClasses) {
512 createControl: function(mode, handler, extraClasses) {
513 var control = this.options[mode + 'Control'];
513 var control = this.options[mode + 'Control'];
514 var text = this.options[mode + 'Text'];
514 var text = this.options[mode + 'Text'];
515 if ('button' == control) {
515 if ('button' == control) {
516 var btn = document.createElement('input');
516 var btn = document.createElement('input');
517 btn.type = 'submit';
517 btn.type = 'submit';
518 btn.value = text;
518 btn.value = text;
519 btn.className = 'editor_' + mode + '_button';
519 btn.className = 'editor_' + mode + '_button';
520 if ('cancel' == mode)
520 if ('cancel' == mode)
521 btn.onclick = this._boundCancelHandler;
521 btn.onclick = this._boundCancelHandler;
522 this._form.appendChild(btn);
522 this._form.appendChild(btn);
523 this._controls[mode] = btn;
523 this._controls[mode] = btn;
524 } else if ('link' == control) {
524 } else if ('link' == control) {
525 var link = document.createElement('a');
525 var link = document.createElement('a');
@@ -559,97 +559,97
559 createForm: function() {
559 createForm: function() {
560 var ipe = this;
560 var ipe = this;
561 function addText(mode, condition) {
561 function addText(mode, condition) {
562 var text = ipe.options['text' + mode + 'Controls'];
562 var text = ipe.options['text' + mode + 'Controls'];
563 if (!text || condition === false) return;
563 if (!text || condition === false) return;
564 ipe._form.appendChild(document.createTextNode(text));
564 ipe._form.appendChild(document.createTextNode(text));
565 };
565 };
566 this._form = $(document.createElement('form'));
566 this._form = $(document.createElement('form'));
567 this._form.id = this.options.formId;
567 this._form.id = this.options.formId;
568 this._form.addClassName(this.options.formClassName);
568 this._form.addClassName(this.options.formClassName);
569 this._form.onsubmit = this._boundSubmitHandler;
569 this._form.onsubmit = this._boundSubmitHandler;
570 this.createEditField();
570 this.createEditField();
571 if ('textarea' == this._controls.editor.tagName.toLowerCase())
571 if ('textarea' == this._controls.editor.tagName.toLowerCase())
572 this._form.appendChild(document.createElement('br'));
572 this._form.appendChild(document.createElement('br'));
573 if (this.options.onFormCustomization)
573 if (this.options.onFormCustomization)
574 this.options.onFormCustomization(this, this._form);
574 this.options.onFormCustomization(this, this._form);
575 addText('Before', this.options.okControl || this.options.cancelControl);
575 addText('Before', this.options.okControl || this.options.cancelControl);
576 this.createControl('ok', this._boundSubmitHandler);
576 this.createControl('ok', this._boundSubmitHandler);
577 addText('Between', this.options.okControl && this.options.cancelControl);
577 addText('Between', this.options.okControl && this.options.cancelControl);
578 this.createControl('cancel', this._boundCancelHandler, 'editor_cancel');
578 this.createControl('cancel', this._boundCancelHandler, 'editor_cancel');
579 addText('After', this.options.okControl || this.options.cancelControl);
579 addText('After', this.options.okControl || this.options.cancelControl);
580 },
580 },
581 destroy: function() {
581 destroy: function() {
582 if (this._oldInnerHTML)
582 if (this._oldInnerHTML)
583 this.element.innerHTML = this._oldInnerHTML;
583 this.element.innerHTML = this._oldInnerHTML;
584 this.leaveEditMode();
584 this.leaveEditMode();
585 this.unregisterListeners();
585 this.unregisterListeners();
586 },
586 },
587 enterEditMode: function(e) {
587 enterEditMode: function(e) {
588 if (this._saving || this._editing) return;
588 if (this._saving || this._editing) return;
589 this._editing = true;
589 this._editing = true;
590 this.triggerCallback('onEnterEditMode');
590 this.triggerCallback('onEnterEditMode');
591 if (this.options.externalControl)
591 if (this.options.externalControl)
592 this.options.externalControl.hide();
592 this.options.externalControl.hide();
593 this.element.hide();
593 this.element.hide();
594 this.createForm();
594 this.createForm();
595 this.element.parentNode.insertBefore(this._form, this.element);
595 this.element.parentNode.insertBefore(this._form, this.element);
596 if (!this.options.loadTextURL)
596 if (!this.options.loadTextURL)
597 this.postProcessEditField();
597 this.postProcessEditField();
598 if (e) Event.stop(e);
598 if (e) Event.stop(e);
599 },
599 },
600 enterHover: function(e) {
600 enterHover: function(e) {
601 if (this.options.hoverClassName)
601 if (this.options.hoverClassName)
602 this.element.addClassName(this.options.hoverClassName);
602 this.element.addClassName(this.options.hoverClassName);
603 if (this._saving) return;
603 if (this._saving) return;
604 this.triggerCallback('onEnterHover');
604 this.triggerCallback('onEnterHover');
605 },
605 },
606 getText: function() {
606 getText: function() {
607 - return this.element.innerHTML;
607 + return this.element.innerHTML.unescapeHTML();
608 },
608 },
609 handleAJAXFailure: function(transport) {
609 handleAJAXFailure: function(transport) {
610 this.triggerCallback('onFailure', transport);
610 this.triggerCallback('onFailure', transport);
611 if (this._oldInnerHTML) {
611 if (this._oldInnerHTML) {
612 this.element.innerHTML = this._oldInnerHTML;
612 this.element.innerHTML = this._oldInnerHTML;
613 this._oldInnerHTML = null;
613 this._oldInnerHTML = null;
614 }
614 }
615 },
615 },
616 handleFormCancellation: function(e) {
616 handleFormCancellation: function(e) {
617 this.wrapUp();
617 this.wrapUp();
618 if (e) Event.stop(e);
618 if (e) Event.stop(e);
619 },
619 },
620 handleFormSubmission: function(e) {
620 handleFormSubmission: function(e) {
621 var form = this._form;
621 var form = this._form;
622 var value = $F(this._controls.editor);
622 var value = $F(this._controls.editor);
623 this.prepareSubmission();
623 this.prepareSubmission();
624 var params = this.options.callback(form, value) || '';
624 var params = this.options.callback(form, value) || '';
625 if (Object.isString(params))
625 if (Object.isString(params))
626 params = params.toQueryParams();
626 params = params.toQueryParams();
627 params.editorId = this.element.id;
627 params.editorId = this.element.id;
628 if (this.options.htmlResponse) {
628 if (this.options.htmlResponse) {
629 var options = Object.extend({ evalScripts: true }, this.options.ajaxOptions);
629 var options = Object.extend({ evalScripts: true }, this.options.ajaxOptions);
630 Object.extend(options, {
630 Object.extend(options, {
631 parameters: params,
631 parameters: params,
632 onComplete: this._boundWrapperHandler,
632 onComplete: this._boundWrapperHandler,
633 onFailure: this._boundFailureHandler
633 onFailure: this._boundFailureHandler
634 });
634 });
635 new Ajax.Updater({ success: this.element }, this.url, options);
635 new Ajax.Updater({ success: this.element }, this.url, options);
636 } else {
636 } else {
637 var options = Object.extend({ method: 'get' }, this.options.ajaxOptions);
637 var options = Object.extend({ method: 'get' }, this.options.ajaxOptions);
638 Object.extend(options, {
638 Object.extend(options, {
639 parameters: params,
639 parameters: params,
640 onComplete: this._boundWrapperHandler,
640 onComplete: this._boundWrapperHandler,
641 onFailure: this._boundFailureHandler
641 onFailure: this._boundFailureHandler
642 });
642 });
643 new Ajax.Request(this.url, options);
643 new Ajax.Request(this.url, options);
644 }
644 }
645 if (e) Event.stop(e);
645 if (e) Event.stop(e);
646 },
646 },
647 leaveEditMode: function() {
647 leaveEditMode: function() {
648 this.element.removeClassName(this.options.savingClassName);
648 this.element.removeClassName(this.options.savingClassName);
649 this.removeForm();
649 this.removeForm();
650 this.leaveHover();
650 this.leaveHover();
651 this.element.style.backgroundColor = this._originalBackground;
651 this.element.style.backgroundColor = this._originalBackground;
652 this.element.show();
652 this.element.show();
653 if (this.options.externalControl)
653 if (this.options.externalControl)
654 this.options.externalControl.show();
654 this.options.externalControl.show();
655 this._saving = false;
655 this._saving = false;
@@ -735,97 +735,97
735 $H(this._listeners).each(function(pair) {
735 $H(this._listeners).each(function(pair) {
736 if (!this.options.externalControlOnly)
736 if (!this.options.externalControlOnly)
737 this.element.stopObserving(pair.key, pair.value);
737 this.element.stopObserving(pair.key, pair.value);
738 if (this.options.externalControl)
738 if (this.options.externalControl)
739 this.options.externalControl.stopObserving(pair.key, pair.value);
739 this.options.externalControl.stopObserving(pair.key, pair.value);
740 }.bind(this));
740 }.bind(this));
741 },
741 },
742 wrapUp: function(transport) {
742 wrapUp: function(transport) {
743 this.leaveEditMode();
743 this.leaveEditMode();
744 // Can't use triggerCallback due to backward compatibility: requires
744 // Can't use triggerCallback due to backward compatibility: requires
745 // binding + direct element
745 // binding + direct element
746 this._boundComplete(transport, this.element);
746 this._boundComplete(transport, this.element);
747 }
747 }
748 });
748 });
749
749
750 Object.extend(Ajax.InPlaceEditor.prototype, {
750 Object.extend(Ajax.InPlaceEditor.prototype, {
751 dispose: Ajax.InPlaceEditor.prototype.destroy
751 dispose: Ajax.InPlaceEditor.prototype.destroy
752 });
752 });
753
753
754 Ajax.InPlaceCollectionEditor = Class.create(Ajax.InPlaceEditor, {
754 Ajax.InPlaceCollectionEditor = Class.create(Ajax.InPlaceEditor, {
755 initialize: function($super, element, url, options) {
755 initialize: function($super, element, url, options) {
756 this._extraDefaultOptions = Ajax.InPlaceCollectionEditor.DefaultOptions;
756 this._extraDefaultOptions = Ajax.InPlaceCollectionEditor.DefaultOptions;
757 $super(element, url, options);
757 $super(element, url, options);
758 },
758 },
759
759
760 createEditField: function() {
760 createEditField: function() {
761 var list = document.createElement('select');
761 var list = document.createElement('select');
762 list.name = this.options.paramName;
762 list.name = this.options.paramName;
763 list.size = 1;
763 list.size = 1;
764 this._controls.editor = list;
764 this._controls.editor = list;
765 this._collection = this.options.collection || [];
765 this._collection = this.options.collection || [];
766 if (this.options.loadCollectionURL)
766 if (this.options.loadCollectionURL)
767 this.loadCollection();
767 this.loadCollection();
768 else
768 else
769 this.checkForExternalText();
769 this.checkForExternalText();
770 this._form.appendChild(this._controls.editor);
770 this._form.appendChild(this._controls.editor);
771 },
771 },
772
772
773 loadCollection: function() {
773 loadCollection: function() {
774 this._form.addClassName(this.options.loadingClassName);
774 this._form.addClassName(this.options.loadingClassName);
775 this.showLoadingText(this.options.loadingCollectionText);
775 this.showLoadingText(this.options.loadingCollectionText);
776 var options = Object.extend({ method: 'get' }, this.options.ajaxOptions);
776 var options = Object.extend({ method: 'get' }, this.options.ajaxOptions);
777 Object.extend(options, {
777 Object.extend(options, {
778 parameters: 'editorId=' + encodeURIComponent(this.element.id),
778 parameters: 'editorId=' + encodeURIComponent(this.element.id),
779 onComplete: Prototype.emptyFunction,
779 onComplete: Prototype.emptyFunction,
780 onSuccess: function(transport) {
780 onSuccess: function(transport) {
781 var js = transport.responseText.strip();
781 var js = transport.responseText.strip();
782 if (!/^\[.*\]$/.test(js)) // TODO: improve sanity check
782 if (!/^\[.*\]$/.test(js)) // TODO: improve sanity check
783 - throw 'Server returned an invalid collection representation.';
783 + throw('Server returned an invalid collection representation.');
784 this._collection = eval(js);
784 this._collection = eval(js);
785 this.checkForExternalText();
785 this.checkForExternalText();
786 }.bind(this),
786 }.bind(this),
787 onFailure: this.onFailure
787 onFailure: this.onFailure
788 });
788 });
789 new Ajax.Request(this.options.loadCollectionURL, options);
789 new Ajax.Request(this.options.loadCollectionURL, options);
790 },
790 },
791
791
792 showLoadingText: function(text) {
792 showLoadingText: function(text) {
793 this._controls.editor.disabled = true;
793 this._controls.editor.disabled = true;
794 var tempOption = this._controls.editor.firstChild;
794 var tempOption = this._controls.editor.firstChild;
795 if (!tempOption) {
795 if (!tempOption) {
796 tempOption = document.createElement('option');
796 tempOption = document.createElement('option');
797 tempOption.value = '';
797 tempOption.value = '';
798 this._controls.editor.appendChild(tempOption);
798 this._controls.editor.appendChild(tempOption);
799 tempOption.selected = true;
799 tempOption.selected = true;
800 }
800 }
801 tempOption.update((text || '').stripScripts().stripTags());
801 tempOption.update((text || '').stripScripts().stripTags());
802 },
802 },
803
803
804 checkForExternalText: function() {
804 checkForExternalText: function() {
805 this._text = this.getText();
805 this._text = this.getText();
806 if (this.options.loadTextURL)
806 if (this.options.loadTextURL)
807 this.loadExternalText();
807 this.loadExternalText();
808 else
808 else
809 this.buildOptionList();
809 this.buildOptionList();
810 },
810 },
811
811
812 loadExternalText: function() {
812 loadExternalText: function() {
813 this.showLoadingText(this.options.loadingText);
813 this.showLoadingText(this.options.loadingText);
814 var options = Object.extend({ method: 'get' }, this.options.ajaxOptions);
814 var options = Object.extend({ method: 'get' }, this.options.ajaxOptions);
815 Object.extend(options, {
815 Object.extend(options, {
816 parameters: 'editorId=' + encodeURIComponent(this.element.id),
816 parameters: 'editorId=' + encodeURIComponent(this.element.id),
817 onComplete: Prototype.emptyFunction,
817 onComplete: Prototype.emptyFunction,
818 onSuccess: function(transport) {
818 onSuccess: function(transport) {
819 this._text = transport.responseText.strip();
819 this._text = transport.responseText.strip();
820 this.buildOptionList();
820 this.buildOptionList();
821 }.bind(this),
821 }.bind(this),
822 onFailure: this.onFailure
822 onFailure: this.onFailure
823 });
823 });
824 new Ajax.Request(this.options.loadTextURL, options);
824 new Ajax.Request(this.options.loadTextURL, options);
825 },
825 },
826
826
827 buildOptionList: function() {
827 buildOptionList: function() {
828 this._form.removeClassName(this.options.loadingClassName);
828 this._form.removeClassName(this.options.loadingClassName);
829 this._collection = this._collection.map(function(entry) {
829 this._collection = this._collection.map(function(entry) {
830 return 2 === entry.length ? entry : [entry, entry].flatten();
830 return 2 === entry.length ? entry : [entry, entry].flatten();
831 });
831 });
@@ -915,49 +915,49
915 },
915 },
916 onFailure: function(transport, ipe) {
916 onFailure: function(transport, ipe) {
917 alert('Error communication with the server: ' + transport.responseText.stripTags());
917 alert('Error communication with the server: ' + transport.responseText.stripTags());
918 },
918 },
919 onFormCustomization: null, // Takes the IPE and its generated form, after editor, before controls.
919 onFormCustomization: null, // Takes the IPE and its generated form, after editor, before controls.
920 onLeaveEditMode: null,
920 onLeaveEditMode: null,
921 onLeaveHover: function(ipe) {
921 onLeaveHover: function(ipe) {
922 ipe._effect = new Effect.Highlight(ipe.element, {
922 ipe._effect = new Effect.Highlight(ipe.element, {
923 startcolor: ipe.options.highlightColor, endcolor: ipe.options.highlightEndColor,
923 startcolor: ipe.options.highlightColor, endcolor: ipe.options.highlightEndColor,
924 restorecolor: ipe._originalBackground, keepBackgroundImage: true
924 restorecolor: ipe._originalBackground, keepBackgroundImage: true
925 });
925 });
926 }
926 }
927 },
927 },
928 Listeners: {
928 Listeners: {
929 click: 'enterEditMode',
929 click: 'enterEditMode',
930 keydown: 'checkForEscapeOrReturn',
930 keydown: 'checkForEscapeOrReturn',
931 mouseover: 'enterHover',
931 mouseover: 'enterHover',
932 mouseout: 'leaveHover'
932 mouseout: 'leaveHover'
933 }
933 }
934 });
934 });
935
935
936 Ajax.InPlaceCollectionEditor.DefaultOptions = {
936 Ajax.InPlaceCollectionEditor.DefaultOptions = {
937 loadingCollectionText: 'Loading options...'
937 loadingCollectionText: 'Loading options...'
938 };
938 };
939
939
940 // Delayed observer, like Form.Element.Observer,
940 // Delayed observer, like Form.Element.Observer,
941 // but waits for delay after last key input
941 // but waits for delay after last key input
942 // Ideal for live-search fields
942 // Ideal for live-search fields
943
943
944 Form.Element.DelayedObserver = Class.create({
944 Form.Element.DelayedObserver = Class.create({
945 initialize: function(element, delay, callback) {
945 initialize: function(element, delay, callback) {
946 this.delay = delay || 0.5;
946 this.delay = delay || 0.5;
947 this.element = $(element);
947 this.element = $(element);
948 this.callback = callback;
948 this.callback = callback;
949 this.timer = null;
949 this.timer = null;
950 this.lastValue = $F(this.element);
950 this.lastValue = $F(this.element);
951 Event.observe(this.element,'keyup',this.delayedListener.bindAsEventListener(this));
951 Event.observe(this.element,'keyup',this.delayedListener.bindAsEventListener(this));
952 },
952 },
953 delayedListener: function(event) {
953 delayedListener: function(event) {
954 if(this.lastValue == $F(this.element)) return;
954 if(this.lastValue == $F(this.element)) return;
955 if(this.timer) clearTimeout(this.timer);
955 if(this.timer) clearTimeout(this.timer);
956 this.timer = setTimeout(this.onTimerEvent.bind(this), this.delay * 1000);
956 this.timer = setTimeout(this.onTimerEvent.bind(this), this.delay * 1000);
957 this.lastValue = $F(this.element);
957 this.lastValue = $F(this.element);
958 },
958 },
959 onTimerEvent: function() {
959 onTimerEvent: function() {
960 this.timer = null;
960 this.timer = null;
961 this.callback(this.element, $F(this.element));
961 this.callback(this.element, $F(this.element));
962 }
962 }
963 - });
963 + }); No newline at end of file
@@ -1,50 +1,50
1 // Copyright (c) 2005-2008 Thomas Fuchs (http://script.aculo.us, http://mir.aculo.us)
1 // Copyright (c) 2005-2008 Thomas Fuchs (http://script.aculo.us, http://mir.aculo.us)
2 - // (c) 2005-2007 Sammi Williams (http://www.oriontransfer.co.nz, sammi@oriontransfer.co.nz)
2 + // (c) 2005-2008 Sammi Williams (http://www.oriontransfer.co.nz, sammi@oriontransfer.co.nz)
3 //
3 //
4 // script.aculo.us is freely distributable under the terms of an MIT-style license.
4 // script.aculo.us is freely distributable under the terms of an MIT-style license.
5 // For details, see the script.aculo.us web site: http://script.aculo.us/
5 // For details, see the script.aculo.us web site: http://script.aculo.us/
6
6
7 if(Object.isUndefined(Effect))
7 if(Object.isUndefined(Effect))
8 throw("dragdrop.js requires including script.aculo.us' effects.js library");
8 throw("dragdrop.js requires including script.aculo.us' effects.js library");
9
9
10 var Droppables = {
10 var Droppables = {
11 drops: [],
11 drops: [],
12
12
13 remove: function(element) {
13 remove: function(element) {
14 this.drops = this.drops.reject(function(d) { return d.element==$(element) });
14 this.drops = this.drops.reject(function(d) { return d.element==$(element) });
15 },
15 },
16
16
17 add: function(element) {
17 add: function(element) {
18 element = $(element);
18 element = $(element);
19 var options = Object.extend({
19 var options = Object.extend({
20 greedy: true,
20 greedy: true,
21 hoverclass: null,
21 hoverclass: null,
22 tree: false
22 tree: false
23 }, arguments[1] || { });
23 }, arguments[1] || { });
24
24
25 // cache containers
25 // cache containers
26 if(options.containment) {
26 if(options.containment) {
27 options._containers = [];
27 options._containers = [];
28 var containment = options.containment;
28 var containment = options.containment;
29 if(Object.isArray(containment)) {
29 if(Object.isArray(containment)) {
30 containment.each( function(c) { options._containers.push($(c)) });
30 containment.each( function(c) { options._containers.push($(c)) });
31 } else {
31 } else {
32 options._containers.push($(containment));
32 options._containers.push($(containment));
33 }
33 }
34 }
34 }
35
35
36 if(options.accept) options.accept = [options.accept].flatten();
36 if(options.accept) options.accept = [options.accept].flatten();
37
37
38 Element.makePositioned(element); // fix IE
38 Element.makePositioned(element); // fix IE
39 options.element = element;
39 options.element = element;
40
40
41 this.drops.push(options);
41 this.drops.push(options);
42 },
42 },
43
43
44 findDeepestChild: function(drops) {
44 findDeepestChild: function(drops) {
45 deepest = drops[0];
45 deepest = drops[0];
46
46
47 for (i = 1; i < drops.length; ++i)
47 for (i = 1; i < drops.length; ++i)
48 if (Element.isParent(drops[i].element, deepest.element))
48 if (Element.isParent(drops[i].element, deepest.element))
49 deepest = drops[i];
49 deepest = drops[i];
50
50
@@ -76,194 +76,194
76 if(drop.hoverclass)
76 if(drop.hoverclass)
77 Element.removeClassName(drop.element, drop.hoverclass);
77 Element.removeClassName(drop.element, drop.hoverclass);
78 this.last_active = null;
78 this.last_active = null;
79 },
79 },
80
80
81 activate: function(drop) {
81 activate: function(drop) {
82 if(drop.hoverclass)
82 if(drop.hoverclass)
83 Element.addClassName(drop.element, drop.hoverclass);
83 Element.addClassName(drop.element, drop.hoverclass);
84 this.last_active = drop;
84 this.last_active = drop;
85 },
85 },
86
86
87 show: function(point, element) {
87 show: function(point, element) {
88 if(!this.drops.length) return;
88 if(!this.drops.length) return;
89 var drop, affected = [];
89 var drop, affected = [];
90
90
91 this.drops.each( function(drop) {
91 this.drops.each( function(drop) {
92 if(Droppables.isAffected(point, element, drop))
92 if(Droppables.isAffected(point, element, drop))
93 affected.push(drop);
93 affected.push(drop);
94 });
94 });
95
95
96 if(affected.length>0)
96 if(affected.length>0)
97 drop = Droppables.findDeepestChild(affected);
97 drop = Droppables.findDeepestChild(affected);
98
98
99 if(this.last_active && this.last_active != drop) this.deactivate(this.last_active);
99 if(this.last_active && this.last_active != drop) this.deactivate(this.last_active);
100 if (drop) {
100 if (drop) {
101 Position.within(drop.element, point[0], point[1]);
101 Position.within(drop.element, point[0], point[1]);
102 if(drop.onHover)
102 if(drop.onHover)
103 drop.onHover(element, drop.element, Position.overlap(drop.overlap, drop.element));
103 drop.onHover(element, drop.element, Position.overlap(drop.overlap, drop.element));
104
104
105 if (drop != this.last_active) Droppables.activate(drop);
105 if (drop != this.last_active) Droppables.activate(drop);
106 }
106 }
107 },
107 },
108
108
109 fire: function(event, element) {
109 fire: function(event, element) {
110 if(!this.last_active) return;
110 if(!this.last_active) return;
111 Position.prepare();
111 Position.prepare();
112
112
113 if (this.isAffected([Event.pointerX(event), Event.pointerY(event)], element, this.last_active))
113 if (this.isAffected([Event.pointerX(event), Event.pointerY(event)], element, this.last_active))
114 if (this.last_active.onDrop) {
114 if (this.last_active.onDrop) {
115 this.last_active.onDrop(element, this.last_active.element, event);
115 this.last_active.onDrop(element, this.last_active.element, event);
116 return true;
116 return true;
117 }
117 }
118 },
118 },
119
119
120 reset: function() {
120 reset: function() {
121 if(this.last_active)
121 if(this.last_active)
122 this.deactivate(this.last_active);
122 this.deactivate(this.last_active);
123 }
123 }
124 - }
124 + };
125
125
126 var Draggables = {
126 var Draggables = {
127 drags: [],
127 drags: [],
128 observers: [],
128 observers: [],
129
129
130 register: function(draggable) {
130 register: function(draggable) {
131 if(this.drags.length == 0) {
131 if(this.drags.length == 0) {
132 this.eventMouseUp = this.endDrag.bindAsEventListener(this);
132 this.eventMouseUp = this.endDrag.bindAsEventListener(this);
133 this.eventMouseMove = this.updateDrag.bindAsEventListener(this);
133 this.eventMouseMove = this.updateDrag.bindAsEventListener(this);
134 this.eventKeypress = this.keyPress.bindAsEventListener(this);
134 this.eventKeypress = this.keyPress.bindAsEventListener(this);
135
135
136 Event.observe(document, "mouseup", this.eventMouseUp);
136 Event.observe(document, "mouseup", this.eventMouseUp);
137 Event.observe(document, "mousemove", this.eventMouseMove);
137 Event.observe(document, "mousemove", this.eventMouseMove);
138 Event.observe(document, "keypress", this.eventKeypress);
138 Event.observe(document, "keypress", this.eventKeypress);
139 }
139 }
140 this.drags.push(draggable);
140 this.drags.push(draggable);
141 },
141 },
142
142
143 unregister: function(draggable) {
143 unregister: function(draggable) {
144 this.drags = this.drags.reject(function(d) { return d==draggable });
144 this.drags = this.drags.reject(function(d) { return d==draggable });
145 if(this.drags.length == 0) {
145 if(this.drags.length == 0) {
146 Event.stopObserving(document, "mouseup", this.eventMouseUp);
146 Event.stopObserving(document, "mouseup", this.eventMouseUp);
147 Event.stopObserving(document, "mousemove", this.eventMouseMove);
147 Event.stopObserving(document, "mousemove", this.eventMouseMove);
148 Event.stopObserving(document, "keypress", this.eventKeypress);
148 Event.stopObserving(document, "keypress", this.eventKeypress);
149 }
149 }
150 },
150 },
151
151
152 activate: function(draggable) {
152 activate: function(draggable) {
153 if(draggable.options.delay) {
153 if(draggable.options.delay) {
154 this._timeout = setTimeout(function() {
154 this._timeout = setTimeout(function() {
155 Draggables._timeout = null;
155 Draggables._timeout = null;
156 window.focus();
156 window.focus();
157 Draggables.activeDraggable = draggable;
157 Draggables.activeDraggable = draggable;
158 }.bind(this), draggable.options.delay);
158 }.bind(this), draggable.options.delay);
159 } else {
159 } else {
160 window.focus(); // allows keypress events if window isn't currently focused, fails for Safari
160 window.focus(); // allows keypress events if window isn't currently focused, fails for Safari
161 this.activeDraggable = draggable;
161 this.activeDraggable = draggable;
162 }
162 }
163 },
163 },
164
164
165 deactivate: function() {
165 deactivate: function() {
166 this.activeDraggable = null;
166 this.activeDraggable = null;
167 },
167 },
168
168
169 updateDrag: function(event) {
169 updateDrag: function(event) {
170 if(!this.activeDraggable) return;
170 if(!this.activeDraggable) return;
171 var pointer = [Event.pointerX(event), Event.pointerY(event)];
171 var pointer = [Event.pointerX(event), Event.pointerY(event)];
172 // Mozilla-based browsers fire successive mousemove events with
172 // Mozilla-based browsers fire successive mousemove events with
173 // the same coordinates, prevent needless redrawing (moz bug?)
173 // the same coordinates, prevent needless redrawing (moz bug?)
174 if(this._lastPointer && (this._lastPointer.inspect() == pointer.inspect())) return;
174 if(this._lastPointer && (this._lastPointer.inspect() == pointer.inspect())) return;
175 this._lastPointer = pointer;
175 this._lastPointer = pointer;
176
176
177 this.activeDraggable.updateDrag(event, pointer);
177 this.activeDraggable.updateDrag(event, pointer);
178 },
178 },
179
179
180 endDrag: function(event) {
180 endDrag: function(event) {
181 if(this._timeout) {
181 if(this._timeout) {
182 clearTimeout(this._timeout);
182 clearTimeout(this._timeout);
183 this._timeout = null;
183 this._timeout = null;
184 }
184 }
185 if(!this.activeDraggable) return;
185 if(!this.activeDraggable) return;
186 this._lastPointer = null;
186 this._lastPointer = null;
187 this.activeDraggable.endDrag(event);
187 this.activeDraggable.endDrag(event);
188 this.activeDraggable = null;
188 this.activeDraggable = null;
189 },
189 },
190
190
191 keyPress: function(event) {
191 keyPress: function(event) {
192 if(this.activeDraggable)
192 if(this.activeDraggable)
193 this.activeDraggable.keyPress(event);
193 this.activeDraggable.keyPress(event);
194 },
194 },
195
195
196 addObserver: function(observer) {
196 addObserver: function(observer) {
197 this.observers.push(observer);
197 this.observers.push(observer);
198 this._cacheObserverCallbacks();
198 this._cacheObserverCallbacks();
199 },
199 },
200
200
201 removeObserver: function(element) { // element instead of observer fixes mem leaks
201 removeObserver: function(element) { // element instead of observer fixes mem leaks
202 this.observers = this.observers.reject( function(o) { return o.element==element });
202 this.observers = this.observers.reject( function(o) { return o.element==element });
203 this._cacheObserverCallbacks();
203 this._cacheObserverCallbacks();
204 },
204 },
205
205
206 notify: function(eventName, draggable, event) { // 'onStart', 'onEnd', 'onDrag'
206 notify: function(eventName, draggable, event) { // 'onStart', 'onEnd', 'onDrag'
207 if(this[eventName+'Count'] > 0)
207 if(this[eventName+'Count'] > 0)
208 this.observers.each( function(o) {
208 this.observers.each( function(o) {
209 if(o[eventName]) o[eventName](eventName, draggable, event);
209 if(o[eventName]) o[eventName](eventName, draggable, event);
210 });
210 });
211 if(draggable.options[eventName]) draggable.options[eventName](draggable, event);
211 if(draggable.options[eventName]) draggable.options[eventName](draggable, event);
212 },
212 },
213
213
214 _cacheObserverCallbacks: function() {
214 _cacheObserverCallbacks: function() {
215 ['onStart','onEnd','onDrag'].each( function(eventName) {
215 ['onStart','onEnd','onDrag'].each( function(eventName) {
216 Draggables[eventName+'Count'] = Draggables.observers.select(
216 Draggables[eventName+'Count'] = Draggables.observers.select(
217 function(o) { return o[eventName]; }
217 function(o) { return o[eventName]; }
218 ).length;
218 ).length;
219 });
219 });
220 }
220 }
221 - }
221 + };
222
222
223 /*--------------------------------------------------------------------------*/
223 /*--------------------------------------------------------------------------*/
224
224
225 var Draggable = Class.create({
225 var Draggable = Class.create({
226 initialize: function(element) {
226 initialize: function(element) {
227 var defaults = {
227 var defaults = {
228 handle: false,
228 handle: false,
229 reverteffect: function(element, top_offset, left_offset) {
229 reverteffect: function(element, top_offset, left_offset) {
230 var dur = Math.sqrt(Math.abs(top_offset^2)+Math.abs(left_offset^2))*0.02;
230 var dur = Math.sqrt(Math.abs(top_offset^2)+Math.abs(left_offset^2))*0.02;
231 new Effect.Move(element, { x: -left_offset, y: -top_offset, duration: dur,
231 new Effect.Move(element, { x: -left_offset, y: -top_offset, duration: dur,
232 queue: {scope:'_draggable', position:'end'}
232 queue: {scope:'_draggable', position:'end'}
233 });
233 });
234 },
234 },
235 endeffect: function(element) {
235 endeffect: function(element) {
236 var toOpacity = Object.isNumber(element._opacity) ? element._opacity : 1.0;
236 var toOpacity = Object.isNumber(element._opacity) ? element._opacity : 1.0;
237 new Effect.Opacity(element, {duration:0.2, from:0.7, to:toOpacity,
237 new Effect.Opacity(element, {duration:0.2, from:0.7, to:toOpacity,
238 queue: {scope:'_draggable', position:'end'},
238 queue: {scope:'_draggable', position:'end'},
239 afterFinish: function(){
239 afterFinish: function(){
240 Draggable._dragging[element] = false
240 Draggable._dragging[element] = false
241 }
241 }
242 });
242 });
243 },
243 },
244 zindex: 1000,
244 zindex: 1000,
245 revert: false,
245 revert: false,
246 quiet: false,
246 quiet: false,
247 scroll: false,
247 scroll: false,
248 scrollSensitivity: 20,
248 scrollSensitivity: 20,
249 scrollSpeed: 15,
249 scrollSpeed: 15,
250 snap: false, // false, or xy or [x,y] or function(x,y){ return [x,y] }
250 snap: false, // false, or xy or [x,y] or function(x,y){ return [x,y] }
251 delay: 0
251 delay: 0
252 };
252 };
253
253
254 if(!arguments[1] || Object.isUndefined(arguments[1].endeffect))
254 if(!arguments[1] || Object.isUndefined(arguments[1].endeffect))
255 Object.extend(defaults, {
255 Object.extend(defaults, {
256 starteffect: function(element) {
256 starteffect: function(element) {
257 element._opacity = Element.getOpacity(element);
257 element._opacity = Element.getOpacity(element);
258 Draggable._dragging[element] = true;
258 Draggable._dragging[element] = true;
259 new Effect.Opacity(element, {duration:0.2, from:element._opacity, to:0.7});
259 new Effect.Opacity(element, {duration:0.2, from:element._opacity, to:0.7});
260 }
260 }
261 });
261 });
262
262
263 var options = Object.extend(defaults, arguments[1] || { });
263 var options = Object.extend(defaults, arguments[1] || { });
264
264
265 this.element = $(element);
265 this.element = $(element);
266
266
267 if(options.handle && Object.isString(options.handle))
267 if(options.handle && Object.isString(options.handle))
268 this.handle = this.element.down('.'+options.handle, 0);
268 this.handle = this.element.down('.'+options.handle, 0);
269
269
@@ -286,462 +286,463
286 Draggables.register(this);
286 Draggables.register(this);
287 },
287 },
288
288
289 destroy: function() {
289 destroy: function() {
290 Event.stopObserving(this.handle, "mousedown", this.eventMouseDown);
290 Event.stopObserving(this.handle, "mousedown", this.eventMouseDown);
291 Draggables.unregister(this);
291 Draggables.unregister(this);
292 },
292 },
293
293
294 currentDelta: function() {
294 currentDelta: function() {
295 return([
295 return([
296 parseInt(Element.getStyle(this.element,'left') || '0'),
296 parseInt(Element.getStyle(this.element,'left') || '0'),
297 parseInt(Element.getStyle(this.element,'top') || '0')]);
297 parseInt(Element.getStyle(this.element,'top') || '0')]);
298 },
298 },
299
299
300 initDrag: function(event) {
300 initDrag: function(event) {
301 if(!Object.isUndefined(Draggable._dragging[this.element]) &&
301 if(!Object.isUndefined(Draggable._dragging[this.element]) &&
302 Draggable._dragging[this.element]) return;
302 Draggable._dragging[this.element]) return;
303 if(Event.isLeftClick(event)) {
303 if(Event.isLeftClick(event)) {
304 // abort on form elements, fixes a Firefox issue
304 // abort on form elements, fixes a Firefox issue
305 var src = Event.element(event);
305 var src = Event.element(event);
306 if((tag_name = src.tagName.toUpperCase()) && (
306 if((tag_name = src.tagName.toUpperCase()) && (
307 tag_name=='INPUT' ||
307 tag_name=='INPUT' ||
308 tag_name=='SELECT' ||
308 tag_name=='SELECT' ||
309 tag_name=='OPTION' ||
309 tag_name=='OPTION' ||
310 tag_name=='BUTTON' ||
310 tag_name=='BUTTON' ||
311 tag_name=='TEXTAREA')) return;
311 tag_name=='TEXTAREA')) return;
312
312
313 var pointer = [Event.pointerX(event), Event.pointerY(event)];
313 var pointer = [Event.pointerX(event), Event.pointerY(event)];
314 var pos = Position.cumulativeOffset(this.element);
314 var pos = Position.cumulativeOffset(this.element);
315 this.offset = [0,1].map( function(i) { return (pointer[i] - pos[i]) });
315 this.offset = [0,1].map( function(i) { return (pointer[i] - pos[i]) });
316
316
317 Draggables.activate(this);
317 Draggables.activate(this);
318 Event.stop(event);
318 Event.stop(event);
319 }
319 }
320 },
320 },
321
321
322 startDrag: function(event) {
322 startDrag: function(event) {
323 this.dragging = true;
323 this.dragging = true;
324 if(!this.delta)
324 if(!this.delta)
325 this.delta = this.currentDelta();
325 this.delta = this.currentDelta();
326
326
327 if(this.options.zindex) {
327 if(this.options.zindex) {
328 this.originalZ = parseInt(Element.getStyle(this.element,'z-index') || 0);
328 this.originalZ = parseInt(Element.getStyle(this.element,'z-index') || 0);
329 this.element.style.zIndex = this.options.zindex;
329 this.element.style.zIndex = this.options.zindex;
330 }
330 }
331
331
332 if(this.options.ghosting) {
332 if(this.options.ghosting) {
333 this._clone = this.element.cloneNode(true);
333 this._clone = this.element.cloneNode(true);
334 - this.element._originallyAbsolute = (this.element.getStyle('position') == 'absolute');
334 + this._originallyAbsolute = (this.element.getStyle('position') == 'absolute');
335 - if (!this.element._originallyAbsolute)
335 + if (!this._originallyAbsolute)
336 Position.absolutize(this.element);
336 Position.absolutize(this.element);
337 this.element.parentNode.insertBefore(this._clone, this.element);
337 this.element.parentNode.insertBefore(this._clone, this.element);
338 }
338 }
339
339
340 if(this.options.scroll) {
340 if(this.options.scroll) {
341 if (this.options.scroll == window) {
341 if (this.options.scroll == window) {
342 var where = this._getWindowScroll(this.options.scroll);
342 var where = this._getWindowScroll(this.options.scroll);
343 this.originalScrollLeft = where.left;
343 this.originalScrollLeft = where.left;
344 this.originalScrollTop = where.top;
344 this.originalScrollTop = where.top;
345 } else {
345 } else {
346 this.originalScrollLeft = this.options.scroll.scrollLeft;
346 this.originalScrollLeft = this.options.scroll.scrollLeft;
347 this.originalScrollTop = this.options.scroll.scrollTop;
347 this.originalScrollTop = this.options.scroll.scrollTop;
348 }
348 }
349 }
349 }
350
350
351 Draggables.notify('onStart', this, event);
351 Draggables.notify('onStart', this, event);
352
352
353 if(this.options.starteffect) this.options.starteffect(this.element);
353 if(this.options.starteffect) this.options.starteffect(this.element);
354 },
354 },
355
355
356 updateDrag: function(event, pointer) {
356 updateDrag: function(event, pointer) {
357 if(!this.dragging) this.startDrag(event);
357 if(!this.dragging) this.startDrag(event);
358
358
359 if(!this.options.quiet){
359 if(!this.options.quiet){
360 Position.prepare();
360 Position.prepare();
361 Droppables.show(pointer, this.element);
361 Droppables.show(pointer, this.element);
362 }
362 }
363
363
364 Draggables.notify('onDrag', this, event);
364 Draggables.notify('onDrag', this, event);
365
365
366 this.draw(pointer);
366 this.draw(pointer);
367 if(this.options.change) this.options.change(this);
367 if(this.options.change) this.options.change(this);
368
368
369 if(this.options.scroll) {
369 if(this.options.scroll) {
370 this.stopScrolling();
370 this.stopScrolling();
371
371
372 var p;
372 var p;
373 if (this.options.scroll == window) {
373 if (this.options.scroll == window) {
374 with(this._getWindowScroll(this.options.scroll)) { p = [ left, top, left+width, top+height ]; }
374 with(this._getWindowScroll(this.options.scroll)) { p = [ left, top, left+width, top+height ]; }
375 } else {
375 } else {
376 p = Position.page(this.options.scroll);
376 p = Position.page(this.options.scroll);
377 p[0] += this.options.scroll.scrollLeft + Position.deltaX;
377 p[0] += this.options.scroll.scrollLeft + Position.deltaX;
378 p[1] += this.options.scroll.scrollTop + Position.deltaY;
378 p[1] += this.options.scroll.scrollTop + Position.deltaY;
379 p.push(p[0]+this.options.scroll.offsetWidth);
379 p.push(p[0]+this.options.scroll.offsetWidth);
380 p.push(p[1]+this.options.scroll.offsetHeight);
380 p.push(p[1]+this.options.scroll.offsetHeight);
381 }
381 }
382 var speed = [0,0];
382 var speed = [0,0];
383 if(pointer[0] < (p[0]+this.options.scrollSensitivity)) speed[0] = pointer[0]-(p[0]+this.options.scrollSensitivity);
383 if(pointer[0] < (p[0]+this.options.scrollSensitivity)) speed[0] = pointer[0]-(p[0]+this.options.scrollSensitivity);
384 if(pointer[1] < (p[1]+this.options.scrollSensitivity)) speed[1] = pointer[1]-(p[1]+this.options.scrollSensitivity);
384 if(pointer[1] < (p[1]+this.options.scrollSensitivity)) speed[1] = pointer[1]-(p[1]+this.options.scrollSensitivity);
385 if(pointer[0] > (p[2]-this.options.scrollSensitivity)) speed[0] = pointer[0]-(p[2]-this.options.scrollSensitivity);
385 if(pointer[0] > (p[2]-this.options.scrollSensitivity)) speed[0] = pointer[0]-(p[2]-this.options.scrollSensitivity);
386 if(pointer[1] > (p[3]-this.options.scrollSensitivity)) speed[1] = pointer[1]-(p[3]-this.options.scrollSensitivity);
386 if(pointer[1] > (p[3]-this.options.scrollSensitivity)) speed[1] = pointer[1]-(p[3]-this.options.scrollSensitivity);
387 this.startScrolling(speed);
387 this.startScrolling(speed);
388 }
388 }
389
389
390 // fix AppleWebKit rendering
390 // fix AppleWebKit rendering
391 if(Prototype.Browser.WebKit) window.scrollBy(0,0);
391 if(Prototype.Browser.WebKit) window.scrollBy(0,0);
392
392
393 Event.stop(event);
393 Event.stop(event);
394 },
394 },
395
395
396 finishDrag: function(event, success) {
396 finishDrag: function(event, success) {
397 this.dragging = false;
397 this.dragging = false;
398
398
399 if(this.options.quiet){
399 if(this.options.quiet){
400 Position.prepare();
400 Position.prepare();
401 var pointer = [Event.pointerX(event), Event.pointerY(event)];
401 var pointer = [Event.pointerX(event), Event.pointerY(event)];
402 Droppables.show(pointer, this.element);
402 Droppables.show(pointer, this.element);
403 }
403 }
404
404
405 if(this.options.ghosting) {
405 if(this.options.ghosting) {
406 - if (!this.element._originallyAbsolute)
406 + if (!this._originallyAbsolute)
407 Position.relativize(this.element);
407 Position.relativize(this.element);
408 - delete this.element._originallyAbsolute;
408 + delete this._originallyAbsolute;
409 Element.remove(this._clone);
409 Element.remove(this._clone);
410 this._clone = null;
410 this._clone = null;
411 }
411 }
412
412
413 var dropped = false;
413 var dropped = false;
414 if(success) {
414 if(success) {
415 dropped = Droppables.fire(event, this.element);
415 dropped = Droppables.fire(event, this.element);
416 if (!dropped) dropped = false;
416 if (!dropped) dropped = false;
417 }
417 }
418 if(dropped && this.options.onDropped) this.options.onDropped(this.element);
418 if(dropped && this.options.onDropped) this.options.onDropped(this.element);
419 Draggables.notify('onEnd', this, event);
419 Draggables.notify('onEnd', this, event);
420
420
421 var revert = this.options.revert;
421 var revert = this.options.revert;
422 if(revert && Object.isFunction(revert)) revert = revert(this.element);
422 if(revert && Object.isFunction(revert)) revert = revert(this.element);
423
423
424 var d = this.currentDelta();
424 var d = this.currentDelta();
425 if(revert && this.options.reverteffect) {
425 if(revert && this.options.reverteffect) {
426 if (dropped == 0 || revert != 'failure')
426 if (dropped == 0 || revert != 'failure')
427 this.options.reverteffect(this.element,
427 this.options.reverteffect(this.element,
428 d[1]-this.delta[1], d[0]-this.delta[0]);
428 d[1]-this.delta[1], d[0]-this.delta[0]);
429 } else {
429 } else {
430 this.delta = d;
430 this.delta = d;
431 }
431 }
432
432
433 if(this.options.zindex)
433 if(this.options.zindex)
434 this.element.style.zIndex = this.originalZ;
434 this.element.style.zIndex = this.originalZ;
435
435
436 if(this.options.endeffect)
436 if(this.options.endeffect)
437 this.options.endeffect(this.element);
437 this.options.endeffect(this.element);
438
438
439 Draggables.deactivate(this);
439 Draggables.deactivate(this);
440 Droppables.reset();
440 Droppables.reset();
441 },
441 },
442
442
443 keyPress: function(event) {
443 keyPress: function(event) {
444 if(event.keyCode!=Event.KEY_ESC) return;
444 if(event.keyCode!=Event.KEY_ESC) return;
445 this.finishDrag(event, false);
445 this.finishDrag(event, false);
446 Event.stop(event);
446 Event.stop(event);
447 },
447 },
448
448
449 endDrag: function(event) {
449 endDrag: function(event) {
450 if(!this.dragging) return;
450 if(!this.dragging) return;
451 this.stopScrolling();
451 this.stopScrolling();
452 this.finishDrag(event, true);
452 this.finishDrag(event, true);
453 Event.stop(event);
453 Event.stop(event);
454 },
454 },
455
455
456 draw: function(point) {
456 draw: function(point) {
457 var pos = Position.cumulativeOffset(this.element);
457 var pos = Position.cumulativeOffset(this.element);
458 if(this.options.ghosting) {
458 if(this.options.ghosting) {
459 var r = Position.realOffset(this.element);
459 var r = Position.realOffset(this.element);
460 pos[0] += r[0] - Position.deltaX; pos[1] += r[1] - Position.deltaY;
460 pos[0] += r[0] - Position.deltaX; pos[1] += r[1] - Position.deltaY;
461 }
461 }
462
462
463 var d = this.currentDelta();
463 var d = this.currentDelta();
464 pos[0] -= d[0]; pos[1] -= d[1];
464 pos[0] -= d[0]; pos[1] -= d[1];
465
465
466 if(this.options.scroll && (this.options.scroll != window && this._isScrollChild)) {
466 if(this.options.scroll && (this.options.scroll != window && this._isScrollChild)) {
467 pos[0] -= this.options.scroll.scrollLeft-this.originalScrollLeft;
467 pos[0] -= this.options.scroll.scrollLeft-this.originalScrollLeft;
468 pos[1] -= this.options.scroll.scrollTop-this.originalScrollTop;
468 pos[1] -= this.options.scroll.scrollTop-this.originalScrollTop;
469 }
469 }
470
470
471 var p = [0,1].map(function(i){
471 var p = [0,1].map(function(i){
472 return (point[i]-pos[i]-this.offset[i])
472 return (point[i]-pos[i]-this.offset[i])
473 }.bind(this));
473 }.bind(this));
474
474
475 if(this.options.snap) {
475 if(this.options.snap) {
476 if(Object.isFunction(this.options.snap)) {
476 if(Object.isFunction(this.options.snap)) {
477 p = this.options.snap(p[0],p[1],this);
477 p = this.options.snap(p[0],p[1],this);
478 } else {
478 } else {
479 if(Object.isArray(this.options.snap)) {
479 if(Object.isArray(this.options.snap)) {
480 p = p.map( function(v, i) {
480 p = p.map( function(v, i) {
481 - return (v/this.options.snap[i]).round()*this.options.snap[i] }.bind(this))
481 + return (v/this.options.snap[i]).round()*this.options.snap[i] }.bind(this));
482 } else {
482 } else {
483 p = p.map( function(v) {
483 p = p.map( function(v) {
484 - return (v/this.options.snap).round()*this.options.snap }.bind(this))
484 + return (v/this.options.snap).round()*this.options.snap }.bind(this));
485 }
485 }
486 }}
486 }}
487
487
488 var style = this.element.style;
488 var style = this.element.style;
489 if((!this.options.constraint) || (this.options.constraint=='horizontal'))
489 if((!this.options.constraint) || (this.options.constraint=='horizontal'))
490 style.left = p[0] + "px";
490 style.left = p[0] + "px";
491 if((!this.options.constraint) || (this.options.constraint=='vertical'))
491 if((!this.options.constraint) || (this.options.constraint=='vertical'))
492 style.top = p[1] + "px";
492 style.top = p[1] + "px";
493
493
494 if(style.visibility=="hidden") style.visibility = ""; // fix gecko rendering
494 if(style.visibility=="hidden") style.visibility = ""; // fix gecko rendering
495 },
495 },
496
496
497 stopScrolling: function() {
497 stopScrolling: function() {
498 if(this.scrollInterval) {
498 if(this.scrollInterval) {
499 clearInterval(this.scrollInterval);
499 clearInterval(this.scrollInterval);
500 this.scrollInterval = null;
500 this.scrollInterval = null;
501 Draggables._lastScrollPointer = null;
501 Draggables._lastScrollPointer = null;
502 }
502 }
503 },
503 },
504
504
505 startScrolling: function(speed) {
505 startScrolling: function(speed) {
506 if(!(speed[0] || speed[1])) return;
506 if(!(speed[0] || speed[1])) return;
507 this.scrollSpeed = [speed[0]*this.options.scrollSpeed,speed[1]*this.options.scrollSpeed];
507 this.scrollSpeed = [speed[0]*this.options.scrollSpeed,speed[1]*this.options.scrollSpeed];
508 this.lastScrolled = new Date();
508 this.lastScrolled = new Date();
509 this.scrollInterval = setInterval(this.scroll.bind(this), 10);
509 this.scrollInterval = setInterval(this.scroll.bind(this), 10);
510 },
510 },
511
511
512 scroll: function() {
512 scroll: function() {
513 var current = new Date();
513 var current = new Date();
514 var delta = current - this.lastScrolled;
514 var delta = current - this.lastScrolled;
515 this.lastScrolled = current;
515 this.lastScrolled = current;
516 if(this.options.scroll == window) {
516 if(this.options.scroll == window) {
517 with (this._getWindowScroll(this.options.scroll)) {
517 with (this._getWindowScroll(this.options.scroll)) {
518 if (this.scrollSpeed[0] || this.scrollSpeed[1]) {
518 if (this.scrollSpeed[0] || this.scrollSpeed[1]) {
519 var d = delta / 1000;
519 var d = delta / 1000;
520 this.options.scroll.scrollTo( left + d*this.scrollSpeed[0], top + d*this.scrollSpeed[1] );
520 this.options.scroll.scrollTo( left + d*this.scrollSpeed[0], top + d*this.scrollSpeed[1] );
521 }
521 }
522 }
522 }
523 } else {
523 } else {
524 this.options.scroll.scrollLeft += this.scrollSpeed[0] * delta / 1000;
524 this.options.scroll.scrollLeft += this.scrollSpeed[0] * delta / 1000;
525 this.options.scroll.scrollTop += this.scrollSpeed[1] * delta / 1000;
525 this.options.scroll.scrollTop += this.scrollSpeed[1] * delta / 1000;
526 }
526 }
527
527
528 Position.prepare();
528 Position.prepare();
529 Droppables.show(Draggables._lastPointer, this.element);
529 Droppables.show(Draggables._lastPointer, this.element);
530 Draggables.notify('onDrag', this);
530 Draggables.notify('onDrag', this);
531 if (this._isScrollChild) {
531 if (this._isScrollChild) {
532 Draggables._lastScrollPointer = Draggables._lastScrollPointer || $A(Draggables._lastPointer);
532 Draggables._lastScrollPointer = Draggables._lastScrollPointer || $A(Draggables._lastPointer);
533 Draggables._lastScrollPointer[0] += this.scrollSpeed[0] * delta / 1000;
533 Draggables._lastScrollPointer[0] += this.scrollSpeed[0] * delta / 1000;
534 Draggables._lastScrollPointer[1] += this.scrollSpeed[1] * delta / 1000;
534 Draggables._lastScrollPointer[1] += this.scrollSpeed[1] * delta / 1000;
535 if (Draggables._lastScrollPointer[0] < 0)
535 if (Draggables._lastScrollPointer[0] < 0)
536 Draggables._lastScrollPointer[0] = 0;
536 Draggables._lastScrollPointer[0] = 0;
537 if (Draggables._lastScrollPointer[1] < 0)
537 if (Draggables._lastScrollPointer[1] < 0)
538 Draggables._lastScrollPointer[1] = 0;
538 Draggables._lastScrollPointer[1] = 0;
539 this.draw(Draggables._lastScrollPointer);
539 this.draw(Draggables._lastScrollPointer);
540 }
540 }
541
541
542 if(this.options.change) this.options.change(this);
542 if(this.options.change) this.options.change(this);
543 },
543 },
544
544
545 _getWindowScroll: function(w) {
545 _getWindowScroll: function(w) {
546 var T, L, W, H;
546 var T, L, W, H;
547 with (w.document) {
547 with (w.document) {
548 if (w.document.documentElement && documentElement.scrollTop) {
548 if (w.document.documentElement && documentElement.scrollTop) {
549 T = documentElement.scrollTop;
549 T = documentElement.scrollTop;
550 L = documentElement.scrollLeft;
550 L = documentElement.scrollLeft;
551 } else if (w.document.body) {
551 } else if (w.document.body) {
552 T = body.scrollTop;
552 T = body.scrollTop;
553 L = body.scrollLeft;
553 L = body.scrollLeft;
554 }
554 }
555 if (w.innerWidth) {
555 if (w.innerWidth) {
556 W = w.innerWidth;
556 W = w.innerWidth;
557 H = w.innerHeight;
557 H = w.innerHeight;
558 } else if (w.document.documentElement && documentElement.clientWidth) {
558 } else if (w.document.documentElement && documentElement.clientWidth) {
559 W = documentElement.clientWidth;
559 W = documentElement.clientWidth;
560 H = documentElement.clientHeight;
560 H = documentElement.clientHeight;
561 } else {
561 } else {
562 W = body.offsetWidth;
562 W = body.offsetWidth;
563 - H = body.offsetHeight
563 + H = body.offsetHeight;
564 }
564 }
565 }
565 }
566 return { top: T, left: L, width: W, height: H };
566 return { top: T, left: L, width: W, height: H };
567 }
567 }
568 });
568 });
569
569
570 Draggable._dragging = { };
570 Draggable._dragging = { };
571
571
572 /*--------------------------------------------------------------------------*/
572 /*--------------------------------------------------------------------------*/
573
573
574 var SortableObserver = Class.create({
574 var SortableObserver = Class.create({
575 initialize: function(element, observer) {
575 initialize: function(element, observer) {
576 this.element = $(element);
576 this.element = $(element);
577 this.observer = observer;
577 this.observer = observer;
578 this.lastValue = Sortable.serialize(this.element);
578 this.lastValue = Sortable.serialize(this.element);
579 },
579 },
580
580
581 onStart: function() {
581 onStart: function() {
582 this.lastValue = Sortable.serialize(this.element);
582 this.lastValue = Sortable.serialize(this.element);
583 },
583 },
584
584
585 onEnd: function() {
585 onEnd: function() {
586 Sortable.unmark();
586 Sortable.unmark();
587 if(this.lastValue != Sortable.serialize(this.element))
587 if(this.lastValue != Sortable.serialize(this.element))
588 this.observer(this.element)
588 this.observer(this.element)
589 }
589 }
590 });
590 });
591
591
592 var Sortable = {
592 var Sortable = {
593 SERIALIZE_RULE: /^[^_\-](?:[A-Za-z0-9\-\_]*)[_](.*)$/,
593 SERIALIZE_RULE: /^[^_\-](?:[A-Za-z0-9\-\_]*)[_](.*)$/,
594
594
595 sortables: { },
595 sortables: { },
596
596
597 _findRootElement: function(element) {
597 _findRootElement: function(element) {
598 while (element.tagName.toUpperCase() != "BODY") {
598 while (element.tagName.toUpperCase() != "BODY") {
599 if(element.id && Sortable.sortables[element.id]) return element;
599 if(element.id && Sortable.sortables[element.id]) return element;
600 element = element.parentNode;
600 element = element.parentNode;
601 }
601 }
602 },
602 },
603
603
604 options: function(element) {
604 options: function(element) {
605 element = Sortable._findRootElement($(element));
605 element = Sortable._findRootElement($(element));
606 if(!element) return;
606 if(!element) return;
607 return Sortable.sortables[element.id];
607 return Sortable.sortables[element.id];
608 },
608 },
609
609
610 destroy: function(element){
610 destroy: function(element){
611 - var s = Sortable.options(element);
611 + element = $(element);
612 + var s = Sortable.sortables[element.id];
612
613
613 if(s) {
614 if(s) {
614 Draggables.removeObserver(s.element);
615 Draggables.removeObserver(s.element);
615 s.droppables.each(function(d){ Droppables.remove(d) });
616 s.droppables.each(function(d){ Droppables.remove(d) });
616 s.draggables.invoke('destroy');
617 s.draggables.invoke('destroy');
617
618
618 delete Sortable.sortables[s.element.id];
619 delete Sortable.sortables[s.element.id];
619 }
620 }
620 },
621 },
621
622
622 create: function(element) {
623 create: function(element) {
623 element = $(element);
624 element = $(element);
624 var options = Object.extend({
625 var options = Object.extend({
625 element: element,
626 element: element,
626 tag: 'li', // assumes li children, override with tag: 'tagname'
627 tag: 'li', // assumes li children, override with tag: 'tagname'
627 dropOnEmpty: false,
628 dropOnEmpty: false,
628 tree: false,
629 tree: false,
629 treeTag: 'ul',
630 treeTag: 'ul',
630 overlap: 'vertical', // one of 'vertical', 'horizontal'
631 overlap: 'vertical', // one of 'vertical', 'horizontal'
631 constraint: 'vertical', // one of 'vertical', 'horizontal', false
632 constraint: 'vertical', // one of 'vertical', 'horizontal', false
632 containment: element, // also takes array of elements (or id's); or false
633 containment: element, // also takes array of elements (or id's); or false
633 handle: false, // or a CSS class
634 handle: false, // or a CSS class
634 only: false,
635 only: false,
635 delay: 0,
636 delay: 0,
636 hoverclass: null,
637 hoverclass: null,
637 ghosting: false,
638 ghosting: false,
638 quiet: false,
639 quiet: false,
639 scroll: false,
640 scroll: false,
640 scrollSensitivity: 20,
641 scrollSensitivity: 20,
641 scrollSpeed: 15,
642 scrollSpeed: 15,
642 format: this.SERIALIZE_RULE,
643 format: this.SERIALIZE_RULE,
643
644
644 // these take arrays of elements or ids and can be
645 // these take arrays of elements or ids and can be
645 // used for better initialization performance
646 // used for better initialization performance
646 elements: false,
647 elements: false,
647 handles: false,
648 handles: false,
648
649
649 onChange: Prototype.emptyFunction,
650 onChange: Prototype.emptyFunction,
650 onUpdate: Prototype.emptyFunction
651 onUpdate: Prototype.emptyFunction
651 }, arguments[1] || { });
652 }, arguments[1] || { });
652
653
653 // clear any old sortable with same element
654 // clear any old sortable with same element
654 this.destroy(element);
655 this.destroy(element);
655
656
656 // build options for the draggables
657 // build options for the draggables
657 var options_for_draggable = {
658 var options_for_draggable = {
658 revert: true,
659 revert: true,
659 quiet: options.quiet,
660 quiet: options.quiet,
660 scroll: options.scroll,
661 scroll: options.scroll,
661 scrollSpeed: options.scrollSpeed,
662 scrollSpeed: options.scrollSpeed,
662 scrollSensitivity: options.scrollSensitivity,
663 scrollSensitivity: options.scrollSensitivity,
663 delay: options.delay,
664 delay: options.delay,
664 ghosting: options.ghosting,
665 ghosting: options.ghosting,
665 constraint: options.constraint,
666 constraint: options.constraint,
666 handle: options.handle };
667 handle: options.handle };
667
668
668 if(options.starteffect)
669 if(options.starteffect)
669 options_for_draggable.starteffect = options.starteffect;
670 options_for_draggable.starteffect = options.starteffect;
670
671
671 if(options.reverteffect)
672 if(options.reverteffect)
672 options_for_draggable.reverteffect = options.reverteffect;
673 options_for_draggable.reverteffect = options.reverteffect;
673 else
674 else
674 if(options.ghosting) options_for_draggable.reverteffect = function(element) {
675 if(options.ghosting) options_for_draggable.reverteffect = function(element) {
675 element.style.top = 0;
676 element.style.top = 0;
676 element.style.left = 0;
677 element.style.left = 0;
677 };
678 };
678
679
679 if(options.endeffect)
680 if(options.endeffect)
680 options_for_draggable.endeffect = options.endeffect;
681 options_for_draggable.endeffect = options.endeffect;
681
682
682 if(options.zindex)
683 if(options.zindex)
683 options_for_draggable.zindex = options.zindex;
684 options_for_draggable.zindex = options.zindex;
684
685
685 // build options for the droppables
686 // build options for the droppables
686 var options_for_droppable = {
687 var options_for_droppable = {
687 overlap: options.overlap,
688 overlap: options.overlap,
688 containment: options.containment,
689 containment: options.containment,
689 tree: options.tree,
690 tree: options.tree,
690 hoverclass: options.hoverclass,
691 hoverclass: options.hoverclass,
691 onHover: Sortable.onHover
692 onHover: Sortable.onHover
692 - }
693 + };
693
694
694 var options_for_tree = {
695 var options_for_tree = {
695 onHover: Sortable.onEmptyHover,
696 onHover: Sortable.onEmptyHover,
696 overlap: options.overlap,
697 overlap: options.overlap,
697 containment: options.containment,
698 containment: options.containment,
698 hoverclass: options.hoverclass
699 hoverclass: options.hoverclass
699 - }
700 + };
700
701
701 // fix for gecko engine
702 // fix for gecko engine
702 Element.cleanWhitespace(element);
703 Element.cleanWhitespace(element);
703
704
704 options.draggables = [];
705 options.draggables = [];
705 options.droppables = [];
706 options.droppables = [];
706
707
707 // drop on empty handling
708 // drop on empty handling
708 if(options.dropOnEmpty || options.tree) {
709 if(options.dropOnEmpty || options.tree) {
709 Droppables.add(element, options_for_tree);
710 Droppables.add(element, options_for_tree);
710 options.droppables.push(element);
711 options.droppables.push(element);
711 }
712 }
712
713
713 (options.elements || this.findElements(element, options) || []).each( function(e,i) {
714 (options.elements || this.findElements(element, options) || []).each( function(e,i) {
714 var handle = options.handles ? $(options.handles[i]) :
715 var handle = options.handles ? $(options.handles[i]) :
715 (options.handle ? $(e).select('.' + options.handle)[0] : e);
716 (options.handle ? $(e).select('.' + options.handle)[0] : e);
716 options.draggables.push(
717 options.draggables.push(
717 new Draggable(e, Object.extend(options_for_draggable, { handle: handle })));
718 new Draggable(e, Object.extend(options_for_draggable, { handle: handle })));
718 Droppables.add(e, options_for_droppable);
719 Droppables.add(e, options_for_droppable);
719 if(options.tree) e.treeNode = element;
720 if(options.tree) e.treeNode = element;
720 options.droppables.push(e);
721 options.droppables.push(e);
721 });
722 });
722
723
723 if(options.tree) {
724 if(options.tree) {
724 (Sortable.findTreeElements(element, options) || []).each( function(e) {
725 (Sortable.findTreeElements(element, options) || []).each( function(e) {
725 Droppables.add(e, options_for_tree);
726 Droppables.add(e, options_for_tree);
726 e.treeNode = element;
727 e.treeNode = element;
727 options.droppables.push(e);
728 options.droppables.push(e);
728 });
729 });
729 }
730 }
730
731
731 // keep reference
732 // keep reference
732 this.sortables[element.id] = options;
733 this.sortables[element.id] = options;
733
734
734 // for onupdate
735 // for onupdate
735 Draggables.addObserver(new SortableObserver(element, options.onUpdate));
736 Draggables.addObserver(new SortableObserver(element, options.onUpdate));
736
737
737 },
738 },
738
739
739 // return all suitable-for-sortable elements in a guaranteed order
740 // return all suitable-for-sortable elements in a guaranteed order
740 findElements: function(element, options) {
741 findElements: function(element, options) {
741 return Element.findChildren(
742 return Element.findChildren(
742 element, options.only, options.tree ? true : false, options.tag);
743 element, options.only, options.tree ? true : false, options.tag);
743 },
744 },
744
745
745 findTreeElements: function(element, options) {
746 findTreeElements: function(element, options) {
746 return Element.findChildren(
747 return Element.findChildren(
747 element, options.only, options.tree ? true : false, options.treeTag);
748 element, options.only, options.tree ? true : false, options.treeTag);
@@ -806,167 +807,167
806
807
807 Sortable.options(oldParentNode).onChange(element);
808 Sortable.options(oldParentNode).onChange(element);
808 droponOptions.onChange(element);
809 droponOptions.onChange(element);
809 }
810 }
810 },
811 },
811
812
812 unmark: function() {
813 unmark: function() {
813 if(Sortable._marker) Sortable._marker.hide();
814 if(Sortable._marker) Sortable._marker.hide();
814 },
815 },
815
816
816 mark: function(dropon, position) {
817 mark: function(dropon, position) {
817 // mark on ghosting only
818 // mark on ghosting only
818 var sortable = Sortable.options(dropon.parentNode);
819 var sortable = Sortable.options(dropon.parentNode);
819 if(sortable && !sortable.ghosting) return;
820 if(sortable && !sortable.ghosting) return;
820
821
821 if(!Sortable._marker) {
822 if(!Sortable._marker) {
822 Sortable._marker =
823 Sortable._marker =
823 ($('dropmarker') || Element.extend(document.createElement('DIV'))).
824 ($('dropmarker') || Element.extend(document.createElement('DIV'))).
824 hide().addClassName('dropmarker').setStyle({position:'absolute'});
825 hide().addClassName('dropmarker').setStyle({position:'absolute'});
825 document.getElementsByTagName("body").item(0).appendChild(Sortable._marker);
826 document.getElementsByTagName("body").item(0).appendChild(Sortable._marker);
826 }
827 }
827 var offsets = Position.cumulativeOffset(dropon);
828 var offsets = Position.cumulativeOffset(dropon);
828 Sortable._marker.setStyle({left: offsets[0]+'px', top: offsets[1] + 'px'});
829 Sortable._marker.setStyle({left: offsets[0]+'px', top: offsets[1] + 'px'});
829
830
830 if(position=='after')
831 if(position=='after')
831 if(sortable.overlap == 'horizontal')
832 if(sortable.overlap == 'horizontal')
832 Sortable._marker.setStyle({left: (offsets[0]+dropon.clientWidth) + 'px'});
833 Sortable._marker.setStyle({left: (offsets[0]+dropon.clientWidth) + 'px'});
833 else
834 else
834 Sortable._marker.setStyle({top: (offsets[1]+dropon.clientHeight) + 'px'});
835 Sortable._marker.setStyle({top: (offsets[1]+dropon.clientHeight) + 'px'});
835
836
836 Sortable._marker.show();
837 Sortable._marker.show();
837 },
838 },
838
839
839 _tree: function(element, options, parent) {
840 _tree: function(element, options, parent) {
840 var children = Sortable.findElements(element, options) || [];
841 var children = Sortable.findElements(element, options) || [];
841
842
842 for (var i = 0; i < children.length; ++i) {
843 for (var i = 0; i < children.length; ++i) {
843 var match = children[i].id.match(options.format);
844 var match = children[i].id.match(options.format);
844
845
845 if (!match) continue;
846 if (!match) continue;
846
847
847 var child = {
848 var child = {
848 id: encodeURIComponent(match ? match[1] : null),
849 id: encodeURIComponent(match ? match[1] : null),
849 element: element,
850 element: element,
850 parent: parent,
851 parent: parent,
851 children: [],
852 children: [],
852 position: parent.children.length,
853 position: parent.children.length,
853 container: $(children[i]).down(options.treeTag)
854 container: $(children[i]).down(options.treeTag)
854 - }
855 + };
855
856
856 /* Get the element containing the children and recurse over it */
857 /* Get the element containing the children and recurse over it */
857 if (child.container)
858 if (child.container)
858 - this._tree(child.container, options, child)
859 + this._tree(child.container, options, child);
859
860
860 parent.children.push (child);
861 parent.children.push (child);
861 }
862 }
862
863
863 return parent;
864 return parent;
864 },
865 },
865
866
866 tree: function(element) {
867 tree: function(element) {
867 element = $(element);
868 element = $(element);
868 var sortableOptions = this.options(element);
869 var sortableOptions = this.options(element);
869 var options = Object.extend({
870 var options = Object.extend({
870 tag: sortableOptions.tag,
871 tag: sortableOptions.tag,
871 treeTag: sortableOptions.treeTag,
872 treeTag: sortableOptions.treeTag,
872 only: sortableOptions.only,
873 only: sortableOptions.only,
873 name: element.id,
874 name: element.id,
874 format: sortableOptions.format
875 format: sortableOptions.format
875 }, arguments[1] || { });
876 }, arguments[1] || { });
876
877
877 var root = {
878 var root = {
878 id: null,
879 id: null,
879 parent: null,
880 parent: null,
880 children: [],
881 children: [],
881 container: element,
882 container: element,
882 position: 0
883 position: 0
883 - }
884 + };
884
885
885 return Sortable._tree(element, options, root);
886 return Sortable._tree(element, options, root);
886 },
887 },
887
888
888 /* Construct a [i] index for a particular node */
889 /* Construct a [i] index for a particular node */
889 _constructIndex: function(node) {
890 _constructIndex: function(node) {
890 var index = '';
891 var index = '';
891 do {
892 do {
892 if (node.id) index = '[' + node.position + ']' + index;
893 if (node.id) index = '[' + node.position + ']' + index;
893 } while ((node = node.parent) != null);
894 } while ((node = node.parent) != null);
894 return index;
895 return index;
895 },
896 },
896
897
897 sequence: function(element) {
898 sequence: function(element) {
898 element = $(element);
899 element = $(element);
899 var options = Object.extend(this.options(element), arguments[1] || { });
900 var options = Object.extend(this.options(element), arguments[1] || { });
900
901
901 return $(this.findElements(element, options) || []).map( function(item) {
902 return $(this.findElements(element, options) || []).map( function(item) {
902 return item.id.match(options.format) ? item.id.match(options.format)[1] : '';
903 return item.id.match(options.format) ? item.id.match(options.format)[1] : '';
903 });
904 });
904 },
905 },
905
906
906 setSequence: function(element, new_sequence) {
907 setSequence: function(element, new_sequence) {
907 element = $(element);
908 element = $(element);
908 var options = Object.extend(this.options(element), arguments[2] || { });
909 var options = Object.extend(this.options(element), arguments[2] || { });
909
910
910 var nodeMap = { };
911 var nodeMap = { };
911 this.findElements(element, options).each( function(n) {
912 this.findElements(element, options).each( function(n) {
912 if (n.id.match(options.format))
913 if (n.id.match(options.format))
913 nodeMap[n.id.match(options.format)[1]] = [n, n.parentNode];
914 nodeMap[n.id.match(options.format)[1]] = [n, n.parentNode];
914 n.parentNode.removeChild(n);
915 n.parentNode.removeChild(n);
915 });
916 });
916
917
917 new_sequence.each(function(ident) {
918 new_sequence.each(function(ident) {
918 var n = nodeMap[ident];
919 var n = nodeMap[ident];
919 if (n) {
920 if (n) {
920 n[1].appendChild(n[0]);
921 n[1].appendChild(n[0]);
921 delete nodeMap[ident];
922 delete nodeMap[ident];
922 }
923 }
923 });
924 });
924 },
925 },
925
926
926 serialize: function(element) {
927 serialize: function(element) {
927 element = $(element);
928 element = $(element);
928 var options = Object.extend(Sortable.options(element), arguments[1] || { });
929 var options = Object.extend(Sortable.options(element), arguments[1] || { });
929 var name = encodeURIComponent(
930 var name = encodeURIComponent(
930 (arguments[1] && arguments[1].name) ? arguments[1].name : element.id);
931 (arguments[1] && arguments[1].name) ? arguments[1].name : element.id);
931
932
932 if (options.tree) {
933 if (options.tree) {
933 return Sortable.tree(element, arguments[1]).children.map( function (item) {
934 return Sortable.tree(element, arguments[1]).children.map( function (item) {
934 return [name + Sortable._constructIndex(item) + "[id]=" +
935 return [name + Sortable._constructIndex(item) + "[id]=" +
935 encodeURIComponent(item.id)].concat(item.children.map(arguments.callee));
936 encodeURIComponent(item.id)].concat(item.children.map(arguments.callee));
936 }).flatten().join('&');
937 }).flatten().join('&');
937 } else {
938 } else {
938 return Sortable.sequence(element, arguments[1]).map( function(item) {
939 return Sortable.sequence(element, arguments[1]).map( function(item) {
939 return name + "[]=" + encodeURIComponent(item);
940 return name + "[]=" + encodeURIComponent(item);
940 }).join('&');
941 }).join('&');
941 }
942 }
942 }
943 }
943 - }
944 + };
944
945
945 // Returns true if child is contained within element
946 // Returns true if child is contained within element
946 Element.isParent = function(child, element) {
947 Element.isParent = function(child, element) {
947 if (!child.parentNode || child == element) return false;
948 if (!child.parentNode || child == element) return false;
948 if (child.parentNode == element) return true;
949 if (child.parentNode == element) return true;
949 return Element.isParent(child.parentNode, element);
950 return Element.isParent(child.parentNode, element);
950 - }
951 + };
951
952
952 Element.findChildren = function(element, only, recursive, tagName) {
953 Element.findChildren = function(element, only, recursive, tagName) {
953 if(!element.hasChildNodes()) return null;
954 if(!element.hasChildNodes()) return null;
954 tagName = tagName.toUpperCase();
955 tagName = tagName.toUpperCase();
955 if(only) only = [only].flatten();
956 if(only) only = [only].flatten();
956 var elements = [];
957 var elements = [];
957 $A(element.childNodes).each( function(e) {
958 $A(element.childNodes).each( function(e) {
958 if(e.tagName && e.tagName.toUpperCase()==tagName &&
959 if(e.tagName && e.tagName.toUpperCase()==tagName &&
959 (!only || (Element.classNames(e).detect(function(v) { return only.include(v) }))))
960 (!only || (Element.classNames(e).detect(function(v) { return only.include(v) }))))
960 elements.push(e);
961 elements.push(e);
961 if(recursive) {
962 if(recursive) {
962 var grandchildren = Element.findChildren(e, only, recursive, tagName);
963 var grandchildren = Element.findChildren(e, only, recursive, tagName);
963 if(grandchildren) elements.push(grandchildren);
964 if(grandchildren) elements.push(grandchildren);
964 }
965 }
965 });
966 });
966
967
967 return (elements.length>0 ? elements.flatten() : []);
968 return (elements.length>0 ? elements.flatten() : []);
968 - }
969 + };
969
970
970 Element.offsetSize = function (element, type) {
971 Element.offsetSize = function (element, type) {
971 return element['offset' + ((type=='vertical' || type=='height') ? 'Height' : 'Width')];
972 return element['offset' + ((type=='vertical' || type=='height') ? 'Height' : 'Width')];
972 - }
973 + }; No newline at end of file
@@ -25,115 +25,110
25
25
26 /*--------------------------------------------------------------------------*/
26 /*--------------------------------------------------------------------------*/
27
27
28 Element.collectTextNodes = function(element) {
28 Element.collectTextNodes = function(element) {
29 return $A($(element).childNodes).collect( function(node) {
29 return $A($(element).childNodes).collect( function(node) {
30 return (node.nodeType==3 ? node.nodeValue :
30 return (node.nodeType==3 ? node.nodeValue :
31 (node.hasChildNodes() ? Element.collectTextNodes(node) : ''));
31 (node.hasChildNodes() ? Element.collectTextNodes(node) : ''));
32 }).flatten().join('');
32 }).flatten().join('');
33 };
33 };
34
34
35 Element.collectTextNodesIgnoreClass = function(element, className) {
35 Element.collectTextNodesIgnoreClass = function(element, className) {
36 return $A($(element).childNodes).collect( function(node) {
36 return $A($(element).childNodes).collect( function(node) {
37 return (node.nodeType==3 ? node.nodeValue :
37 return (node.nodeType==3 ? node.nodeValue :
38 ((node.hasChildNodes() && !Element.hasClassName(node,className)) ?
38 ((node.hasChildNodes() && !Element.hasClassName(node,className)) ?
39 Element.collectTextNodesIgnoreClass(node, className) : ''));
39 Element.collectTextNodesIgnoreClass(node, className) : ''));
40 }).flatten().join('');
40 }).flatten().join('');
41 };
41 };
42
42
43 Element.setContentZoom = function(element, percent) {
43 Element.setContentZoom = function(element, percent) {
44 element = $(element);
44 element = $(element);
45 element.setStyle({fontSize: (percent/100) + 'em'});
45 element.setStyle({fontSize: (percent/100) + 'em'});
46 if (Prototype.Browser.WebKit) window.scrollBy(0,0);
46 if (Prototype.Browser.WebKit) window.scrollBy(0,0);
47 return element;
47 return element;
48 };
48 };
49
49
50 Element.getInlineOpacity = function(element){
50 Element.getInlineOpacity = function(element){
51 return $(element).style.opacity || '';
51 return $(element).style.opacity || '';
52 };
52 };
53
53
54 Element.forceRerendering = function(element) {
54 Element.forceRerendering = function(element) {
55 try {
55 try {
56 element = $(element);
56 element = $(element);
57 var n = document.createTextNode(' ');
57 var n = document.createTextNode(' ');
58 element.appendChild(n);
58 element.appendChild(n);
59 element.removeChild(n);
59 element.removeChild(n);
60 } catch(e) { }
60 } catch(e) { }
61 };
61 };
62
62
63 /*--------------------------------------------------------------------------*/
63 /*--------------------------------------------------------------------------*/
64
64
65 var Effect = {
65 var Effect = {
66 _elementDoesNotExistError: {
66 _elementDoesNotExistError: {
67 name: 'ElementDoesNotExistError',
67 name: 'ElementDoesNotExistError',
68 message: 'The specified DOM element does not exist, but is required for this effect to operate'
68 message: 'The specified DOM element does not exist, but is required for this effect to operate'
69 },
69 },
70 Transitions: {
70 Transitions: {
71 linear: Prototype.K,
71 linear: Prototype.K,
72 sinoidal: function(pos) {
72 sinoidal: function(pos) {
73 - return (-Math.cos(pos*Math.PI)/2) + 0.5;
73 + return (-Math.cos(pos*Math.PI)/2) + .5;
74 },
74 },
75 reverse: function(pos) {
75 reverse: function(pos) {
76 return 1-pos;
76 return 1-pos;
77 },
77 },
78 flicker: function(pos) {
78 flicker: function(pos) {
79 - var pos = ((-Math.cos(pos*Math.PI)/4) + 0.75) + Math.random()/4;
79 + var pos = ((-Math.cos(pos*Math.PI)/4) + .75) + Math.random()/4;
80 return pos > 1 ? 1 : pos;
80 return pos > 1 ? 1 : pos;
81 },
81 },
82 wobble: function(pos) {
82 wobble: function(pos) {
83 - return (-Math.cos(pos*Math.PI*(9*pos))/2) + 0.5;
83 + return (-Math.cos(pos*Math.PI*(9*pos))/2) + .5;
84 },
84 },
85 pulse: function(pos, pulses) {
85 pulse: function(pos, pulses) {
86 - pulses = pulses || 5;
86 + return (-Math.cos((pos*((pulses||5)-.5)*2)*Math.PI)/2) + .5;
87 - return (
88 - ((pos % (1/pulses)) * pulses).round() == 0 ?
89 - ((pos * pulses * 2) - (pos * pulses * 2).floor()) :
90 - 1 - ((pos * pulses * 2) - (pos * pulses * 2).floor())
91 - );
92 },
87 },
93 spring: function(pos) {
88 spring: function(pos) {
94 return 1 - (Math.cos(pos * 4.5 * Math.PI) * Math.exp(-pos * 6));
89 return 1 - (Math.cos(pos * 4.5 * Math.PI) * Math.exp(-pos * 6));
95 },
90 },
96 none: function(pos) {
91 none: function(pos) {
97 return 0;
92 return 0;
98 },
93 },
99 full: function(pos) {
94 full: function(pos) {
100 return 1;
95 return 1;
101 }
96 }
102 },
97 },
103 DefaultOptions: {
98 DefaultOptions: {
104 duration: 1.0, // seconds
99 duration: 1.0, // seconds
105 fps: 100, // 100= assume 66fps max.
100 fps: 100, // 100= assume 66fps max.
106 sync: false, // true for combining
101 sync: false, // true for combining
107 from: 0.0,
102 from: 0.0,
108 to: 1.0,
103 to: 1.0,
109 delay: 0.0,
104 delay: 0.0,
110 queue: 'parallel'
105 queue: 'parallel'
111 },
106 },
112 tagifyText: function(element) {
107 tagifyText: function(element) {
113 var tagifyStyle = 'position:relative';
108 var tagifyStyle = 'position:relative';
114 if (Prototype.Browser.IE) tagifyStyle += ';zoom:1';
109 if (Prototype.Browser.IE) tagifyStyle += ';zoom:1';
115
110
116 element = $(element);
111 element = $(element);
117 $A(element.childNodes).each( function(child) {
112 $A(element.childNodes).each( function(child) {
118 if (child.nodeType==3) {
113 if (child.nodeType==3) {
119 child.nodeValue.toArray().each( function(character) {
114 child.nodeValue.toArray().each( function(character) {
120 element.insertBefore(
115 element.insertBefore(
121 new Element('span', {style: tagifyStyle}).update(
116 new Element('span', {style: tagifyStyle}).update(
122 character == ' ' ? String.fromCharCode(160) : character),
117 character == ' ' ? String.fromCharCode(160) : character),
123 child);
118 child);
124 });
119 });
125 Element.remove(child);
120 Element.remove(child);
126 }
121 }
127 });
122 });
128 },
123 },
129 multiple: function(element, effect) {
124 multiple: function(element, effect) {
130 var elements;
125 var elements;
131 if (((typeof element == 'object') ||
126 if (((typeof element == 'object') ||
132 Object.isFunction(element)) &&
127 Object.isFunction(element)) &&
133 (element.length))
128 (element.length))
134 elements = element;
129 elements = element;
135 else
130 else
136 elements = $(element).childNodes;
131 elements = $(element).childNodes;
137
132
138 var options = Object.extend({
133 var options = Object.extend({
139 speed: 0.1,
134 speed: 0.1,
@@ -204,108 +199,120
204
199
205 if (!this.interval)
200 if (!this.interval)
206 this.interval = setInterval(this.loop.bind(this), 15);
201 this.interval = setInterval(this.loop.bind(this), 15);
207 },
202 },
208 remove: function(effect) {
203 remove: function(effect) {
209 this.effects = this.effects.reject(function(e) { return e==effect });
204 this.effects = this.effects.reject(function(e) { return e==effect });
210 if (this.effects.length == 0) {
205 if (this.effects.length == 0) {
211 clearInterval(this.interval);
206 clearInterval(this.interval);
212 this.interval = null;
207 this.interval = null;
213 }
208 }
214 },
209 },
215 loop: function() {
210 loop: function() {
216 var timePos = new Date().getTime();
211 var timePos = new Date().getTime();
217 for(var i=0, len=this.effects.length;i<len;i++)
212 for(var i=0, len=this.effects.length;i<len;i++)
218 this.effects[i] && this.effects[i].loop(timePos);
213 this.effects[i] && this.effects[i].loop(timePos);
219 }
214 }
220 });
215 });
221
216
222 Effect.Queues = {
217 Effect.Queues = {
223 instances: $H(),
218 instances: $H(),
224 get: function(queueName) {
219 get: function(queueName) {
225 if (!Object.isString(queueName)) return queueName;
220 if (!Object.isString(queueName)) return queueName;
226
221
227 return this.instances.get(queueName) ||
222 return this.instances.get(queueName) ||
228 this.instances.set(queueName, new Effect.ScopedQueue());
223 this.instances.set(queueName, new Effect.ScopedQueue());
229 }
224 }
230 };
225 };
231 Effect.Queue = Effect.Queues.get('global');
226 Effect.Queue = Effect.Queues.get('global');
232
227
233 Effect.Base = Class.create({
228 Effect.Base = Class.create({
234 position: null,
229 position: null,
235 start: function(options) {
230 start: function(options) {
236 function codeForEvent(options,eventName){
231 function codeForEvent(options,eventName){
237 return (
232 return (
238 (options[eventName+'Internal'] ? 'this.options.'+eventName+'Internal(this);' : '') +
233 (options[eventName+'Internal'] ? 'this.options.'+eventName+'Internal(this);' : '') +
239 (options[eventName] ? 'this.options.'+eventName+'(this);' : '')
234 (options[eventName] ? 'this.options.'+eventName+'(this);' : '')
240 );
235 );
241 }
236 }
242 if (options && options.transition === false) options.transition = Effect.Transitions.linear;
237 if (options && options.transition === false) options.transition = Effect.Transitions.linear;
243 this.options = Object.extend(Object.extend({ },Effect.DefaultOptions), options || { });
238 this.options = Object.extend(Object.extend({ },Effect.DefaultOptions), options || { });
244 this.currentFrame = 0;
239 this.currentFrame = 0;
245 this.state = 'idle';
240 this.state = 'idle';
246 this.startOn = this.options.delay*1000;
241 this.startOn = this.options.delay*1000;
247 this.finishOn = this.startOn+(this.options.duration*1000);
242 this.finishOn = this.startOn+(this.options.duration*1000);
248 this.fromToDelta = this.options.to-this.options.from;
243 this.fromToDelta = this.options.to-this.options.from;
249 this.totalTime = this.finishOn-this.startOn;
244 this.totalTime = this.finishOn-this.startOn;
250 this.totalFrames = this.options.fps*this.options.duration;
245 this.totalFrames = this.options.fps*this.options.duration;
251
246
252 - eval('this.render = function(pos){ '+
247 + this.render = (function() {
253 - 'if (this.state=="idle"){this.state="running";'+
248 + function dispatch(effect, eventName) {
254 - codeForEvent(this.options,'beforeSetup')+
249 + if (effect.options[eventName + 'Internal'])
255 - (this.setup ? 'this.setup();':'')+
250 + effect.options[eventName + 'Internal'](effect);
256 - codeForEvent(this.options,'afterSetup')+
251 + if (effect.options[eventName])
257 - '};if (this.state=="running"){'+
252 + effect.options[eventName](effect);
258 - 'pos=this.options.transition(pos)*'+this.fromToDelta+'+'+this.options.from+';'+
253 + }
259 - 'this.position=pos;'+
254 +
260 - codeForEvent(this.options,'beforeUpdate')+
255 + return function(pos) {
261 - (this.update ? 'this.update(pos);':'')+
256 + if (this.state === "idle") {
262 - codeForEvent(this.options,'afterUpdate')+
257 + this.state = "running";
263 - '}}');
258 + dispatch(this, 'beforeSetup');
259 + if (this.setup) this.setup();
260 + dispatch(this, 'afterSetup');
261 + }
262 + if (this.state === "running") {
263 + pos = (this.options.transition(pos) * this.fromToDelta) + this.options.from;
264 + this.position = pos;
265 + dispatch(this, 'beforeUpdate');
266 + if (this.update) this.update(pos);
267 + dispatch(this, 'afterUpdate');
268 + }
269 + };
270 + })();
264
271
265 this.event('beforeStart');
272 this.event('beforeStart');
266 if (!this.options.sync)
273 if (!this.options.sync)
267 Effect.Queues.get(Object.isString(this.options.queue) ?
274 Effect.Queues.get(Object.isString(this.options.queue) ?
268 'global' : this.options.queue.scope).add(this);
275 'global' : this.options.queue.scope).add(this);
269 },
276 },
270 loop: function(timePos) {
277 loop: function(timePos) {
271 if (timePos >= this.startOn) {
278 if (timePos >= this.startOn) {
272 if (timePos >= this.finishOn) {
279 if (timePos >= this.finishOn) {
273 this.render(1.0);
280 this.render(1.0);
274 this.cancel();
281 this.cancel();
275 this.event('beforeFinish');
282 this.event('beforeFinish');
276 if (this.finish) this.finish();
283 if (this.finish) this.finish();
277 this.event('afterFinish');
284 this.event('afterFinish');
278 return;
285 return;
279 }
286 }
280 var pos = (timePos - this.startOn) / this.totalTime,
287 var pos = (timePos - this.startOn) / this.totalTime,
281 frame = (pos * this.totalFrames).round();
288 frame = (pos * this.totalFrames).round();
282 if (frame > this.currentFrame) {
289 if (frame > this.currentFrame) {
283 this.render(pos);
290 this.render(pos);
284 this.currentFrame = frame;
291 this.currentFrame = frame;
285 }
292 }
286 }
293 }
287 },
294 },
288 cancel: function() {
295 cancel: function() {
289 if (!this.options.sync)
296 if (!this.options.sync)
290 Effect.Queues.get(Object.isString(this.options.queue) ?
297 Effect.Queues.get(Object.isString(this.options.queue) ?
291 'global' : this.options.queue.scope).remove(this);
298 'global' : this.options.queue.scope).remove(this);
292 this.state = 'finished';
299 this.state = 'finished';
293 },
300 },
294 event: function(eventName) {
301 event: function(eventName) {
295 if (this.options[eventName + 'Internal']) this.options[eventName + 'Internal'](this);
302 if (this.options[eventName + 'Internal']) this.options[eventName + 'Internal'](this);
296 if (this.options[eventName]) this.options[eventName](this);
303 if (this.options[eventName]) this.options[eventName](this);
297 },
304 },
298 inspect: function() {
305 inspect: function() {
299 var data = $H();
306 var data = $H();
300 for(property in this)
307 for(property in this)
301 if (!Object.isFunction(this[property])) data.set(property, this[property]);
308 if (!Object.isFunction(this[property])) data.set(property, this[property]);
302 return '#<Effect:' + data.inspect() + ',options:' + $H(this.options).inspect() + '>';
309 return '#<Effect:' + data.inspect() + ',options:' + $H(this.options).inspect() + '>';
303 }
310 }
304 });
311 });
305
312
306 Effect.Parallel = Class.create(Effect.Base, {
313 Effect.Parallel = Class.create(Effect.Base, {
307 initialize: function(effects) {
314 initialize: function(effects) {
308 this.effects = effects || [];
315 this.effects = effects || [];
309 this.start(arguments[1]);
316 this.start(arguments[1]);
310 },
317 },
311 update: function(position) {
318 update: function(position) {
@@ -463,263 +470,262
463 if (this.options.scaleX) d.left = this.originalLeft-leftd + 'px';
470 if (this.options.scaleX) d.left = this.originalLeft-leftd + 'px';
464 } else {
471 } else {
465 if (this.options.scaleY) d.top = -topd + 'px';
472 if (this.options.scaleY) d.top = -topd + 'px';
466 if (this.options.scaleX) d.left = -leftd + 'px';
473 if (this.options.scaleX) d.left = -leftd + 'px';
467 }
474 }
468 }
475 }
469 this.element.setStyle(d);
476 this.element.setStyle(d);
470 }
477 }
471 });
478 });
472
479
473 Effect.Highlight = Class.create(Effect.Base, {
480 Effect.Highlight = Class.create(Effect.Base, {
474 initialize: function(element) {
481 initialize: function(element) {
475 this.element = $(element);
482 this.element = $(element);
476 if (!this.element) throw(Effect._elementDoesNotExistError);
483 if (!this.element) throw(Effect._elementDoesNotExistError);
477 var options = Object.extend({ startcolor: '#ffff99' }, arguments[1] || { });
484 var options = Object.extend({ startcolor: '#ffff99' }, arguments[1] || { });
478 this.start(options);
485 this.start(options);
479 },
486 },
480 setup: function() {
487 setup: function() {
481 // Prevent executing on elements not in the layout flow
488 // Prevent executing on elements not in the layout flow
482 if (this.element.getStyle('display')=='none') { this.cancel(); return; }
489 if (this.element.getStyle('display')=='none') { this.cancel(); return; }
483 // Disable background image during the effect
490 // Disable background image during the effect
484 this.oldStyle = { };
491 this.oldStyle = { };
485 if (!this.options.keepBackgroundImage) {
492 if (!this.options.keepBackgroundImage) {
486 this.oldStyle.backgroundImage = this.element.getStyle('background-image');
493 this.oldStyle.backgroundImage = this.element.getStyle('background-image');
487 this.element.setStyle({backgroundImage: 'none'});
494 this.element.setStyle({backgroundImage: 'none'});
488 }
495 }
489 if (!this.options.endcolor)
496 if (!this.options.endcolor)
490 this.options.endcolor = this.element.getStyle('background-color').parseColor('#ffffff');
497 this.options.endcolor = this.element.getStyle('background-color').parseColor('#ffffff');
491 if (!this.options.restorecolor)
498 if (!this.options.restorecolor)
492 this.options.restorecolor = this.element.getStyle('background-color');
499 this.options.restorecolor = this.element.getStyle('background-color');
493 // init color calculations
500 // init color calculations
494 this._base = $R(0,2).map(function(i){ return parseInt(this.options.startcolor.slice(i*2+1,i*2+3),16) }.bind(this));
501 this._base = $R(0,2).map(function(i){ return parseInt(this.options.startcolor.slice(i*2+1,i*2+3),16) }.bind(this));
495 this._delta = $R(0,2).map(function(i){ return parseInt(this.options.endcolor.slice(i*2+1,i*2+3),16)-this._base[i] }.bind(this));
502 this._delta = $R(0,2).map(function(i){ return parseInt(this.options.endcolor.slice(i*2+1,i*2+3),16)-this._base[i] }.bind(this));
496 },
503 },
497 update: function(position) {
504 update: function(position) {
498 this.element.setStyle({backgroundColor: $R(0,2).inject('#',function(m,v,i){
505 this.element.setStyle({backgroundColor: $R(0,2).inject('#',function(m,v,i){
499 return m+((this._base[i]+(this._delta[i]*position)).round().toColorPart()); }.bind(this)) });
506 return m+((this._base[i]+(this._delta[i]*position)).round().toColorPart()); }.bind(this)) });
500 },
507 },
501 finish: function() {
508 finish: function() {
502 this.element.setStyle(Object.extend(this.oldStyle, {
509 this.element.setStyle(Object.extend(this.oldStyle, {
503 backgroundColor: this.options.restorecolor
510 backgroundColor: this.options.restorecolor
504 }));
511 }));
505 }
512 }
506 });
513 });
507
514
508 Effect.ScrollTo = function(element) {
515 Effect.ScrollTo = function(element) {
509 var options = arguments[1] || { },
516 var options = arguments[1] || { },
510 scrollOffsets = document.viewport.getScrollOffsets(),
517 scrollOffsets = document.viewport.getScrollOffsets(),
511 - elementOffsets = $(element).cumulativeOffset(),
518 + elementOffsets = $(element).cumulativeOffset();
512 - max = (window.height || document.body.scrollHeight) - document.viewport.getHeight();
513
519
514 if (options.offset) elementOffsets[1] += options.offset;
520 if (options.offset) elementOffsets[1] += options.offset;
515
521
516 return new Effect.Tween(null,
522 return new Effect.Tween(null,
517 scrollOffsets.top,
523 scrollOffsets.top,
518 - elementOffsets[1] > max ? max : elementOffsets[1],
524 + elementOffsets[1],
519 options,
525 options,
520 - function(p){ scrollTo(scrollOffsets.left, p.round()) }
526 + function(p){ scrollTo(scrollOffsets.left, p.round()); }
521 );
527 );
522 };
528 };
523
529
524 /* ------------- combination effects ------------- */
530 /* ------------- combination effects ------------- */
525
531
526 Effect.Fade = function(element) {
532 Effect.Fade = function(element) {
527 element = $(element);
533 element = $(element);
528 var oldOpacity = element.getInlineOpacity();
534 var oldOpacity = element.getInlineOpacity();
529 var options = Object.extend({
535 var options = Object.extend({
530 from: element.getOpacity() || 1.0,
536 from: element.getOpacity() || 1.0,
531 to: 0.0,
537 to: 0.0,
532 afterFinishInternal: function(effect) {
538 afterFinishInternal: function(effect) {
533 if (effect.options.to!=0) return;
539 if (effect.options.to!=0) return;
534 effect.element.hide().setStyle({opacity: oldOpacity});
540 effect.element.hide().setStyle({opacity: oldOpacity});
535 }
541 }
536 }, arguments[1] || { });
542 }, arguments[1] || { });
537 return new Effect.Opacity(element,options);
543 return new Effect.Opacity(element,options);
538 };
544 };
539
545
540 Effect.Appear = function(element) {
546 Effect.Appear = function(element) {
541 element = $(element);
547 element = $(element);
542 var options = Object.extend({
548 var options = Object.extend({
543 from: (element.getStyle('display') == 'none' ? 0.0 : element.getOpacity() || 0.0),
549 from: (element.getStyle('display') == 'none' ? 0.0 : element.getOpacity() || 0.0),
544 to: 1.0,
550 to: 1.0,
545 // force Safari to render floated elements properly
551 // force Safari to render floated elements properly
546 afterFinishInternal: function(effect) {
552 afterFinishInternal: function(effect) {
547 effect.element.forceRerendering();
553 effect.element.forceRerendering();
548 },
554 },
549 beforeSetup: function(effect) {
555 beforeSetup: function(effect) {
550 effect.element.setOpacity(effect.options.from).show();
556 effect.element.setOpacity(effect.options.from).show();
551 }}, arguments[1] || { });
557 }}, arguments[1] || { });
552 return new Effect.Opacity(element,options);
558 return new Effect.Opacity(element,options);
553 };
559 };
554
560
555 Effect.Puff = function(element) {
561 Effect.Puff = function(element) {
556 element = $(element);
562 element = $(element);
557 var oldStyle = {
563 var oldStyle = {
558 opacity: element.getInlineOpacity(),
564 opacity: element.getInlineOpacity(),
559 position: element.getStyle('position'),
565 position: element.getStyle('position'),
560 top: element.style.top,
566 top: element.style.top,
561 left: element.style.left,
567 left: element.style.left,
562 width: element.style.width,
568 width: element.style.width,
563 height: element.style.height
569 height: element.style.height
564 };
570 };
565 return new Effect.Parallel(
571 return new Effect.Parallel(
566 [ new Effect.Scale(element, 200,
572 [ new Effect.Scale(element, 200,
567 { sync: true, scaleFromCenter: true, scaleContent: true, restoreAfterFinish: true }),
573 { sync: true, scaleFromCenter: true, scaleContent: true, restoreAfterFinish: true }),
568 new Effect.Opacity(element, { sync: true, to: 0.0 } ) ],
574 new Effect.Opacity(element, { sync: true, to: 0.0 } ) ],
569 Object.extend({ duration: 1.0,
575 Object.extend({ duration: 1.0,
570 beforeSetupInternal: function(effect) {
576 beforeSetupInternal: function(effect) {
571 - Position.absolutize(effect.effects[0].element)
577 + Position.absolutize(effect.effects[0].element);
572 },
578 },
573 afterFinishInternal: function(effect) {
579 afterFinishInternal: function(effect) {
574 effect.effects[0].element.hide().setStyle(oldStyle); }
580 effect.effects[0].element.hide().setStyle(oldStyle); }
575 }, arguments[1] || { })
581 }, arguments[1] || { })
576 );
582 );
577 };
583 };
578
584
579 Effect.BlindUp = function(element) {
585 Effect.BlindUp = function(element) {
580 element = $(element);
586 element = $(element);
581 element.makeClipping();
587 element.makeClipping();
582 return new Effect.Scale(element, 0,
588 return new Effect.Scale(element, 0,
583 Object.extend({ scaleContent: false,
589 Object.extend({ scaleContent: false,
584 scaleX: false,
590 scaleX: false,
585 restoreAfterFinish: true,
591 restoreAfterFinish: true,
586 afterFinishInternal: function(effect) {
592 afterFinishInternal: function(effect) {
587 effect.element.hide().undoClipping();
593 effect.element.hide().undoClipping();
588 }
594 }
589 }, arguments[1] || { })
595 }, arguments[1] || { })
590 );
596 );
591 };
597 };
592
598
593 Effect.BlindDown = function(element) {
599 Effect.BlindDown = function(element) {
594 element = $(element);
600 element = $(element);
595 var elementDimensions = element.getDimensions();
601 var elementDimensions = element.getDimensions();
596 return new Effect.Scale(element, 100, Object.extend({
602 return new Effect.Scale(element, 100, Object.extend({
597 scaleContent: false,
603 scaleContent: false,
598 scaleX: false,
604 scaleX: false,
599 scaleFrom: 0,
605 scaleFrom: 0,
600 scaleMode: {originalHeight: elementDimensions.height, originalWidth: elementDimensions.width},
606 scaleMode: {originalHeight: elementDimensions.height, originalWidth: elementDimensions.width},
601 restoreAfterFinish: true,
607 restoreAfterFinish: true,
602 afterSetup: function(effect) {
608 afterSetup: function(effect) {
603 effect.element.makeClipping().setStyle({height: '0px'}).show();
609 effect.element.makeClipping().setStyle({height: '0px'}).show();
604 },
610 },
605 afterFinishInternal: function(effect) {
611 afterFinishInternal: function(effect) {
606 effect.element.undoClipping();
612 effect.element.undoClipping();
607 }
613 }
608 }, arguments[1] || { }));
614 }, arguments[1] || { }));
609 };
615 };
610
616
611 Effect.SwitchOff = function(element) {
617 Effect.SwitchOff = function(element) {
612 element = $(element);
618 element = $(element);
613 var oldOpacity = element.getInlineOpacity();
619 var oldOpacity = element.getInlineOpacity();
614 return new Effect.Appear(element, Object.extend({
620 return new Effect.Appear(element, Object.extend({
615 duration: 0.4,
621 duration: 0.4,
616 from: 0,
622 from: 0,
617 transition: Effect.Transitions.flicker,
623 transition: Effect.Transitions.flicker,
618 afterFinishInternal: function(effect) {
624 afterFinishInternal: function(effect) {
619 new Effect.Scale(effect.element, 1, {
625 new Effect.Scale(effect.element, 1, {
620 duration: 0.3, scaleFromCenter: true,
626 duration: 0.3, scaleFromCenter: true,
621 scaleX: false, scaleContent: false, restoreAfterFinish: true,
627 scaleX: false, scaleContent: false, restoreAfterFinish: true,
622 beforeSetup: function(effect) {
628 beforeSetup: function(effect) {
623 effect.element.makePositioned().makeClipping();
629 effect.element.makePositioned().makeClipping();
624 },
630 },
625 afterFinishInternal: function(effect) {
631 afterFinishInternal: function(effect) {
626 effect.element.hide().undoClipping().undoPositioned().setStyle({opacity: oldOpacity});
632 effect.element.hide().undoClipping().undoPositioned().setStyle({opacity: oldOpacity});
627 }
633 }
628 - })
634 + });
629 }
635 }
630 }, arguments[1] || { }));
636 }, arguments[1] || { }));
631 };
637 };
632
638
633 Effect.DropOut = function(element) {
639 Effect.DropOut = function(element) {
634 element = $(element);
640 element = $(element);
635 var oldStyle = {
641 var oldStyle = {
636 top: element.getStyle('top'),
642 top: element.getStyle('top'),
637 left: element.getStyle('left'),
643 left: element.getStyle('left'),
638 opacity: element.getInlineOpacity() };
644 opacity: element.getInlineOpacity() };
639 return new Effect.Parallel(
645 return new Effect.Parallel(
640 [ new Effect.Move(element, {x: 0, y: 100, sync: true }),
646 [ new Effect.Move(element, {x: 0, y: 100, sync: true }),
641 new Effect.Opacity(element, { sync: true, to: 0.0 }) ],
647 new Effect.Opacity(element, { sync: true, to: 0.0 }) ],
642 Object.extend(
648 Object.extend(
643 { duration: 0.5,
649 { duration: 0.5,
644 beforeSetup: function(effect) {
650 beforeSetup: function(effect) {
645 effect.effects[0].element.makePositioned();
651 effect.effects[0].element.makePositioned();
646 },
652 },
647 afterFinishInternal: function(effect) {
653 afterFinishInternal: function(effect) {
648 effect.effects[0].element.hide().undoPositioned().setStyle(oldStyle);
654 effect.effects[0].element.hide().undoPositioned().setStyle(oldStyle);
649 }
655 }
650 }, arguments[1] || { }));
656 }, arguments[1] || { }));
651 };
657 };
652
658
653 Effect.Shake = function(element) {
659 Effect.Shake = function(element) {
654 element = $(element);
660 element = $(element);
655 var options = Object.extend({
661 var options = Object.extend({
656 distance: 20,
662 distance: 20,
657 duration: 0.5
663 duration: 0.5
658 }, arguments[1] || {});
664 }, arguments[1] || {});
659 var distance = parseFloat(options.distance);
665 var distance = parseFloat(options.distance);
660 var split = parseFloat(options.duration) / 10.0;
666 var split = parseFloat(options.duration) / 10.0;
661 var oldStyle = {
667 var oldStyle = {
662 top: element.getStyle('top'),
668 top: element.getStyle('top'),
663 left: element.getStyle('left') };
669 left: element.getStyle('left') };
664 return new Effect.Move(element,
670 return new Effect.Move(element,
665 { x: distance, y: 0, duration: split, afterFinishInternal: function(effect) {
671 { x: distance, y: 0, duration: split, afterFinishInternal: function(effect) {
666 new Effect.Move(effect.element,
672 new Effect.Move(effect.element,
667 { x: -distance*2, y: 0, duration: split*2, afterFinishInternal: function(effect) {
673 { x: -distance*2, y: 0, duration: split*2, afterFinishInternal: function(effect) {
668 new Effect.Move(effect.element,
674 new Effect.Move(effect.element,
669 { x: distance*2, y: 0, duration: split*2, afterFinishInternal: function(effect) {
675 { x: distance*2, y: 0, duration: split*2, afterFinishInternal: function(effect) {
670 new Effect.Move(effect.element,
676 new Effect.Move(effect.element,
671 { x: -distance*2, y: 0, duration: split*2, afterFinishInternal: function(effect) {
677 { x: -distance*2, y: 0, duration: split*2, afterFinishInternal: function(effect) {
672 new Effect.Move(effect.element,
678 new Effect.Move(effect.element,
673 { x: distance*2, y: 0, duration: split*2, afterFinishInternal: function(effect) {
679 { x: distance*2, y: 0, duration: split*2, afterFinishInternal: function(effect) {
674 new Effect.Move(effect.element,
680 new Effect.Move(effect.element,
675 { x: -distance, y: 0, duration: split, afterFinishInternal: function(effect) {
681 { x: -distance, y: 0, duration: split, afterFinishInternal: function(effect) {
676 effect.element.undoPositioned().setStyle(oldStyle);
682 effect.element.undoPositioned().setStyle(oldStyle);
677 - }}) }}) }}) }}) }}) }});
683 + }}); }}); }}); }}); }}); }});
678 };
684 };
679
685
680 Effect.SlideDown = function(element) {
686 Effect.SlideDown = function(element) {
681 element = $(element).cleanWhitespace();
687 element = $(element).cleanWhitespace();
682 // SlideDown need to have the content of the element wrapped in a container element with fixed height!
688 // SlideDown need to have the content of the element wrapped in a container element with fixed height!
683 var oldInnerBottom = element.down().getStyle('bottom');
689 var oldInnerBottom = element.down().getStyle('bottom');
684 var elementDimensions = element.getDimensions();
690 var elementDimensions = element.getDimensions();
685 return new Effect.Scale(element, 100, Object.extend({
691 return new Effect.Scale(element, 100, Object.extend({
686 scaleContent: false,
692 scaleContent: false,
687 scaleX: false,
693 scaleX: false,
688 scaleFrom: window.opera ? 0 : 1,
694 scaleFrom: window.opera ? 0 : 1,
689 scaleMode: {originalHeight: elementDimensions.height, originalWidth: elementDimensions.width},
695 scaleMode: {originalHeight: elementDimensions.height, originalWidth: elementDimensions.width},
690 restoreAfterFinish: true,
696 restoreAfterFinish: true,
691 afterSetup: function(effect) {
697 afterSetup: function(effect) {
692 effect.element.makePositioned();
698 effect.element.makePositioned();
693 effect.element.down().makePositioned();
699 effect.element.down().makePositioned();
694 if (window.opera) effect.element.setStyle({top: ''});
700 if (window.opera) effect.element.setStyle({top: ''});
695 effect.element.makeClipping().setStyle({height: '0px'}).show();
701 effect.element.makeClipping().setStyle({height: '0px'}).show();
696 },
702 },
697 afterUpdateInternal: function(effect) {
703 afterUpdateInternal: function(effect) {
698 effect.element.down().setStyle({bottom:
704 effect.element.down().setStyle({bottom:
699 (effect.dims[0] - effect.element.clientHeight) + 'px' });
705 (effect.dims[0] - effect.element.clientHeight) + 'px' });
700 },
706 },
701 afterFinishInternal: function(effect) {
707 afterFinishInternal: function(effect) {
702 effect.element.undoClipping().undoPositioned();
708 effect.element.undoClipping().undoPositioned();
703 effect.element.down().undoPositioned().setStyle({bottom: oldInnerBottom}); }
709 effect.element.down().undoPositioned().setStyle({bottom: oldInnerBottom}); }
704 }, arguments[1] || { })
710 }, arguments[1] || { })
705 );
711 );
706 };
712 };
707
713
708 Effect.SlideUp = function(element) {
714 Effect.SlideUp = function(element) {
709 element = $(element).cleanWhitespace();
715 element = $(element).cleanWhitespace();
710 var oldInnerBottom = element.down().getStyle('bottom');
716 var oldInnerBottom = element.down().getStyle('bottom');
711 var elementDimensions = element.getDimensions();
717 var elementDimensions = element.getDimensions();
712 return new Effect.Scale(element, window.opera ? 0 : 1,
718 return new Effect.Scale(element, window.opera ? 0 : 1,
713 Object.extend({ scaleContent: false,
719 Object.extend({ scaleContent: false,
714 scaleX: false,
720 scaleX: false,
715 scaleMode: 'box',
721 scaleMode: 'box',
716 scaleFrom: 100,
722 scaleFrom: 100,
717 scaleMode: {originalHeight: elementDimensions.height, originalWidth: elementDimensions.width},
723 scaleMode: {originalHeight: elementDimensions.height, originalWidth: elementDimensions.width},
718 restoreAfterFinish: true,
724 restoreAfterFinish: true,
719 afterSetup: function(effect) {
725 afterSetup: function(effect) {
720 effect.element.makePositioned();
726 effect.element.makePositioned();
721 effect.element.down().makePositioned();
727 effect.element.down().makePositioned();
722 if (window.opera) effect.element.setStyle({top: ''});
728 if (window.opera) effect.element.setStyle({top: ''});
723 effect.element.makeClipping().show();
729 effect.element.makeClipping().show();
724 },
730 },
725 afterUpdateInternal: function(effect) {
731 afterUpdateInternal: function(effect) {
@@ -771,350 +777,352
771 initialMoveX = initialMoveY = moveX = moveY = 0;
777 initialMoveX = initialMoveY = moveX = moveY = 0;
772 break;
778 break;
773 case 'top-right':
779 case 'top-right':
774 initialMoveX = dims.width;
780 initialMoveX = dims.width;
775 initialMoveY = moveY = 0;
781 initialMoveY = moveY = 0;
776 moveX = -dims.width;
782 moveX = -dims.width;
777 break;
783 break;
778 case 'bottom-left':
784 case 'bottom-left':
779 initialMoveX = moveX = 0;
785 initialMoveX = moveX = 0;
780 initialMoveY = dims.height;
786 initialMoveY = dims.height;
781 moveY = -dims.height;
787 moveY = -dims.height;
782 break;
788 break;
783 case 'bottom-right':
789 case 'bottom-right':
784 initialMoveX = dims.width;
790 initialMoveX = dims.width;
785 initialMoveY = dims.height;
791 initialMoveY = dims.height;
786 moveX = -dims.width;
792 moveX = -dims.width;
787 moveY = -dims.height;
793 moveY = -dims.height;
788 break;
794 break;
789 case 'center':
795 case 'center':
790 initialMoveX = dims.width / 2;
796 initialMoveX = dims.width / 2;
791 initialMoveY = dims.height / 2;
797 initialMoveY = dims.height / 2;
792 moveX = -dims.width / 2;
798 moveX = -dims.width / 2;
793 moveY = -dims.height / 2;
799 moveY = -dims.height / 2;
794 break;
800 break;
795 }
801 }
796
802
797 return new Effect.Move(element, {
803 return new Effect.Move(element, {
798 x: initialMoveX,
804 x: initialMoveX,
799 y: initialMoveY,
805 y: initialMoveY,
800 duration: 0.01,
806 duration: 0.01,
801 beforeSetup: function(effect) {
807 beforeSetup: function(effect) {
802 effect.element.hide().makeClipping().makePositioned();
808 effect.element.hide().makeClipping().makePositioned();
803 },
809 },
804 afterFinishInternal: function(effect) {
810 afterFinishInternal: function(effect) {
805 new Effect.Parallel(
811 new Effect.Parallel(
806 [ new Effect.Opacity(effect.element, { sync: true, to: 1.0, from: 0.0, transition: options.opacityTransition }),
812 [ new Effect.Opacity(effect.element, { sync: true, to: 1.0, from: 0.0, transition: options.opacityTransition }),
807 new Effect.Move(effect.element, { x: moveX, y: moveY, sync: true, transition: options.moveTransition }),
813 new Effect.Move(effect.element, { x: moveX, y: moveY, sync: true, transition: options.moveTransition }),
808 new Effect.Scale(effect.element, 100, {
814 new Effect.Scale(effect.element, 100, {
809 scaleMode: { originalHeight: dims.height, originalWidth: dims.width },
815 scaleMode: { originalHeight: dims.height, originalWidth: dims.width },
810 sync: true, scaleFrom: window.opera ? 1 : 0, transition: options.scaleTransition, restoreAfterFinish: true})
816 sync: true, scaleFrom: window.opera ? 1 : 0, transition: options.scaleTransition, restoreAfterFinish: true})
811 ], Object.extend({
817 ], Object.extend({
812 beforeSetup: function(effect) {
818 beforeSetup: function(effect) {
813 effect.effects[0].element.setStyle({height: '0px'}).show();
819 effect.effects[0].element.setStyle({height: '0px'}).show();
814 },
820 },
815 afterFinishInternal: function(effect) {
821 afterFinishInternal: function(effect) {
816 effect.effects[0].element.undoClipping().undoPositioned().setStyle(oldStyle);
822 effect.effects[0].element.undoClipping().undoPositioned().setStyle(oldStyle);
817 }
823 }
818 }, options)
824 }, options)
819 - )
825 + );
820 }
826 }
821 });
827 });
822 };
828 };
823
829
824 Effect.Shrink = function(element) {
830 Effect.Shrink = function(element) {
825 element = $(element);
831 element = $(element);
826 var options = Object.extend({
832 var options = Object.extend({
827 direction: 'center',
833 direction: 'center',
828 moveTransition: Effect.Transitions.sinoidal,
834 moveTransition: Effect.Transitions.sinoidal,
829 scaleTransition: Effect.Transitions.sinoidal,
835 scaleTransition: Effect.Transitions.sinoidal,
830 opacityTransition: Effect.Transitions.none
836 opacityTransition: Effect.Transitions.none
831 }, arguments[1] || { });
837 }, arguments[1] || { });
832 var oldStyle = {
838 var oldStyle = {
833 top: element.style.top,
839 top: element.style.top,
834 left: element.style.left,
840 left: element.style.left,
835 height: element.style.height,
841 height: element.style.height,
836 width: element.style.width,
842 width: element.style.width,
837 opacity: element.getInlineOpacity() };
843 opacity: element.getInlineOpacity() };
838
844
839 var dims = element.getDimensions();
845 var dims = element.getDimensions();
840 var moveX, moveY;
846 var moveX, moveY;
841
847
842 switch (options.direction) {
848 switch (options.direction) {
843 case 'top-left':
849 case 'top-left':
844 moveX = moveY = 0;
850 moveX = moveY = 0;
845 break;
851 break;
846 case 'top-right':
852 case 'top-right':
847 moveX = dims.width;
853 moveX = dims.width;
848 moveY = 0;
854 moveY = 0;
849 break;
855 break;
850 case 'bottom-left':
856 case 'bottom-left':
851 moveX = 0;
857 moveX = 0;
852 moveY = dims.height;
858 moveY = dims.height;
853 break;
859 break;
854 case 'bottom-right':
860 case 'bottom-right':
855 moveX = dims.width;
861 moveX = dims.width;
856 moveY = dims.height;
862 moveY = dims.height;
857 break;
863 break;
858 case 'center':
864 case 'center':
859 moveX = dims.width / 2;
865 moveX = dims.width / 2;
860 moveY = dims.height / 2;
866 moveY = dims.height / 2;
861 break;
867 break;
862 }
868 }
863
869
864 return new Effect.Parallel(
870 return new Effect.Parallel(
865 [ new Effect.Opacity(element, { sync: true, to: 0.0, from: 1.0, transition: options.opacityTransition }),
871 [ new Effect.Opacity(element, { sync: true, to: 0.0, from: 1.0, transition: options.opacityTransition }),
866 new Effect.Scale(element, window.opera ? 1 : 0, { sync: true, transition: options.scaleTransition, restoreAfterFinish: true}),
872 new Effect.Scale(element, window.opera ? 1 : 0, { sync: true, transition: options.scaleTransition, restoreAfterFinish: true}),
867 new Effect.Move(element, { x: moveX, y: moveY, sync: true, transition: options.moveTransition })
873 new Effect.Move(element, { x: moveX, y: moveY, sync: true, transition: options.moveTransition })
868 ], Object.extend({
874 ], Object.extend({
869 beforeStartInternal: function(effect) {
875 beforeStartInternal: function(effect) {
870 effect.effects[0].element.makePositioned().makeClipping();
876 effect.effects[0].element.makePositioned().makeClipping();
871 },
877 },
872 afterFinishInternal: function(effect) {
878 afterFinishInternal: function(effect) {
873 effect.effects[0].element.hide().undoClipping().undoPositioned().setStyle(oldStyle); }
879 effect.effects[0].element.hide().undoClipping().undoPositioned().setStyle(oldStyle); }
874 }, options)
880 }, options)
875 );
881 );
876 };
882 };
877
883
878 Effect.Pulsate = function(element) {
884 Effect.Pulsate = function(element) {
879 element = $(element);
885 element = $(element);
880 - var options = arguments[1] || { };
886 + var options = arguments[1] || { },
881 - var oldOpacity = element.getInlineOpacity();
887 + oldOpacity = element.getInlineOpacity(),
882 - var transition = options.transition || Effect.Transitions.sinoidal;
888 + transition = options.transition || Effect.Transitions.linear,
883 - var reverser = function(pos){ return transition(1-Effect.Transitions.pulse(pos, options.pulses)) };
889 + reverser = function(pos){
884 - reverser.bind(transition);
890 + return 1 - transition((-Math.cos((pos*(options.pulses||5)*2)*Math.PI)/2) + .5);
891 + };
892 +
885 return new Effect.Opacity(element,
893 return new Effect.Opacity(element,
886 Object.extend(Object.extend({ duration: 2.0, from: 0,
894 Object.extend(Object.extend({ duration: 2.0, from: 0,
887 afterFinishInternal: function(effect) { effect.element.setStyle({opacity: oldOpacity}); }
895 afterFinishInternal: function(effect) { effect.element.setStyle({opacity: oldOpacity}); }
888 }, options), {transition: reverser}));
896 }, options), {transition: reverser}));
889 };
897 };
890
898
891 Effect.Fold = function(element) {
899 Effect.Fold = function(element) {
892 element = $(element);
900 element = $(element);
893 var oldStyle = {
901 var oldStyle = {
894 top: element.style.top,
902 top: element.style.top,
895 left: element.style.left,
903 left: element.style.left,
896 width: element.style.width,
904 width: element.style.width,
897 height: element.style.height };
905 height: element.style.height };
898 element.makeClipping();
906 element.makeClipping();
899 return new Effect.Scale(element, 5, Object.extend({
907 return new Effect.Scale(element, 5, Object.extend({
900 scaleContent: false,
908 scaleContent: false,
901 scaleX: false,
909 scaleX: false,
902 afterFinishInternal: function(effect) {
910 afterFinishInternal: function(effect) {
903 new Effect.Scale(element, 1, {
911 new Effect.Scale(element, 1, {
904 scaleContent: false,
912 scaleContent: false,
905 scaleY: false,
913 scaleY: false,
906 afterFinishInternal: function(effect) {
914 afterFinishInternal: function(effect) {
907 effect.element.hide().undoClipping().setStyle(oldStyle);
915 effect.element.hide().undoClipping().setStyle(oldStyle);
908 } });
916 } });
909 }}, arguments[1] || { }));
917 }}, arguments[1] || { }));
910 };
918 };
911
919
912 Effect.Morph = Class.create(Effect.Base, {
920 Effect.Morph = Class.create(Effect.Base, {
913 initialize: function(element) {
921 initialize: function(element) {
914 this.element = $(element);
922 this.element = $(element);
915 if (!this.element) throw(Effect._elementDoesNotExistError);
923 if (!this.element) throw(Effect._elementDoesNotExistError);
916 var options = Object.extend({
924 var options = Object.extend({
917 style: { }
925 style: { }
918 }, arguments[1] || { });
926 }, arguments[1] || { });
919
927
920 if (!Object.isString(options.style)) this.style = $H(options.style);
928 if (!Object.isString(options.style)) this.style = $H(options.style);
921 else {
929 else {
922 if (options.style.include(':'))
930 if (options.style.include(':'))
923 this.style = options.style.parseStyle();
931 this.style = options.style.parseStyle();
924 else {
932 else {
925 this.element.addClassName(options.style);
933 this.element.addClassName(options.style);
926 this.style = $H(this.element.getStyles());
934 this.style = $H(this.element.getStyles());
927 this.element.removeClassName(options.style);
935 this.element.removeClassName(options.style);
928 var css = this.element.getStyles();
936 var css = this.element.getStyles();
929 this.style = this.style.reject(function(style) {
937 this.style = this.style.reject(function(style) {
930 return style.value == css[style.key];
938 return style.value == css[style.key];
931 });
939 });
932 options.afterFinishInternal = function(effect) {
940 options.afterFinishInternal = function(effect) {
933 effect.element.addClassName(effect.options.style);
941 effect.element.addClassName(effect.options.style);
934 effect.transforms.each(function(transform) {
942 effect.transforms.each(function(transform) {
935 effect.element.style[transform.style] = '';
943 effect.element.style[transform.style] = '';
936 });
944 });
937 - }
945 + };
938 }
946 }
939 }
947 }
940 this.start(options);
948 this.start(options);
941 },
949 },
942
950
943 setup: function(){
951 setup: function(){
944 function parseColor(color){
952 function parseColor(color){
945 if (!color || ['rgba(0, 0, 0, 0)','transparent'].include(color)) color = '#ffffff';
953 if (!color || ['rgba(0, 0, 0, 0)','transparent'].include(color)) color = '#ffffff';
946 color = color.parseColor();
954 color = color.parseColor();
947 return $R(0,2).map(function(i){
955 return $R(0,2).map(function(i){
948 - return parseInt( color.slice(i*2+1,i*2+3), 16 )
956 + return parseInt( color.slice(i*2+1,i*2+3), 16 );
949 });
957 });
950 }
958 }
951 this.transforms = this.style.map(function(pair){
959 this.transforms = this.style.map(function(pair){
952 var property = pair[0], value = pair[1], unit = null;
960 var property = pair[0], value = pair[1], unit = null;
953
961
954 if (value.parseColor('#zzzzzz') != '#zzzzzz') {
962 if (value.parseColor('#zzzzzz') != '#zzzzzz') {
955 value = value.parseColor();
963 value = value.parseColor();
956 unit = 'color';
964 unit = 'color';
957 } else if (property == 'opacity') {
965 } else if (property == 'opacity') {
958 value = parseFloat(value);
966 value = parseFloat(value);
959 if (Prototype.Browser.IE && (!this.element.currentStyle.hasLayout))
967 if (Prototype.Browser.IE && (!this.element.currentStyle.hasLayout))
960 this.element.setStyle({zoom: 1});
968 this.element.setStyle({zoom: 1});
961 } else if (Element.CSS_LENGTH.test(value)) {
969 } else if (Element.CSS_LENGTH.test(value)) {
962 var components = value.match(/^([\+\-]?[0-9\.]+)(.*)$/);
970 var components = value.match(/^([\+\-]?[0-9\.]+)(.*)$/);
963 value = parseFloat(components[1]);
971 value = parseFloat(components[1]);
964 unit = (components.length == 3) ? components[2] : null;
972 unit = (components.length == 3) ? components[2] : null;
965 }
973 }
966
974
967 var originalValue = this.element.getStyle(property);
975 var originalValue = this.element.getStyle(property);
968 return {
976 return {
969 style: property.camelize(),
977 style: property.camelize(),
970 originalValue: unit=='color' ? parseColor(originalValue) : parseFloat(originalValue || 0),
978 originalValue: unit=='color' ? parseColor(originalValue) : parseFloat(originalValue || 0),
971 targetValue: unit=='color' ? parseColor(value) : value,
979 targetValue: unit=='color' ? parseColor(value) : value,
972 unit: unit
980 unit: unit
973 };
981 };
974 }.bind(this)).reject(function(transform){
982 }.bind(this)).reject(function(transform){
975 return (
983 return (
976 (transform.originalValue == transform.targetValue) ||
984 (transform.originalValue == transform.targetValue) ||
977 (
985 (
978 transform.unit != 'color' &&
986 transform.unit != 'color' &&
979 (isNaN(transform.originalValue) || isNaN(transform.targetValue))
987 (isNaN(transform.originalValue) || isNaN(transform.targetValue))
980 )
988 )
981 - )
989 + );
982 });
990 });
983 },
991 },
984 update: function(position) {
992 update: function(position) {
985 var style = { }, transform, i = this.transforms.length;
993 var style = { }, transform, i = this.transforms.length;
986 while(i--)
994 while(i--)
987 style[(transform = this.transforms[i]).style] =
995 style[(transform = this.transforms[i]).style] =
988 transform.unit=='color' ? '#'+
996 transform.unit=='color' ? '#'+
989 (Math.round(transform.originalValue[0]+
997 (Math.round(transform.originalValue[0]+
990 (transform.targetValue[0]-transform.originalValue[0])*position)).toColorPart() +
998 (transform.targetValue[0]-transform.originalValue[0])*position)).toColorPart() +
991 (Math.round(transform.originalValue[1]+
999 (Math.round(transform.originalValue[1]+
992 (transform.targetValue[1]-transform.originalValue[1])*position)).toColorPart() +
1000 (transform.targetValue[1]-transform.originalValue[1])*position)).toColorPart() +
993 (Math.round(transform.originalValue[2]+
1001 (Math.round(transform.originalValue[2]+
994 (transform.targetValue[2]-transform.originalValue[2])*position)).toColorPart() :
1002 (transform.targetValue[2]-transform.originalValue[2])*position)).toColorPart() :
995 (transform.originalValue +
1003 (transform.originalValue +
996 (transform.targetValue - transform.originalValue) * position).toFixed(3) +
1004 (transform.targetValue - transform.originalValue) * position).toFixed(3) +
997 (transform.unit === null ? '' : transform.unit);
1005 (transform.unit === null ? '' : transform.unit);
998 this.element.setStyle(style, true);
1006 this.element.setStyle(style, true);
999 }
1007 }
1000 });
1008 });
1001
1009
1002 Effect.Transform = Class.create({
1010 Effect.Transform = Class.create({
1003 initialize: function(tracks){
1011 initialize: function(tracks){
1004 this.tracks = [];
1012 this.tracks = [];
1005 this.options = arguments[1] || { };
1013 this.options = arguments[1] || { };
1006 this.addTracks(tracks);
1014 this.addTracks(tracks);
1007 },
1015 },
1008 addTracks: function(tracks){
1016 addTracks: function(tracks){
1009 tracks.each(function(track){
1017 tracks.each(function(track){
1010 track = $H(track);
1018 track = $H(track);
1011 var data = track.values().first();
1019 var data = track.values().first();
1012 this.tracks.push($H({
1020 this.tracks.push($H({
1013 ids: track.keys().first(),
1021 ids: track.keys().first(),
1014 effect: Effect.Morph,
1022 effect: Effect.Morph,
1015 options: { style: data }
1023 options: { style: data }
1016 }));
1024 }));
1017 }.bind(this));
1025 }.bind(this));
1018 return this;
1026 return this;
1019 },
1027 },
1020 play: function(){
1028 play: function(){
1021 return new Effect.Parallel(
1029 return new Effect.Parallel(
1022 this.tracks.map(function(track){
1030 this.tracks.map(function(track){
1023 var ids = track.get('ids'), effect = track.get('effect'), options = track.get('options');
1031 var ids = track.get('ids'), effect = track.get('effect'), options = track.get('options');
1024 var elements = [$(ids) || $$(ids)].flatten();
1032 var elements = [$(ids) || $$(ids)].flatten();
1025 return elements.map(function(e){ return new effect(e, Object.extend({ sync:true }, options)) });
1033 return elements.map(function(e){ return new effect(e, Object.extend({ sync:true }, options)) });
1026 }).flatten(),
1034 }).flatten(),
1027 this.options
1035 this.options
1028 );
1036 );
1029 }
1037 }
1030 });
1038 });
1031
1039
1032 Element.CSS_PROPERTIES = $w(
1040 Element.CSS_PROPERTIES = $w(
1033 'backgroundColor backgroundPosition borderBottomColor borderBottomStyle ' +
1041 'backgroundColor backgroundPosition borderBottomColor borderBottomStyle ' +
1034 'borderBottomWidth borderLeftColor borderLeftStyle borderLeftWidth ' +
1042 'borderBottomWidth borderLeftColor borderLeftStyle borderLeftWidth ' +
1035 'borderRightColor borderRightStyle borderRightWidth borderSpacing ' +
1043 'borderRightColor borderRightStyle borderRightWidth borderSpacing ' +
1036 'borderTopColor borderTopStyle borderTopWidth bottom clip color ' +
1044 'borderTopColor borderTopStyle borderTopWidth bottom clip color ' +
1037 'fontSize fontWeight height left letterSpacing lineHeight ' +
1045 'fontSize fontWeight height left letterSpacing lineHeight ' +
1038 'marginBottom marginLeft marginRight marginTop markerOffset maxHeight '+
1046 'marginBottom marginLeft marginRight marginTop markerOffset maxHeight '+
1039 'maxWidth minHeight minWidth opacity outlineColor outlineOffset ' +
1047 'maxWidth minHeight minWidth opacity outlineColor outlineOffset ' +
1040 'outlineWidth paddingBottom paddingLeft paddingRight paddingTop ' +
1048 'outlineWidth paddingBottom paddingLeft paddingRight paddingTop ' +
1041 'right textIndent top width wordSpacing zIndex');
1049 'right textIndent top width wordSpacing zIndex');
1042
1050
1043 Element.CSS_LENGTH = /^(([\+\-]?[0-9\.]+)(em|ex|px|in|cm|mm|pt|pc|\%))|0$/;
1051 Element.CSS_LENGTH = /^(([\+\-]?[0-9\.]+)(em|ex|px|in|cm|mm|pt|pc|\%))|0$/;
1044
1052
1045 String.__parseStyleElement = document.createElement('div');
1053 String.__parseStyleElement = document.createElement('div');
1046 String.prototype.parseStyle = function(){
1054 String.prototype.parseStyle = function(){
1047 var style, styleRules = $H();
1055 var style, styleRules = $H();
1048 if (Prototype.Browser.WebKit)
1056 if (Prototype.Browser.WebKit)
1049 style = new Element('div',{style:this}).style;
1057 style = new Element('div',{style:this}).style;
1050 else {
1058 else {
1051 String.__parseStyleElement.innerHTML = '<div style="' + this + '"></div>';
1059 String.__parseStyleElement.innerHTML = '<div style="' + this + '"></div>';
1052 style = String.__parseStyleElement.childNodes[0].style;
1060 style = String.__parseStyleElement.childNodes[0].style;
1053 }
1061 }
1054
1062
1055 Element.CSS_PROPERTIES.each(function(property){
1063 Element.CSS_PROPERTIES.each(function(property){
1056 if (style[property]) styleRules.set(property, style[property]);
1064 if (style[property]) styleRules.set(property, style[property]);
1057 });
1065 });
1058
1066
1059 if (Prototype.Browser.IE && this.include('opacity'))
1067 if (Prototype.Browser.IE && this.include('opacity'))
1060 styleRules.set('opacity', this.match(/opacity:\s*((?:0|1)?(?:\.\d*)?)/)[1]);
1068 styleRules.set('opacity', this.match(/opacity:\s*((?:0|1)?(?:\.\d*)?)/)[1]);
1061
1069
1062 return styleRules;
1070 return styleRules;
1063 };
1071 };
1064
1072
1065 if (document.defaultView && document.defaultView.getComputedStyle) {
1073 if (document.defaultView && document.defaultView.getComputedStyle) {
1066 Element.getStyles = function(element) {
1074 Element.getStyles = function(element) {
1067 var css = document.defaultView.getComputedStyle($(element), null);
1075 var css = document.defaultView.getComputedStyle($(element), null);
1068 return Element.CSS_PROPERTIES.inject({ }, function(styles, property) {
1076 return Element.CSS_PROPERTIES.inject({ }, function(styles, property) {
1069 styles[property] = css[property];
1077 styles[property] = css[property];
1070 return styles;
1078 return styles;
1071 });
1079 });
1072 };
1080 };
1073 } else {
1081 } else {
1074 Element.getStyles = function(element) {
1082 Element.getStyles = function(element) {
1075 element = $(element);
1083 element = $(element);
1076 var css = element.currentStyle, styles;
1084 var css = element.currentStyle, styles;
1077 - styles = Element.CSS_PROPERTIES.inject({ }, function(hash, property) {
1085 + styles = Element.CSS_PROPERTIES.inject({ }, function(results, property) {
1078 - hash.set(property, css[property]);
1086 + results[property] = css[property];
1079 - return hash;
1087 + return results;
1080 });
1088 });
1081 - if (!styles.opacity) styles.set('opacity', element.getOpacity());
1089 + if (!styles.opacity) styles.opacity = element.getOpacity();
1082 return styles;
1090 return styles;
1083 };
1091 };
1084 - };
1092 + }
1085
1093
1086 Effect.Methods = {
1094 Effect.Methods = {
1087 morph: function(element, style) {
1095 morph: function(element, style) {
1088 element = $(element);
1096 element = $(element);
1089 new Effect.Morph(element, Object.extend({ style: style }, arguments[2] || { }));
1097 new Effect.Morph(element, Object.extend({ style: style }, arguments[2] || { }));
1090 return element;
1098 return element;
1091 },
1099 },
1092 visualEffect: function(element, effect, options) {
1100 visualEffect: function(element, effect, options) {
1093 - element = $(element)
1101 + element = $(element);
1094 var s = effect.dasherize().camelize(), klass = s.charAt(0).toUpperCase() + s.substring(1);
1102 var s = effect.dasherize().camelize(), klass = s.charAt(0).toUpperCase() + s.substring(1);
1095 new Effect[klass](element, options);
1103 new Effect[klass](element, options);
1096 return element;
1104 return element;
1097 },
1105 },
1098 highlight: function(element, options) {
1106 highlight: function(element, options) {
1099 element = $(element);
1107 element = $(element);
1100 new Effect.Highlight(element, options);
1108 new Effect.Highlight(element, options);
1101 return element;
1109 return element;
1102 }
1110 }
1103 };
1111 };
1104
1112
1105 $w('fade appear grow shrink fold blindUp blindDown slideUp slideDown '+
1113 $w('fade appear grow shrink fold blindUp blindDown slideUp slideDown '+
1106 'pulsate shake puff squish switchOff dropOut').each(
1114 'pulsate shake puff squish switchOff dropOut').each(
1107 function(effect) {
1115 function(effect) {
1108 Effect.Methods[effect] = function(element, options){
1116 Effect.Methods[effect] = function(element, options){
1109 element = $(element);
1117 element = $(element);
1110 Effect[effect.charAt(0).toUpperCase() + effect.substring(1)](element, options);
1118 Effect[effect.charAt(0).toUpperCase() + effect.substring(1)](element, options);
1111 return element;
1119 return element;
1112 - }
1120 + };
1113 }
1121 }
1114 );
1122 );
1115
1123
1116 $w('getInlineOpacity forceRerendering setContentZoom collectTextNodes collectTextNodesIgnoreClass getStyles').each(
1124 $w('getInlineOpacity forceRerendering setContentZoom collectTextNodes collectTextNodesIgnoreClass getStyles').each(
1117 function(f) { Effect.Methods[f] = Element[f]; }
1125 function(f) { Effect.Methods[f] = Element[f]; }
1118 );
1126 );
1119
1127
1120 - Element.addMethods(Effect.Methods);
1128 + Element.addMethods(Effect.Methods); No newline at end of file
This diff has been collapsed as it changes many lines, (595 lines changed) Show them Hide them
@@ -1,299 +1,308
1 - /* Prototype JavaScript framework, version 1.6.0.1
1 + /* Prototype JavaScript framework, version 1.6.0.3
2 - * (c) 2005-2007 Sam Stephenson
2 + * (c) 2005-2008 Sam Stephenson
3 *
3 *
4 * Prototype is freely distributable under the terms of an MIT-style license.
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/
5 * For details, see the Prototype web site: http://www.prototypejs.org/
6 *
6 *
7 *--------------------------------------------------------------------------*/
7 *--------------------------------------------------------------------------*/
8
8
9 var Prototype = {
9 var Prototype = {
10 - Version: '1.6.0.1',
10 + Version: '1.6.0.3',
11
11
12 Browser: {
12 Browser: {
13 - IE: !!(window.attachEvent && !window.opera),
13 + IE: !!(window.attachEvent &&
14 - Opera: !!window.opera,
14 + navigator.userAgent.indexOf('Opera') === -1),
15 + Opera: navigator.userAgent.indexOf('Opera') > -1,
15 WebKit: navigator.userAgent.indexOf('AppleWebKit/') > -1,
16 WebKit: navigator.userAgent.indexOf('AppleWebKit/') > -1,
16 - Gecko: navigator.userAgent.indexOf('Gecko') > -1 && navigator.userAgent.indexOf('KHTML') == -1,
17 + Gecko: navigator.userAgent.indexOf('Gecko') > -1 &&
18 + navigator.userAgent.indexOf('KHTML') === -1,
17 MobileSafari: !!navigator.userAgent.match(/Apple.*Mobile.*Safari/)
19 MobileSafari: !!navigator.userAgent.match(/Apple.*Mobile.*Safari/)
18 },
20 },
19
21
20 BrowserFeatures: {
22 BrowserFeatures: {
21 XPath: !!document.evaluate,
23 XPath: !!document.evaluate,
24 + SelectorsAPI: !!document.querySelector,
22 ElementExtensions: !!window.HTMLElement,
25 ElementExtensions: !!window.HTMLElement,
23 SpecificElementExtensions:
26 SpecificElementExtensions:
24 - document.createElement('div').__proto__ &&
27 + document.createElement('div')['__proto__'] &&
25 - document.createElement('div').__proto__ !==
28 + document.createElement('div')['__proto__'] !==
26 - document.createElement('form').__proto__
29 + document.createElement('form')['__proto__']
27 },
30 },
28
31
29 ScriptFragment: '<script[^>]*>([\\S\\s]*?)<\/script>',
32 ScriptFragment: '<script[^>]*>([\\S\\s]*?)<\/script>',
30 JSONFilter: /^\/\*-secure-([\s\S]*)\*\/\s*$/,
33 JSONFilter: /^\/\*-secure-([\s\S]*)\*\/\s*$/,
31
34
32 emptyFunction: function() { },
35 emptyFunction: function() { },
33 K: function(x) { return x }
36 K: function(x) { return x }
34 };
37 };
35
38
36 if (Prototype.Browser.MobileSafari)
39 if (Prototype.Browser.MobileSafari)
37 Prototype.BrowserFeatures.SpecificElementExtensions = false;
40 Prototype.BrowserFeatures.SpecificElementExtensions = false;
38
41
39
42
40 /* Based on Alex Arnell's inheritance implementation. */
43 /* Based on Alex Arnell's inheritance implementation. */
41 var Class = {
44 var Class = {
42 create: function() {
45 create: function() {
43 var parent = null, properties = $A(arguments);
46 var parent = null, properties = $A(arguments);
44 if (Object.isFunction(properties[0]))
47 if (Object.isFunction(properties[0]))
45 parent = properties.shift();
48 parent = properties.shift();
46
49
47 function klass() {
50 function klass() {
48 this.initialize.apply(this, arguments);
51 this.initialize.apply(this, arguments);
49 }
52 }
50
53
51 Object.extend(klass, Class.Methods);
54 Object.extend(klass, Class.Methods);
52 klass.superclass = parent;
55 klass.superclass = parent;
53 klass.subclasses = [];
56 klass.subclasses = [];
54
57
55 if (parent) {
58 if (parent) {
56 var subclass = function() { };
59 var subclass = function() { };
57 subclass.prototype = parent.prototype;
60 subclass.prototype = parent.prototype;
58 klass.prototype = new subclass;
61 klass.prototype = new subclass;
59 parent.subclasses.push(klass);
62 parent.subclasses.push(klass);
60 }
63 }
61
64
62 for (var i = 0; i < properties.length; i++)
65 for (var i = 0; i < properties.length; i++)
63 klass.addMethods(properties[i]);
66 klass.addMethods(properties[i]);
64
67
65 if (!klass.prototype.initialize)
68 if (!klass.prototype.initialize)
66 klass.prototype.initialize = Prototype.emptyFunction;
69 klass.prototype.initialize = Prototype.emptyFunction;
67
70
68 klass.prototype.constructor = klass;
71 klass.prototype.constructor = klass;
69
72
70 return klass;
73 return klass;
71 }
74 }
72 };
75 };
73
76
74 Class.Methods = {
77 Class.Methods = {
75 addMethods: function(source) {
78 addMethods: function(source) {
76 var ancestor = this.superclass && this.superclass.prototype;
79 var ancestor = this.superclass && this.superclass.prototype;
77 var properties = Object.keys(source);
80 var properties = Object.keys(source);
78
81
79 if (!Object.keys({ toString: true }).length)
82 if (!Object.keys({ toString: true }).length)
80 properties.push("toString", "valueOf");
83 properties.push("toString", "valueOf");
81
84
82 for (var i = 0, length = properties.length; i < length; i++) {
85 for (var i = 0, length = properties.length; i < length; i++) {
83 var property = properties[i], value = source[property];
86 var property = properties[i], value = source[property];
84 if (ancestor && Object.isFunction(value) &&
87 if (ancestor && Object.isFunction(value) &&
85 value.argumentNames().first() == "$super") {
88 value.argumentNames().first() == "$super") {
86 - var method = value, value = Object.extend((function(m) {
89 + var method = value;
90 + value = (function(m) {
87 return function() { return ancestor[m].apply(this, arguments) };
91 return function() { return ancestor[m].apply(this, arguments) };
88 - })(property).wrap(method), {
92 + })(property).wrap(method);
89 - valueOf: function() { return method },
93 +
90 - toString: function() { return method.toString() }
94 + value.valueOf = method.valueOf.bind(method);
91 - });
95 + value.toString = method.toString.bind(method);
92 }
96 }
93 this.prototype[property] = value;
97 this.prototype[property] = value;
94 }
98 }
95
99
96 return this;
100 return this;
97 }
101 }
98 };
102 };
99
103
100 var Abstract = { };
104 var Abstract = { };
101
105
102 Object.extend = function(destination, source) {
106 Object.extend = function(destination, source) {
103 for (var property in source)
107 for (var property in source)
104 destination[property] = source[property];
108 destination[property] = source[property];
105 return destination;
109 return destination;
106 };
110 };
107
111
108 Object.extend(Object, {
112 Object.extend(Object, {
109 inspect: function(object) {
113 inspect: function(object) {
110 try {
114 try {
111 if (Object.isUndefined(object)) return 'undefined';
115 if (Object.isUndefined(object)) return 'undefined';
112 if (object === null) return 'null';
116 if (object === null) return 'null';
113 - return object.inspect ? object.inspect() : object.toString();
117 + return object.inspect ? object.inspect() : String(object);
114 } catch (e) {
118 } catch (e) {
115 if (e instanceof RangeError) return '...';
119 if (e instanceof RangeError) return '...';
116 throw e;
120 throw e;
117 }
121 }
118 },
122 },
119
123
120 toJSON: function(object) {
124 toJSON: function(object) {
121 var type = typeof object;
125 var type = typeof object;
122 switch (type) {
126 switch (type) {
123 case 'undefined':
127 case 'undefined':
124 case 'function':
128 case 'function':
125 case 'unknown': return;
129 case 'unknown': return;
126 case 'boolean': return object.toString();
130 case 'boolean': return object.toString();
127 }
131 }
128
132
129 if (object === null) return 'null';
133 if (object === null) return 'null';
130 if (object.toJSON) return object.toJSON();
134 if (object.toJSON) return object.toJSON();
131 if (Object.isElement(object)) return;
135 if (Object.isElement(object)) return;
132
136
133 var results = [];
137 var results = [];
134 for (var property in object) {
138 for (var property in object) {
135 var value = Object.toJSON(object[property]);
139 var value = Object.toJSON(object[property]);
136 if (!Object.isUndefined(value))
140 if (!Object.isUndefined(value))
137 results.push(property.toJSON() + ': ' + value);
141 results.push(property.toJSON() + ': ' + value);
138 }
142 }
139
143
140 return '{' + results.join(', ') + '}';
144 return '{' + results.join(', ') + '}';
141 },
145 },
142
146
143 toQueryString: function(object) {
147 toQueryString: function(object) {
144 return $H(object).toQueryString();
148 return $H(object).toQueryString();
145 },
149 },
146
150
147 toHTML: function(object) {
151 toHTML: function(object) {
148 return object && object.toHTML ? object.toHTML() : String.interpret(object);
152 return object && object.toHTML ? object.toHTML() : String.interpret(object);
149 },
153 },
150
154
151 keys: function(object) {
155 keys: function(object) {
152 var keys = [];
156 var keys = [];
153 for (var property in object)
157 for (var property in object)
154 keys.push(property);
158 keys.push(property);
155 return keys;
159 return keys;
156 },
160 },
157
161
158 values: function(object) {
162 values: function(object) {
159 var values = [];
163 var values = [];
160 for (var property in object)
164 for (var property in object)
161 values.push(object[property]);
165 values.push(object[property]);
162 return values;
166 return values;
163 },
167 },
164
168
165 clone: function(object) {
169 clone: function(object) {
166 return Object.extend({ }, object);
170 return Object.extend({ }, object);
167 },
171 },
168
172
169 isElement: function(object) {
173 isElement: function(object) {
170 - return object && object.nodeType == 1;
174 + return !!(object && object.nodeType == 1);
171 },
175 },
172
176
173 isArray: function(object) {
177 isArray: function(object) {
174 - return object && object.constructor === Array;
178 + return object != null && typeof object == "object" &&
179 + 'splice' in object && 'join' in object;
175 },
180 },
176
181
177 isHash: function(object) {
182 isHash: function(object) {
178 return object instanceof Hash;
183 return object instanceof Hash;
179 },
184 },
180
185
181 isFunction: function(object) {
186 isFunction: function(object) {
182 return typeof object == "function";
187 return typeof object == "function";
183 },
188 },
184
189
185 isString: function(object) {
190 isString: function(object) {
186 return typeof object == "string";
191 return typeof object == "string";
187 },
192 },
188
193
189 isNumber: function(object) {
194 isNumber: function(object) {
190 return typeof object == "number";
195 return typeof object == "number";
191 },
196 },
192
197
193 isUndefined: function(object) {
198 isUndefined: function(object) {
194 return typeof object == "undefined";
199 return typeof object == "undefined";
195 }
200 }
196 });
201 });
197
202
198 Object.extend(Function.prototype, {
203 Object.extend(Function.prototype, {
199 argumentNames: function() {
204 argumentNames: function() {
200 - var names = this.toString().match(/^[\s\(]*function[^(]*\((.*?)\)/)[1].split(",").invoke("strip");
205 + var names = this.toString().match(/^[\s\(]*function[^(]*\(([^\)]*)\)/)[1]
206 + .replace(/\s+/g, '').split(',');
201 return names.length == 1 && !names[0] ? [] : names;
207 return names.length == 1 && !names[0] ? [] : names;
202 },
208 },
203
209
204 bind: function() {
210 bind: function() {
205 if (arguments.length < 2 && Object.isUndefined(arguments[0])) return this;
211 if (arguments.length < 2 && Object.isUndefined(arguments[0])) return this;
206 var __method = this, args = $A(arguments), object = args.shift();
212 var __method = this, args = $A(arguments), object = args.shift();
207 return function() {
213 return function() {
208 return __method.apply(object, args.concat($A(arguments)));
214 return __method.apply(object, args.concat($A(arguments)));
209 }
215 }
210 },
216 },
211
217
212 bindAsEventListener: function() {
218 bindAsEventListener: function() {
213 var __method = this, args = $A(arguments), object = args.shift();
219 var __method = this, args = $A(arguments), object = args.shift();
214 return function(event) {
220 return function(event) {
215 return __method.apply(object, [event || window.event].concat(args));
221 return __method.apply(object, [event || window.event].concat(args));
216 }
222 }
217 },
223 },
218
224
219 curry: function() {
225 curry: function() {
220 if (!arguments.length) return this;
226 if (!arguments.length) return this;
221 var __method = this, args = $A(arguments);
227 var __method = this, args = $A(arguments);
222 return function() {
228 return function() {
223 return __method.apply(this, args.concat($A(arguments)));
229 return __method.apply(this, args.concat($A(arguments)));
224 }
230 }
225 },
231 },
226
232
227 delay: function() {
233 delay: function() {
228 var __method = this, args = $A(arguments), timeout = args.shift() * 1000;
234 var __method = this, args = $A(arguments), timeout = args.shift() * 1000;
229 return window.setTimeout(function() {
235 return window.setTimeout(function() {
230 return __method.apply(__method, args);
236 return __method.apply(__method, args);
231 }, timeout);
237 }, timeout);
232 },
238 },
233
239
240 + defer: function() {
241 + var args = [0.01].concat($A(arguments));
242 + return this.delay.apply(this, args);
243 + },
244 +
234 wrap: function(wrapper) {
245 wrap: function(wrapper) {
235 var __method = this;
246 var __method = this;
236 return function() {
247 return function() {
237 return wrapper.apply(this, [__method.bind(this)].concat($A(arguments)));
248 return wrapper.apply(this, [__method.bind(this)].concat($A(arguments)));
238 }
249 }
239 },
250 },
240
251
241 methodize: function() {
252 methodize: function() {
242 if (this._methodized) return this._methodized;
253 if (this._methodized) return this._methodized;
243 var __method = this;
254 var __method = this;
244 return this._methodized = function() {
255 return this._methodized = function() {
245 return __method.apply(null, [this].concat($A(arguments)));
256 return __method.apply(null, [this].concat($A(arguments)));
246 };
257 };
247 }
258 }
248 });
259 });
249
260
250 - Function.prototype.defer = Function.prototype.delay.curry(0.01);
251 -
252 Date.prototype.toJSON = function() {
261 Date.prototype.toJSON = function() {
253 return '"' + this.getUTCFullYear() + '-' +
262 return '"' + this.getUTCFullYear() + '-' +
254 (this.getUTCMonth() + 1).toPaddedString(2) + '-' +
263 (this.getUTCMonth() + 1).toPaddedString(2) + '-' +
255 this.getUTCDate().toPaddedString(2) + 'T' +
264 this.getUTCDate().toPaddedString(2) + 'T' +
256 this.getUTCHours().toPaddedString(2) + ':' +
265 this.getUTCHours().toPaddedString(2) + ':' +
257 this.getUTCMinutes().toPaddedString(2) + ':' +
266 this.getUTCMinutes().toPaddedString(2) + ':' +
258 this.getUTCSeconds().toPaddedString(2) + 'Z"';
267 this.getUTCSeconds().toPaddedString(2) + 'Z"';
259 };
268 };
260
269
261 var Try = {
270 var Try = {
262 these: function() {
271 these: function() {
263 var returnValue;
272 var returnValue;
264
273
265 for (var i = 0, length = arguments.length; i < length; i++) {
274 for (var i = 0, length = arguments.length; i < length; i++) {
266 var lambda = arguments[i];
275 var lambda = arguments[i];
267 try {
276 try {
268 returnValue = lambda();
277 returnValue = lambda();
269 break;
278 break;
270 } catch (e) { }
279 } catch (e) { }
271 }
280 }
272
281
273 return returnValue;
282 return returnValue;
274 }
283 }
275 };
284 };
276
285
277 RegExp.prototype.match = RegExp.prototype.test;
286 RegExp.prototype.match = RegExp.prototype.test;
278
287
279 RegExp.escape = function(str) {
288 RegExp.escape = function(str) {
280 return String(str).replace(/([.*+?^=!:${}()|[\]\/\\])/g, '\\$1');
289 return String(str).replace(/([.*+?^=!:${}()|[\]\/\\])/g, '\\$1');
281 };
290 };
282
291
283 /*--------------------------------------------------------------------------*/
292 /*--------------------------------------------------------------------------*/
284
293
285 var PeriodicalExecuter = Class.create({
294 var PeriodicalExecuter = Class.create({
286 initialize: function(callback, frequency) {
295 initialize: function(callback, frequency) {
287 this.callback = callback;
296 this.callback = callback;
288 this.frequency = frequency;
297 this.frequency = frequency;
289 this.currentlyExecuting = false;
298 this.currentlyExecuting = false;
290
299
291 this.registerCallback();
300 this.registerCallback();
292 },
301 },
293
302
294 registerCallback: function() {
303 registerCallback: function() {
295 this.timer = setInterval(this.onTimerEvent.bind(this), this.frequency * 1000);
304 this.timer = setInterval(this.onTimerEvent.bind(this), this.frequency * 1000);
296 },
305 },
297
306
298 execute: function() {
307 execute: function() {
299 this.callback(this);
308 this.callback(this);
@@ -484,387 +493,388
484 },
493 },
485
494
486 isJSON: function() {
495 isJSON: function() {
487 var str = this;
496 var str = this;
488 if (str.blank()) return false;
497 if (str.blank()) return false;
489 str = this.replace(/\\./g, '@').replace(/"[^"\\\n\r]*"/g, '');
498 str = this.replace(/\\./g, '@').replace(/"[^"\\\n\r]*"/g, '');
490 return (/^[,:{}\[\]0-9.\-+Eaeflnr-u \n\r\t]*$/).test(str);
499 return (/^[,:{}\[\]0-9.\-+Eaeflnr-u \n\r\t]*$/).test(str);
491 },
500 },
492
501
493 evalJSON: function(sanitize) {
502 evalJSON: function(sanitize) {
494 var json = this.unfilterJSON();
503 var json = this.unfilterJSON();
495 try {
504 try {
496 if (!sanitize || json.isJSON()) return eval('(' + json + ')');
505 if (!sanitize || json.isJSON()) return eval('(' + json + ')');
497 } catch (e) { }
506 } catch (e) { }
498 throw new SyntaxError('Badly formed JSON string: ' + this.inspect());
507 throw new SyntaxError('Badly formed JSON string: ' + this.inspect());
499 },
508 },
500
509
501 include: function(pattern) {
510 include: function(pattern) {
502 return this.indexOf(pattern) > -1;
511 return this.indexOf(pattern) > -1;
503 },
512 },
504
513
505 startsWith: function(pattern) {
514 startsWith: function(pattern) {
506 return this.indexOf(pattern) === 0;
515 return this.indexOf(pattern) === 0;
507 },
516 },
508
517
509 endsWith: function(pattern) {
518 endsWith: function(pattern) {
510 var d = this.length - pattern.length;
519 var d = this.length - pattern.length;
511 return d >= 0 && this.lastIndexOf(pattern) === d;
520 return d >= 0 && this.lastIndexOf(pattern) === d;
512 },
521 },
513
522
514 empty: function() {
523 empty: function() {
515 return this == '';
524 return this == '';
516 },
525 },
517
526
518 blank: function() {
527 blank: function() {
519 return /^\s*$/.test(this);
528 return /^\s*$/.test(this);
520 },
529 },
521
530
522 interpolate: function(object, pattern) {
531 interpolate: function(object, pattern) {
523 return new Template(this, pattern).evaluate(object);
532 return new Template(this, pattern).evaluate(object);
524 }
533 }
525 });
534 });
526
535
527 if (Prototype.Browser.WebKit || Prototype.Browser.IE) Object.extend(String.prototype, {
536 if (Prototype.Browser.WebKit || Prototype.Browser.IE) Object.extend(String.prototype, {
528 escapeHTML: function() {
537 escapeHTML: function() {
529 return this.replace(/&/g,'&amp;').replace(/</g,'&lt;').replace(/>/g,'&gt;');
538 return this.replace(/&/g,'&amp;').replace(/</g,'&lt;').replace(/>/g,'&gt;');
530 },
539 },
531 unescapeHTML: function() {
540 unescapeHTML: function() {
532 - return this.replace(/&amp;/g,'&').replace(/&lt;/g,'<').replace(/&gt;/g,'>');
541 + return this.stripTags().replace(/&amp;/g,'&').replace(/&lt;/g,'<').replace(/&gt;/g,'>');
533 }
542 }
534 });
543 });
535
544
536 String.prototype.gsub.prepareReplacement = function(replacement) {
545 String.prototype.gsub.prepareReplacement = function(replacement) {
537 if (Object.isFunction(replacement)) return replacement;
546 if (Object.isFunction(replacement)) return replacement;
538 var template = new Template(replacement);
547 var template = new Template(replacement);
539 return function(match) { return template.evaluate(match) };
548 return function(match) { return template.evaluate(match) };
540 };
549 };
541
550
542 String.prototype.parseQuery = String.prototype.toQueryParams;
551 String.prototype.parseQuery = String.prototype.toQueryParams;
543
552
544 Object.extend(String.prototype.escapeHTML, {
553 Object.extend(String.prototype.escapeHTML, {
545 div: document.createElement('div'),
554 div: document.createElement('div'),
546 text: document.createTextNode('')
555 text: document.createTextNode('')
547 });
556 });
548
557
549 - with (String.prototype.escapeHTML) div.appendChild(text);
558 + String.prototype.escapeHTML.div.appendChild(String.prototype.escapeHTML.text);
550
559
551 var Template = Class.create({
560 var Template = Class.create({
552 initialize: function(template, pattern) {
561 initialize: function(template, pattern) {
553 this.template = template.toString();
562 this.template = template.toString();
554 this.pattern = pattern || Template.Pattern;
563 this.pattern = pattern || Template.Pattern;
555 },
564 },
556
565
557 evaluate: function(object) {
566 evaluate: function(object) {
558 if (Object.isFunction(object.toTemplateReplacements))
567 if (Object.isFunction(object.toTemplateReplacements))
559 object = object.toTemplateReplacements();
568 object = object.toTemplateReplacements();
560
569
561 return this.template.gsub(this.pattern, function(match) {
570 return this.template.gsub(this.pattern, function(match) {
562 if (object == null) return '';
571 if (object == null) return '';
563
572
564 var before = match[1] || '';
573 var before = match[1] || '';
565 if (before == '\\') return match[2];
574 if (before == '\\') return match[2];
566
575
567 var ctx = object, expr = match[3];
576 var ctx = object, expr = match[3];
568 var pattern = /^([^.[]+|\[((?:.*?[^\\])?)\])(\.|\[|$)/;
577 var pattern = /^([^.[]+|\[((?:.*?[^\\])?)\])(\.|\[|$)/;
569 match = pattern.exec(expr);
578 match = pattern.exec(expr);
570 if (match == null) return before;
579 if (match == null) return before;
571
580
572 while (match != null) {
581 while (match != null) {
573 var comp = match[1].startsWith('[') ? match[2].gsub('\\\\]', ']') : match[1];
582 var comp = match[1].startsWith('[') ? match[2].gsub('\\\\]', ']') : match[1];
574 ctx = ctx[comp];
583 ctx = ctx[comp];
575 if (null == ctx || '' == match[3]) break;
584 if (null == ctx || '' == match[3]) break;
576 expr = expr.substring('[' == match[3] ? match[1].length : match[0].length);
585 expr = expr.substring('[' == match[3] ? match[1].length : match[0].length);
577 match = pattern.exec(expr);
586 match = pattern.exec(expr);
578 }
587 }
579
588
580 return before + String.interpret(ctx);
589 return before + String.interpret(ctx);
581 - }.bind(this));
590 + });
582 }
591 }
583 });
592 });
584 Template.Pattern = /(^|.|\r|\n)(#\{(.*?)\})/;
593 Template.Pattern = /(^|.|\r|\n)(#\{(.*?)\})/;
585
594
586 var $break = { };
595 var $break = { };
587
596
588 var Enumerable = {
597 var Enumerable = {
589 each: function(iterator, context) {
598 each: function(iterator, context) {
590 var index = 0;
599 var index = 0;
591 - iterator = iterator.bind(context);
592 try {
600 try {
593 this._each(function(value) {
601 this._each(function(value) {
594 - iterator(value, index++);
602 + iterator.call(context, value, index++);
595 });
603 });
596 } catch (e) {
604 } catch (e) {
597 if (e != $break) throw e;
605 if (e != $break) throw e;
598 }
606 }
599 return this;
607 return this;
600 },
608 },
601
609
602 eachSlice: function(number, iterator, context) {
610 eachSlice: function(number, iterator, context) {
603 - iterator = iterator ? iterator.bind(context) : Prototype.K;
604 var index = -number, slices = [], array = this.toArray();
611 var index = -number, slices = [], array = this.toArray();
612 + if (number < 1) return array;
605 while ((index += number) < array.length)
613 while ((index += number) < array.length)
606 slices.push(array.slice(index, index+number));
614 slices.push(array.slice(index, index+number));
607 return slices.collect(iterator, context);
615 return slices.collect(iterator, context);
608 },
616 },
609
617
610 all: function(iterator, context) {
618 all: function(iterator, context) {
611 - iterator = iterator ? iterator.bind(context) : Prototype.K;
619 + iterator = iterator || Prototype.K;
612 var result = true;
620 var result = true;
613 this.each(function(value, index) {
621 this.each(function(value, index) {
614 - result = result && !!iterator(value, index);
622 + result = result && !!iterator.call(context, value, index);
615 if (!result) throw $break;
623 if (!result) throw $break;
616 });
624 });
617 return result;
625 return result;
618 },
626 },
619
627
620 any: function(iterator, context) {
628 any: function(iterator, context) {
621 - iterator = iterator ? iterator.bind(context) : Prototype.K;
629 + iterator = iterator || Prototype.K;
622 var result = false;
630 var result = false;
623 this.each(function(value, index) {
631 this.each(function(value, index) {
624 - if (result = !!iterator(value, index))
632 + if (result = !!iterator.call(context, value, index))
625 throw $break;
633 throw $break;
626 });
634 });
627 return result;
635 return result;
628 },
636 },
629
637
630 collect: function(iterator, context) {
638 collect: function(iterator, context) {
631 - iterator = iterator ? iterator.bind(context) : Prototype.K;
639 + iterator = iterator || Prototype.K;
632 var results = [];
640 var results = [];
633 this.each(function(value, index) {
641 this.each(function(value, index) {
634 - results.push(iterator(value, index));
642 + results.push(iterator.call(context, value, index));
635 });
643 });
636 return results;
644 return results;
637 },
645 },
638
646
639 detect: function(iterator, context) {
647 detect: function(iterator, context) {
640 - iterator = iterator.bind(context);
641 var result;
648 var result;
642 this.each(function(value, index) {
649 this.each(function(value, index) {
643 - if (iterator(value, index)) {
650 + if (iterator.call(context, value, index)) {
644 result = value;
651 result = value;
645 throw $break;
652 throw $break;
646 }
653 }
647 });
654 });
648 return result;
655 return result;
649 },
656 },
650
657
651 findAll: function(iterator, context) {
658 findAll: function(iterator, context) {
652 - iterator = iterator.bind(context);
653 var results = [];
659 var results = [];
654 this.each(function(value, index) {
660 this.each(function(value, index) {
655 - if (iterator(value, index))
661 + if (iterator.call(context, value, index))
656 results.push(value);
662 results.push(value);
657 });
663 });
658 return results;
664 return results;
659 },
665 },
660
666
661 grep: function(filter, iterator, context) {
667 grep: function(filter, iterator, context) {
662 - iterator = iterator ? iterator.bind(context) : Prototype.K;
668 + iterator = iterator || Prototype.K;
663 var results = [];
669 var results = [];
664
670
665 if (Object.isString(filter))
671 if (Object.isString(filter))
666 filter = new RegExp(filter);
672 filter = new RegExp(filter);
667
673
668 this.each(function(value, index) {
674 this.each(function(value, index) {
669 if (filter.match(value))
675 if (filter.match(value))
670 - results.push(iterator(value, index));
676 + results.push(iterator.call(context, value, index));
671 });
677 });
672 return results;
678 return results;
673 },
679 },
674
680
675 include: function(object) {
681 include: function(object) {
676 if (Object.isFunction(this.indexOf))
682 if (Object.isFunction(this.indexOf))
677 if (this.indexOf(object) != -1) return true;
683 if (this.indexOf(object) != -1) return true;
678
684
679 var found = false;
685 var found = false;
680 this.each(function(value) {
686 this.each(function(value) {
681 if (value == object) {
687 if (value == object) {
682 found = true;
688 found = true;
683 throw $break;
689 throw $break;
684 }
690 }
685 });
691 });
686 return found;
692 return found;
687 },
693 },
688
694
689 inGroupsOf: function(number, fillWith) {
695 inGroupsOf: function(number, fillWith) {
690 fillWith = Object.isUndefined(fillWith) ? null : fillWith;
696 fillWith = Object.isUndefined(fillWith) ? null : fillWith;
691 return this.eachSlice(number, function(slice) {
697 return this.eachSlice(number, function(slice) {
692 while(slice.length < number) slice.push(fillWith);
698 while(slice.length < number) slice.push(fillWith);
693 return slice;
699 return slice;
694 });
700 });
695 },
701 },
696
702
697 inject: function(memo, iterator, context) {
703 inject: function(memo, iterator, context) {
698 - iterator = iterator.bind(context);
699 this.each(function(value, index) {
704 this.each(function(value, index) {
700 - memo = iterator(memo, value, index);
705 + memo = iterator.call(context, memo, value, index);
701 });
706 });
702 return memo;
707 return memo;
703 },
708 },
704
709
705 invoke: function(method) {
710 invoke: function(method) {
706 var args = $A(arguments).slice(1);
711 var args = $A(arguments).slice(1);
707 return this.map(function(value) {
712 return this.map(function(value) {
708 return value[method].apply(value, args);
713 return value[method].apply(value, args);
709 });
714 });
710 },
715 },
711
716
712 max: function(iterator, context) {
717 max: function(iterator, context) {
713 - iterator = iterator ? iterator.bind(context) : Prototype.K;
718 + iterator = iterator || Prototype.K;
714 var result;
719 var result;
715 this.each(function(value, index) {
720 this.each(function(value, index) {
716 - value = iterator(value, index);
721 + value = iterator.call(context, value, index);
717 if (result == null || value >= result)
722 if (result == null || value >= result)
718 result = value;
723 result = value;
719 });
724 });
720 return result;
725 return result;
721 },
726 },
722
727
723 min: function(iterator, context) {
728 min: function(iterator, context) {
724 - iterator = iterator ? iterator.bind(context) : Prototype.K;
729 + iterator = iterator || Prototype.K;
725 var result;
730 var result;
726 this.each(function(value, index) {
731 this.each(function(value, index) {
727 - value = iterator(value, index);
732 + value = iterator.call(context, value, index);
728 if (result == null || value < result)
733 if (result == null || value < result)
729 result = value;
734 result = value;
730 });
735 });
731 return result;
736 return result;
732 },
737 },
733
738
734 partition: function(iterator, context) {
739 partition: function(iterator, context) {
735 - iterator = iterator ? iterator.bind(context) : Prototype.K;
740 + iterator = iterator || Prototype.K;
736 var trues = [], falses = [];
741 var trues = [], falses = [];
737 this.each(function(value, index) {
742 this.each(function(value, index) {
738 - (iterator(value, index) ?
743 + (iterator.call(context, value, index) ?
739 trues : falses).push(value);
744 trues : falses).push(value);
740 });
745 });
741 return [trues, falses];
746 return [trues, falses];
742 },
747 },
743
748
744 pluck: function(property) {
749 pluck: function(property) {
745 var results = [];
750 var results = [];
746 this.each(function(value) {
751 this.each(function(value) {
747 results.push(value[property]);
752 results.push(value[property]);
748 });
753 });
749 return results;
754 return results;
750 },
755 },
751
756
752 reject: function(iterator, context) {
757 reject: function(iterator, context) {
753 - iterator = iterator.bind(context);
754 var results = [];
758 var results = [];
755 this.each(function(value, index) {
759 this.each(function(value, index) {
756 - if (!iterator(value, index))
760 + if (!iterator.call(context, value, index))
757 results.push(value);
761 results.push(value);
758 });
762 });
759 return results;
763 return results;
760 },
764 },
761
765
762 sortBy: function(iterator, context) {
766 sortBy: function(iterator, context) {
763 - iterator = iterator.bind(context);
764 return this.map(function(value, index) {
767 return this.map(function(value, index) {
765 - return {value: value, criteria: iterator(value, index)};
768 + return {
769 + value: value,
770 + criteria: iterator.call(context, value, index)
771 + };
766 }).sort(function(left, right) {
772 }).sort(function(left, right) {
767 var a = left.criteria, b = right.criteria;
773 var a = left.criteria, b = right.criteria;
768 return a < b ? -1 : a > b ? 1 : 0;
774 return a < b ? -1 : a > b ? 1 : 0;
769 }).pluck('value');
775 }).pluck('value');
770 },
776 },
771
777
772 toArray: function() {
778 toArray: function() {
773 return this.map();
779 return this.map();
774 },
780 },
775
781
776 zip: function() {
782 zip: function() {
777 var iterator = Prototype.K, args = $A(arguments);
783 var iterator = Prototype.K, args = $A(arguments);
778 if (Object.isFunction(args.last()))
784 if (Object.isFunction(args.last()))
779 iterator = args.pop();
785 iterator = args.pop();
780
786
781 var collections = [this].concat(args).map($A);
787 var collections = [this].concat(args).map($A);
782 return this.map(function(value, index) {
788 return this.map(function(value, index) {
783 return iterator(collections.pluck(index));
789 return iterator(collections.pluck(index));
784 });
790 });
785 },
791 },
786
792
787 size: function() {
793 size: function() {
788 return this.toArray().length;
794 return this.toArray().length;
789 },
795 },
790
796
791 inspect: function() {
797 inspect: function() {
792 return '#<Enumerable:' + this.toArray().inspect() + '>';
798 return '#<Enumerable:' + this.toArray().inspect() + '>';
793 }
799 }
794 };
800 };
795
801
796 Object.extend(Enumerable, {
802 Object.extend(Enumerable, {
797 map: Enumerable.collect,
803 map: Enumerable.collect,
798 find: Enumerable.detect,
804 find: Enumerable.detect,
799 select: Enumerable.findAll,
805 select: Enumerable.findAll,
800 filter: Enumerable.findAll,
806 filter: Enumerable.findAll,
801 member: Enumerable.include,
807 member: Enumerable.include,
802 entries: Enumerable.toArray,
808 entries: Enumerable.toArray,
803 every: Enumerable.all,
809 every: Enumerable.all,
804 some: Enumerable.any
810 some: Enumerable.any
805 });
811 });
806 function $A(iterable) {
812 function $A(iterable) {
807 if (!iterable) return [];
813 if (!iterable) return [];
808 if (iterable.toArray) return iterable.toArray();
814 if (iterable.toArray) return iterable.toArray();
809 - var length = iterable.length, results = new Array(length);
815 + var length = iterable.length || 0, results = new Array(length);
810 while (length--) results[length] = iterable[length];
816 while (length--) results[length] = iterable[length];
811 return results;
817 return results;
812 }
818 }
813
819
814 if (Prototype.Browser.WebKit) {
820 if (Prototype.Browser.WebKit) {
815 - function $A(iterable) {
821 + $A = function(iterable) {
816 if (!iterable) return [];
822 if (!iterable) return [];
817 - if (!(Object.isFunction(iterable) && iterable == '[object NodeList]') &&
823 + // In Safari, only use the `toArray` method if it's not a NodeList.
818 - iterable.toArray) return iterable.toArray();
824 + // A NodeList is a function, has an function `item` property, and a numeric
819 - var length = iterable.length, results = new Array(length);
825 + // `length` property. Adapted from Google Doctype.
826 + if (!(typeof iterable === 'function' && typeof iterable.length ===
827 + 'number' && typeof iterable.item === 'function') && iterable.toArray)
828 + return iterable.toArray();
829 + var length = iterable.length || 0, results = new Array(length);
820 while (length--) results[length] = iterable[length];
830 while (length--) results[length] = iterable[length];
821 return results;
831 return results;
822 - }
832 + };
823 }
833 }
824
834
825 Array.from = $A;
835 Array.from = $A;
826
836
827 Object.extend(Array.prototype, Enumerable);
837 Object.extend(Array.prototype, Enumerable);
828
838
829 if (!Array.prototype._reverse) Array.prototype._reverse = Array.prototype.reverse;
839 if (!Array.prototype._reverse) Array.prototype._reverse = Array.prototype.reverse;
830
840
831 Object.extend(Array.prototype, {
841 Object.extend(Array.prototype, {
832 _each: function(iterator) {
842 _each: function(iterator) {
833 for (var i = 0, length = this.length; i < length; i++)
843 for (var i = 0, length = this.length; i < length; i++)
834 iterator(this[i]);
844 iterator(this[i]);
835 },
845 },
836
846
837 clear: function() {
847 clear: function() {
838 this.length = 0;
848 this.length = 0;
839 return this;
849 return this;
840 },
850 },
841
851
842 first: function() {
852 first: function() {
843 return this[0];
853 return this[0];
844 },
854 },
845
855
846 last: function() {
856 last: function() {
847 return this[this.length - 1];
857 return this[this.length - 1];
848 },
858 },
849
859
850 compact: function() {
860 compact: function() {
851 return this.select(function(value) {
861 return this.select(function(value) {
852 return value != null;
862 return value != null;
853 });
863 });
854 },
864 },
855
865
856 flatten: function() {
866 flatten: function() {
857 return this.inject([], function(array, value) {
867 return this.inject([], function(array, value) {
858 return array.concat(Object.isArray(value) ?
868 return array.concat(Object.isArray(value) ?
859 value.flatten() : [value]);
869 value.flatten() : [value]);
860 });
870 });
861 },
871 },
862
872
863 without: function() {
873 without: function() {
864 var values = $A(arguments);
874 var values = $A(arguments);
865 return this.select(function(value) {
875 return this.select(function(value) {
866 return !values.include(value);
876 return !values.include(value);
867 });
877 });
868 },
878 },
869
879
870 reverse: function(inline) {
880 reverse: function(inline) {
@@ -917,192 +927,194
917
927
918 if (!Array.prototype.indexOf) Array.prototype.indexOf = function(item, i) {
928 if (!Array.prototype.indexOf) Array.prototype.indexOf = function(item, i) {
919 i || (i = 0);
929 i || (i = 0);
920 var length = this.length;
930 var length = this.length;
921 if (i < 0) i = length + i;
931 if (i < 0) i = length + i;
922 for (; i < length; i++)
932 for (; i < length; i++)
923 if (this[i] === item) return i;
933 if (this[i] === item) return i;
924 return -1;
934 return -1;
925 };
935 };
926
936
927 if (!Array.prototype.lastIndexOf) Array.prototype.lastIndexOf = function(item, i) {
937 if (!Array.prototype.lastIndexOf) Array.prototype.lastIndexOf = function(item, i) {
928 i = isNaN(i) ? this.length : (i < 0 ? this.length + i : i) + 1;
938 i = isNaN(i) ? this.length : (i < 0 ? this.length + i : i) + 1;
929 var n = this.slice(0, i).reverse().indexOf(item);
939 var n = this.slice(0, i).reverse().indexOf(item);
930 return (n < 0) ? n : i - n - 1;
940 return (n < 0) ? n : i - n - 1;
931 };
941 };
932
942
933 Array.prototype.toArray = Array.prototype.clone;
943 Array.prototype.toArray = Array.prototype.clone;
934
944
935 function $w(string) {
945 function $w(string) {
936 if (!Object.isString(string)) return [];
946 if (!Object.isString(string)) return [];
937 string = string.strip();
947 string = string.strip();
938 return string ? string.split(/\s+/) : [];
948 return string ? string.split(/\s+/) : [];
939 }
949 }
940
950
941 if (Prototype.Browser.Opera){
951 if (Prototype.Browser.Opera){
942 Array.prototype.concat = function() {
952 Array.prototype.concat = function() {
943 var array = [];
953 var array = [];
944 for (var i = 0, length = this.length; i < length; i++) array.push(this[i]);
954 for (var i = 0, length = this.length; i < length; i++) array.push(this[i]);
945 for (var i = 0, length = arguments.length; i < length; i++) {
955 for (var i = 0, length = arguments.length; i < length; i++) {
946 if (Object.isArray(arguments[i])) {
956 if (Object.isArray(arguments[i])) {
947 for (var j = 0, arrayLength = arguments[i].length; j < arrayLength; j++)
957 for (var j = 0, arrayLength = arguments[i].length; j < arrayLength; j++)
948 array.push(arguments[i][j]);
958 array.push(arguments[i][j]);
949 } else {
959 } else {
950 array.push(arguments[i]);
960 array.push(arguments[i]);
951 }
961 }
952 }
962 }
953 return array;
963 return array;
954 };
964 };
955 }
965 }
956 Object.extend(Number.prototype, {
966 Object.extend(Number.prototype, {
957 toColorPart: function() {
967 toColorPart: function() {
958 return this.toPaddedString(2, 16);
968 return this.toPaddedString(2, 16);
959 },
969 },
960
970
961 succ: function() {
971 succ: function() {
962 return this + 1;
972 return this + 1;
963 },
973 },
964
974
965 - times: function(iterator) {
975 + times: function(iterator, context) {
966 - $R(0, this, true).each(iterator);
976 + $R(0, this, true).each(iterator, context);
967 return this;
977 return this;
968 },
978 },
969
979
970 toPaddedString: function(length, radix) {
980 toPaddedString: function(length, radix) {
971 var string = this.toString(radix || 10);
981 var string = this.toString(radix || 10);
972 return '0'.times(length - string.length) + string;
982 return '0'.times(length - string.length) + string;
973 },
983 },
974
984
975 toJSON: function() {
985 toJSON: function() {
976 return isFinite(this) ? this.toString() : 'null';
986 return isFinite(this) ? this.toString() : 'null';
977 }
987 }
978 });
988 });
979
989
980 $w('abs round ceil floor').each(function(method){
990 $w('abs round ceil floor').each(function(method){
981 Number.prototype[method] = Math[method].methodize();
991 Number.prototype[method] = Math[method].methodize();
982 });
992 });
983 function $H(object) {
993 function $H(object) {
984 return new Hash(object);
994 return new Hash(object);
985 };
995 };
986
996
987 var Hash = Class.create(Enumerable, (function() {
997 var Hash = Class.create(Enumerable, (function() {
988
998
989 function toQueryPair(key, value) {
999 function toQueryPair(key, value) {
990 if (Object.isUndefined(value)) return key;
1000 if (Object.isUndefined(value)) return key;
991 return key + '=' + encodeURIComponent(String.interpret(value));
1001 return key + '=' + encodeURIComponent(String.interpret(value));
992 }
1002 }
993
1003
994 return {
1004 return {
995 initialize: function(object) {
1005 initialize: function(object) {
996 this._object = Object.isHash(object) ? object.toObject() : Object.clone(object);
1006 this._object = Object.isHash(object) ? object.toObject() : Object.clone(object);
997 },
1007 },
998
1008
999 _each: function(iterator) {
1009 _each: function(iterator) {
1000 for (var key in this._object) {
1010 for (var key in this._object) {
1001 var value = this._object[key], pair = [key, value];
1011 var value = this._object[key], pair = [key, value];
1002 pair.key = key;
1012 pair.key = key;
1003 pair.value = value;
1013 pair.value = value;
1004 iterator(pair);
1014 iterator(pair);
1005 }
1015 }
1006 },
1016 },
1007
1017
1008 set: function(key, value) {
1018 set: function(key, value) {
1009 return this._object[key] = value;
1019 return this._object[key] = value;
1010 },
1020 },
1011
1021
1012 get: function(key) {
1022 get: function(key) {
1023 + // simulating poorly supported hasOwnProperty
1024 + if (this._object[key] !== Object.prototype[key])
1013 return this._object[key];
1025 return this._object[key];
1014 },
1026 },
1015
1027
1016 unset: function(key) {
1028 unset: function(key) {
1017 var value = this._object[key];
1029 var value = this._object[key];
1018 delete this._object[key];
1030 delete this._object[key];
1019 return value;
1031 return value;
1020 },
1032 },
1021
1033
1022 toObject: function() {
1034 toObject: function() {
1023 return Object.clone(this._object);
1035 return Object.clone(this._object);
1024 },
1036 },
1025
1037
1026 keys: function() {
1038 keys: function() {
1027 return this.pluck('key');
1039 return this.pluck('key');
1028 },
1040 },
1029
1041
1030 values: function() {
1042 values: function() {
1031 return this.pluck('value');
1043 return this.pluck('value');
1032 },
1044 },
1033
1045
1034 index: function(value) {
1046 index: function(value) {
1035 var match = this.detect(function(pair) {
1047 var match = this.detect(function(pair) {
1036 return pair.value === value;
1048 return pair.value === value;
1037 });
1049 });
1038 return match && match.key;
1050 return match && match.key;
1039 },
1051 },
1040
1052
1041 merge: function(object) {
1053 merge: function(object) {
1042 return this.clone().update(object);
1054 return this.clone().update(object);
1043 },
1055 },
1044
1056
1045 update: function(object) {
1057 update: function(object) {
1046 return new Hash(object).inject(this, function(result, pair) {
1058 return new Hash(object).inject(this, function(result, pair) {
1047 result.set(pair.key, pair.value);
1059 result.set(pair.key, pair.value);
1048 return result;
1060 return result;
1049 });
1061 });
1050 },
1062 },
1051
1063
1052 toQueryString: function() {
1064 toQueryString: function() {
1053 - return this.map(function(pair) {
1065 + return this.inject([], function(results, pair) {
1054 var key = encodeURIComponent(pair.key), values = pair.value;
1066 var key = encodeURIComponent(pair.key), values = pair.value;
1055
1067
1056 if (values && typeof values == 'object') {
1068 if (values && typeof values == 'object') {
1057 if (Object.isArray(values))
1069 if (Object.isArray(values))
1058 - return values.map(toQueryPair.curry(key)).join('&');
1070 + return results.concat(values.map(toQueryPair.curry(key)));
1059 - }
1071 + } else results.push(toQueryPair(key, values));
1060 - return toQueryPair(key, values);
1072 + return results;
1061 }).join('&');
1073 }).join('&');
1062 },
1074 },
1063
1075
1064 inspect: function() {
1076 inspect: function() {
1065 return '#<Hash:{' + this.map(function(pair) {
1077 return '#<Hash:{' + this.map(function(pair) {
1066 return pair.map(Object.inspect).join(': ');
1078 return pair.map(Object.inspect).join(': ');
1067 }).join(', ') + '}>';
1079 }).join(', ') + '}>';
1068 },
1080 },
1069
1081
1070 toJSON: function() {
1082 toJSON: function() {
1071 return Object.toJSON(this.toObject());
1083 return Object.toJSON(this.toObject());
1072 },
1084 },
1073
1085
1074 clone: function() {
1086 clone: function() {
1075 return new Hash(this);
1087 return new Hash(this);
1076 }
1088 }
1077 }
1089 }
1078 })());
1090 })());
1079
1091
1080 Hash.prototype.toTemplateReplacements = Hash.prototype.toObject;
1092 Hash.prototype.toTemplateReplacements = Hash.prototype.toObject;
1081 Hash.from = $H;
1093 Hash.from = $H;
1082 var ObjectRange = Class.create(Enumerable, {
1094 var ObjectRange = Class.create(Enumerable, {
1083 initialize: function(start, end, exclusive) {
1095 initialize: function(start, end, exclusive) {
1084 this.start = start;
1096 this.start = start;
1085 this.end = end;
1097 this.end = end;
1086 this.exclusive = exclusive;
1098 this.exclusive = exclusive;
1087 },
1099 },
1088
1100
1089 _each: function(iterator) {
1101 _each: function(iterator) {
1090 var value = this.start;
1102 var value = this.start;
1091 while (this.include(value)) {
1103 while (this.include(value)) {
1092 iterator(value);
1104 iterator(value);
1093 value = value.succ();
1105 value = value.succ();
1094 }
1106 }
1095 },
1107 },
1096
1108
1097 include: function(value) {
1109 include: function(value) {
1098 if (value < this.start)
1110 if (value < this.start)
1099 return false;
1111 return false;
1100 if (this.exclusive)
1112 if (this.exclusive)
1101 return value < this.end;
1113 return value < this.end;
1102 return value <= this.end;
1114 return value <= this.end;
1103 }
1115 }
1104 });
1116 });
1105
1117
1106 var $R = function(start, end, exclusive) {
1118 var $R = function(start, end, exclusive) {
1107 return new ObjectRange(start, end, exclusive);
1119 return new ObjectRange(start, end, exclusive);
1108 };
1120 };
@@ -1253,203 +1265,214
1253 * Content-length header. See Mozilla Bugzilla #246651.
1265 * Content-length header. See Mozilla Bugzilla #246651.
1254 */
1266 */
1255 if (this.transport.overrideMimeType &&
1267 if (this.transport.overrideMimeType &&
1256 (navigator.userAgent.match(/Gecko\/(\d{4})/) || [0,2005])[1] < 2005)
1268 (navigator.userAgent.match(/Gecko\/(\d{4})/) || [0,2005])[1] < 2005)
1257 headers['Connection'] = 'close';
1269 headers['Connection'] = 'close';
1258 }
1270 }
1259
1271
1260 // user-defined headers
1272 // user-defined headers
1261 if (typeof this.options.requestHeaders == 'object') {
1273 if (typeof this.options.requestHeaders == 'object') {
1262 var extras = this.options.requestHeaders;
1274 var extras = this.options.requestHeaders;
1263
1275
1264 if (Object.isFunction(extras.push))
1276 if (Object.isFunction(extras.push))
1265 for (var i = 0, length = extras.length; i < length; i += 2)
1277 for (var i = 0, length = extras.length; i < length; i += 2)
1266 headers[extras[i]] = extras[i+1];
1278 headers[extras[i]] = extras[i+1];
1267 else
1279 else
1268 $H(extras).each(function(pair) { headers[pair.key] = pair.value });
1280 $H(extras).each(function(pair) { headers[pair.key] = pair.value });
1269 }
1281 }
1270
1282
1271 for (var name in headers)
1283 for (var name in headers)
1272 this.transport.setRequestHeader(name, headers[name]);
1284 this.transport.setRequestHeader(name, headers[name]);
1273 },
1285 },
1274
1286
1275 success: function() {
1287 success: function() {
1276 var status = this.getStatus();
1288 var status = this.getStatus();
1277 return !status || (status >= 200 && status < 300);
1289 return !status || (status >= 200 && status < 300);
1278 },
1290 },
1279
1291
1280 getStatus: function() {
1292 getStatus: function() {
1281 try {
1293 try {
1282 return this.transport.status || 0;
1294 return this.transport.status || 0;
1283 } catch (e) { return 0 }
1295 } catch (e) { return 0 }
1284 },
1296 },
1285
1297
1286 respondToReadyState: function(readyState) {
1298 respondToReadyState: function(readyState) {
1287 var state = Ajax.Request.Events[readyState], response = new Ajax.Response(this);
1299 var state = Ajax.Request.Events[readyState], response = new Ajax.Response(this);
1288
1300
1289 if (state == 'Complete') {
1301 if (state == 'Complete') {
1290 try {
1302 try {
1291 this._complete = true;
1303 this._complete = true;
1292 (this.options['on' + response.status]
1304 (this.options['on' + response.status]
1293 || this.options['on' + (this.success() ? 'Success' : 'Failure')]
1305 || this.options['on' + (this.success() ? 'Success' : 'Failure')]
1294 || Prototype.emptyFunction)(response, response.headerJSON);
1306 || Prototype.emptyFunction)(response, response.headerJSON);
1295 } catch (e) {
1307 } catch (e) {
1296 this.dispatchException(e);
1308 this.dispatchException(e);
1297 }
1309 }
1298
1310
1299 var contentType = response.getHeader('Content-type');
1311 var contentType = response.getHeader('Content-type');
1300 if (this.options.evalJS == 'force'
1312 if (this.options.evalJS == 'force'
1301 - || (this.options.evalJS && contentType
1313 + || (this.options.evalJS && this.isSameOrigin() && contentType
1302 && contentType.match(/^\s*(text|application)\/(x-)?(java|ecma)script(;.*)?\s*$/i)))
1314 && contentType.match(/^\s*(text|application)\/(x-)?(java|ecma)script(;.*)?\s*$/i)))
1303 this.evalResponse();
1315 this.evalResponse();
1304 }
1316 }
1305
1317
1306 try {
1318 try {
1307 (this.options['on' + state] || Prototype.emptyFunction)(response, response.headerJSON);
1319 (this.options['on' + state] || Prototype.emptyFunction)(response, response.headerJSON);
1308 Ajax.Responders.dispatch('on' + state, this, response, response.headerJSON);
1320 Ajax.Responders.dispatch('on' + state, this, response, response.headerJSON);
1309 } catch (e) {
1321 } catch (e) {
1310 this.dispatchException(e);
1322 this.dispatchException(e);
1311 }
1323 }
1312
1324
1313 if (state == 'Complete') {
1325 if (state == 'Complete') {
1314 // avoid memory leak in MSIE: clean up
1326 // avoid memory leak in MSIE: clean up
1315 this.transport.onreadystatechange = Prototype.emptyFunction;
1327 this.transport.onreadystatechange = Prototype.emptyFunction;
1316 }
1328 }
1317 },
1329 },
1318
1330
1331 + isSameOrigin: function() {
1332 + var m = this.url.match(/^\s*https?:\/\/[^\/]*/);
1333 + return !m || (m[0] == '#{protocol}//#{domain}#{port}'.interpolate({
1334 + protocol: location.protocol,
1335 + domain: document.domain,
1336 + port: location.port ? ':' + location.port : ''
1337 + }));
1338 + },
1339 +
1319 getHeader: function(name) {
1340 getHeader: function(name) {
1320 try {
1341 try {
1321 - return this.transport.getResponseHeader(name);
1342 + return this.transport.getResponseHeader(name) || null;
1322 } catch (e) { return null }
1343 } catch (e) { return null }
1323 },
1344 },
1324
1345
1325 evalResponse: function() {
1346 evalResponse: function() {
1326 try {
1347 try {
1327 return eval((this.transport.responseText || '').unfilterJSON());
1348 return eval((this.transport.responseText || '').unfilterJSON());
1328 } catch (e) {
1349 } catch (e) {
1329 this.dispatchException(e);
1350 this.dispatchException(e);
1330 }
1351 }
1331 },
1352 },
1332
1353
1333 dispatchException: function(exception) {
1354 dispatchException: function(exception) {
1334 (this.options.onException || Prototype.emptyFunction)(this, exception);
1355 (this.options.onException || Prototype.emptyFunction)(this, exception);
1335 Ajax.Responders.dispatch('onException', this, exception);
1356 Ajax.Responders.dispatch('onException', this, exception);
1336 }
1357 }
1337 });
1358 });
1338
1359
1339 Ajax.Request.Events =
1360 Ajax.Request.Events =
1340 ['Uninitialized', 'Loading', 'Loaded', 'Interactive', 'Complete'];
1361 ['Uninitialized', 'Loading', 'Loaded', 'Interactive', 'Complete'];
1341
1362
1342 Ajax.Response = Class.create({
1363 Ajax.Response = Class.create({
1343 initialize: function(request){
1364 initialize: function(request){
1344 this.request = request;
1365 this.request = request;
1345 var transport = this.transport = request.transport,
1366 var transport = this.transport = request.transport,
1346 readyState = this.readyState = transport.readyState;
1367 readyState = this.readyState = transport.readyState;
1347
1368
1348 if((readyState > 2 && !Prototype.Browser.IE) || readyState == 4) {
1369 if((readyState > 2 && !Prototype.Browser.IE) || readyState == 4) {
1349 this.status = this.getStatus();
1370 this.status = this.getStatus();
1350 this.statusText = this.getStatusText();
1371 this.statusText = this.getStatusText();
1351 this.responseText = String.interpret(transport.responseText);
1372 this.responseText = String.interpret(transport.responseText);
1352 this.headerJSON = this._getHeaderJSON();
1373 this.headerJSON = this._getHeaderJSON();
1353 }
1374 }
1354
1375
1355 if(readyState == 4) {
1376 if(readyState == 4) {
1356 var xml = transport.responseXML;
1377 var xml = transport.responseXML;
1357 this.responseXML = Object.isUndefined(xml) ? null : xml;
1378 this.responseXML = Object.isUndefined(xml) ? null : xml;
1358 this.responseJSON = this._getResponseJSON();
1379 this.responseJSON = this._getResponseJSON();
1359 }
1380 }
1360 },
1381 },
1361
1382
1362 status: 0,
1383 status: 0,
1363 statusText: '',
1384 statusText: '',
1364
1385
1365 getStatus: Ajax.Request.prototype.getStatus,
1386 getStatus: Ajax.Request.prototype.getStatus,
1366
1387
1367 getStatusText: function() {
1388 getStatusText: function() {
1368 try {
1389 try {
1369 return this.transport.statusText || '';
1390 return this.transport.statusText || '';
1370 } catch (e) { return '' }
1391 } catch (e) { return '' }
1371 },
1392 },
1372
1393
1373 getHeader: Ajax.Request.prototype.getHeader,
1394 getHeader: Ajax.Request.prototype.getHeader,
1374
1395
1375 getAllHeaders: function() {
1396 getAllHeaders: function() {
1376 try {
1397 try {
1377 return this.getAllResponseHeaders();
1398 return this.getAllResponseHeaders();
1378 } catch (e) { return null }
1399 } catch (e) { return null }
1379 },
1400 },
1380
1401
1381 getResponseHeader: function(name) {
1402 getResponseHeader: function(name) {
1382 return this.transport.getResponseHeader(name);
1403 return this.transport.getResponseHeader(name);
1383 },
1404 },
1384
1405
1385 getAllResponseHeaders: function() {
1406 getAllResponseHeaders: function() {
1386 return this.transport.getAllResponseHeaders();
1407 return this.transport.getAllResponseHeaders();
1387 },
1408 },
1388
1409
1389 _getHeaderJSON: function() {
1410 _getHeaderJSON: function() {
1390 var json = this.getHeader('X-JSON');
1411 var json = this.getHeader('X-JSON');
1391 if (!json) return null;
1412 if (!json) return null;
1392 json = decodeURIComponent(escape(json));
1413 json = decodeURIComponent(escape(json));
1393 try {
1414 try {
1394 - return json.evalJSON(this.request.options.sanitizeJSON);
1415 + return json.evalJSON(this.request.options.sanitizeJSON ||
1416 + !this.request.isSameOrigin());
1395 } catch (e) {
1417 } catch (e) {
1396 this.request.dispatchException(e);
1418 this.request.dispatchException(e);
1397 }
1419 }
1398 },
1420 },
1399
1421
1400 _getResponseJSON: function() {
1422 _getResponseJSON: function() {
1401 var options = this.request.options;
1423 var options = this.request.options;
1402 if (!options.evalJSON || (options.evalJSON != 'force' &&
1424 if (!options.evalJSON || (options.evalJSON != 'force' &&
1403 !(this.getHeader('Content-type') || '').include('application/json')) ||
1425 !(this.getHeader('Content-type') || '').include('application/json')) ||
1404 this.responseText.blank())
1426 this.responseText.blank())
1405 return null;
1427 return null;
1406 try {
1428 try {
1407 - return this.responseText.evalJSON(options.sanitizeJSON);
1429 + return this.responseText.evalJSON(options.sanitizeJSON ||
1430 + !this.request.isSameOrigin());
1408 } catch (e) {
1431 } catch (e) {
1409 this.request.dispatchException(e);
1432 this.request.dispatchException(e);
1410 }
1433 }
1411 }
1434 }
1412 });
1435 });
1413
1436
1414 Ajax.Updater = Class.create(Ajax.Request, {
1437 Ajax.Updater = Class.create(Ajax.Request, {
1415 initialize: function($super, container, url, options) {
1438 initialize: function($super, container, url, options) {
1416 this.container = {
1439 this.container = {
1417 success: (container.success || container),
1440 success: (container.success || container),
1418 failure: (container.failure || (container.success ? null : container))
1441 failure: (container.failure || (container.success ? null : container))
1419 };
1442 };
1420
1443
1421 options = Object.clone(options);
1444 options = Object.clone(options);
1422 var onComplete = options.onComplete;
1445 var onComplete = options.onComplete;
1423 options.onComplete = (function(response, json) {
1446 options.onComplete = (function(response, json) {
1424 this.updateContent(response.responseText);
1447 this.updateContent(response.responseText);
1425 if (Object.isFunction(onComplete)) onComplete(response, json);
1448 if (Object.isFunction(onComplete)) onComplete(response, json);
1426 }).bind(this);
1449 }).bind(this);
1427
1450
1428 $super(url, options);
1451 $super(url, options);
1429 },
1452 },
1430
1453
1431 updateContent: function(responseText) {
1454 updateContent: function(responseText) {
1432 var receiver = this.container[this.success() ? 'success' : 'failure'],
1455 var receiver = this.container[this.success() ? 'success' : 'failure'],
1433 options = this.options;
1456 options = this.options;
1434
1457
1435 if (!options.evalScripts) responseText = responseText.stripScripts();
1458 if (!options.evalScripts) responseText = responseText.stripScripts();
1436
1459
1437 if (receiver = $(receiver)) {
1460 if (receiver = $(receiver)) {
1438 if (options.insertion) {
1461 if (options.insertion) {
1439 if (Object.isString(options.insertion)) {
1462 if (Object.isString(options.insertion)) {
1440 var insertion = { }; insertion[options.insertion] = responseText;
1463 var insertion = { }; insertion[options.insertion] = responseText;
1441 receiver.insert(insertion);
1464 receiver.insert(insertion);
1442 }
1465 }
1443 else options.insertion(receiver, responseText);
1466 else options.insertion(receiver, responseText);
1444 }
1467 }
1445 else receiver.update(responseText);
1468 else receiver.update(responseText);
1446 }
1469 }
1447 }
1470 }
1448 });
1471 });
1449
1472
1450 Ajax.PeriodicalUpdater = Class.create(Ajax.Base, {
1473 Ajax.PeriodicalUpdater = Class.create(Ajax.Base, {
1451 initialize: function($super, container, url, options) {
1474 initialize: function($super, container, url, options) {
1452 $super(options);
1475 $super(options);
1453 this.onComplete = this.options.onComplete;
1476 this.onComplete = this.options.onComplete;
1454
1477
1455 this.frequency = (this.options.frequency || 2);
1478 this.frequency = (this.options.frequency || 2);
@@ -1501,285 +1524,291
1501 if (Prototype.BrowserFeatures.XPath) {
1524 if (Prototype.BrowserFeatures.XPath) {
1502 document._getElementsByXPath = function(expression, parentElement) {
1525 document._getElementsByXPath = function(expression, parentElement) {
1503 var results = [];
1526 var results = [];
1504 var query = document.evaluate(expression, $(parentElement) || document,
1527 var query = document.evaluate(expression, $(parentElement) || document,
1505 null, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);
1528 null, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);
1506 for (var i = 0, length = query.snapshotLength; i < length; i++)
1529 for (var i = 0, length = query.snapshotLength; i < length; i++)
1507 results.push(Element.extend(query.snapshotItem(i)));
1530 results.push(Element.extend(query.snapshotItem(i)));
1508 return results;
1531 return results;
1509 };
1532 };
1510 }
1533 }
1511
1534
1512 /*--------------------------------------------------------------------------*/
1535 /*--------------------------------------------------------------------------*/
1513
1536
1514 if (!window.Node) var Node = { };
1537 if (!window.Node) var Node = { };
1515
1538
1516 if (!Node.ELEMENT_NODE) {
1539 if (!Node.ELEMENT_NODE) {
1517 // DOM level 2 ECMAScript Language Binding
1540 // DOM level 2 ECMAScript Language Binding
1518 Object.extend(Node, {
1541 Object.extend(Node, {
1519 ELEMENT_NODE: 1,
1542 ELEMENT_NODE: 1,
1520 ATTRIBUTE_NODE: 2,
1543 ATTRIBUTE_NODE: 2,
1521 TEXT_NODE: 3,
1544 TEXT_NODE: 3,
1522 CDATA_SECTION_NODE: 4,
1545 CDATA_SECTION_NODE: 4,
1523 ENTITY_REFERENCE_NODE: 5,
1546 ENTITY_REFERENCE_NODE: 5,
1524 ENTITY_NODE: 6,
1547 ENTITY_NODE: 6,
1525 PROCESSING_INSTRUCTION_NODE: 7,
1548 PROCESSING_INSTRUCTION_NODE: 7,
1526 COMMENT_NODE: 8,
1549 COMMENT_NODE: 8,
1527 DOCUMENT_NODE: 9,
1550 DOCUMENT_NODE: 9,
1528 DOCUMENT_TYPE_NODE: 10,
1551 DOCUMENT_TYPE_NODE: 10,
1529 DOCUMENT_FRAGMENT_NODE: 11,
1552 DOCUMENT_FRAGMENT_NODE: 11,
1530 NOTATION_NODE: 12
1553 NOTATION_NODE: 12
1531 });
1554 });
1532 }
1555 }
1533
1556
1534 (function() {
1557 (function() {
1535 var element = this.Element;
1558 var element = this.Element;
1536 this.Element = function(tagName, attributes) {
1559 this.Element = function(tagName, attributes) {
1537 attributes = attributes || { };
1560 attributes = attributes || { };
1538 tagName = tagName.toLowerCase();
1561 tagName = tagName.toLowerCase();
1539 var cache = Element.cache;
1562 var cache = Element.cache;
1540 if (Prototype.Browser.IE && attributes.name) {
1563 if (Prototype.Browser.IE && attributes.name) {
1541 tagName = '<' + tagName + ' name="' + attributes.name + '">';
1564 tagName = '<' + tagName + ' name="' + attributes.name + '">';
1542 delete attributes.name;
1565 delete attributes.name;
1543 return Element.writeAttribute(document.createElement(tagName), attributes);
1566 return Element.writeAttribute(document.createElement(tagName), attributes);
1544 }
1567 }
1545 if (!cache[tagName]) cache[tagName] = Element.extend(document.createElement(tagName));
1568 if (!cache[tagName]) cache[tagName] = Element.extend(document.createElement(tagName));
1546 return Element.writeAttribute(cache[tagName].cloneNode(false), attributes);
1569 return Element.writeAttribute(cache[tagName].cloneNode(false), attributes);
1547 };
1570 };
1548 Object.extend(this.Element, element || { });
1571 Object.extend(this.Element, element || { });
1572 + if (element) this.Element.prototype = element.prototype;
1549 }).call(window);
1573 }).call(window);
1550
1574
1551 Element.cache = { };
1575 Element.cache = { };
1552
1576
1553 Element.Methods = {
1577 Element.Methods = {
1554 visible: function(element) {
1578 visible: function(element) {
1555 return $(element).style.display != 'none';
1579 return $(element).style.display != 'none';
1556 },
1580 },
1557
1581
1558 toggle: function(element) {
1582 toggle: function(element) {
1559 element = $(element);
1583 element = $(element);
1560 Element[Element.visible(element) ? 'hide' : 'show'](element);
1584 Element[Element.visible(element) ? 'hide' : 'show'](element);
1561 return element;
1585 return element;
1562 },
1586 },
1563
1587
1564 hide: function(element) {
1588 hide: function(element) {
1565 - $(element).style.display = 'none';
1589 + element = $(element);
1590 + element.style.display = 'none';
1566 return element;
1591 return element;
1567 },
1592 },
1568
1593
1569 show: function(element) {
1594 show: function(element) {
1570 - $(element).style.display = '';
1595 + element = $(element);
1596 + element.style.display = '';
1571 return element;
1597 return element;
1572 },
1598 },
1573
1599
1574 remove: function(element) {
1600 remove: function(element) {
1575 element = $(element);
1601 element = $(element);
1576 element.parentNode.removeChild(element);
1602 element.parentNode.removeChild(element);
1577 return element;
1603 return element;
1578 },
1604 },
1579
1605
1580 update: function(element, content) {
1606 update: function(element, content) {
1581 element = $(element);
1607 element = $(element);
1582 if (content && content.toElement) content = content.toElement();
1608 if (content && content.toElement) content = content.toElement();
1583 if (Object.isElement(content)) return element.update().insert(content);
1609 if (Object.isElement(content)) return element.update().insert(content);
1584 content = Object.toHTML(content);
1610 content = Object.toHTML(content);
1585 element.innerHTML = content.stripScripts();
1611 element.innerHTML = content.stripScripts();
1586 content.evalScripts.bind(content).defer();
1612 content.evalScripts.bind(content).defer();
1587 return element;
1613 return element;
1588 },
1614 },
1589
1615
1590 replace: function(element, content) {
1616 replace: function(element, content) {
1591 element = $(element);
1617 element = $(element);
1592 if (content && content.toElement) content = content.toElement();
1618 if (content && content.toElement) content = content.toElement();
1593 else if (!Object.isElement(content)) {
1619 else if (!Object.isElement(content)) {
1594 content = Object.toHTML(content);
1620 content = Object.toHTML(content);
1595 var range = element.ownerDocument.createRange();
1621 var range = element.ownerDocument.createRange();
1596 range.selectNode(element);
1622 range.selectNode(element);
1597 content.evalScripts.bind(content).defer();
1623 content.evalScripts.bind(content).defer();
1598 content = range.createContextualFragment(content.stripScripts());
1624 content = range.createContextualFragment(content.stripScripts());
1599 }
1625 }
1600 element.parentNode.replaceChild(content, element);
1626 element.parentNode.replaceChild(content, element);
1601 return element;
1627 return element;
1602 },
1628 },
1603
1629
1604 insert: function(element, insertions) {
1630 insert: function(element, insertions) {
1605 element = $(element);
1631 element = $(element);
1606
1632
1607 if (Object.isString(insertions) || Object.isNumber(insertions) ||
1633 if (Object.isString(insertions) || Object.isNumber(insertions) ||
1608 Object.isElement(insertions) || (insertions && (insertions.toElement || insertions.toHTML)))
1634 Object.isElement(insertions) || (insertions && (insertions.toElement || insertions.toHTML)))
1609 insertions = {bottom:insertions};
1635 insertions = {bottom:insertions};
1610
1636
1611 - var content, t, range;
1637 + var content, insert, tagName, childNodes;
1612 -
1638 +
1613 - for (position in insertions) {
1639 + for (var position in insertions) {
1614 content = insertions[position];
1640 content = insertions[position];
1615 position = position.toLowerCase();
1641 position = position.toLowerCase();
1616 - t = Element._insertionTranslations[position];
1642 + insert = Element._insertionTranslations[position];
1617
1643
1618 if (content && content.toElement) content = content.toElement();
1644 if (content && content.toElement) content = content.toElement();
1619 if (Object.isElement(content)) {
1645 if (Object.isElement(content)) {
1620 - t.insert(element, content);
1646 + insert(element, content);
1621 continue;
1647 continue;
1622 }
1648 }
1623
1649
1624 content = Object.toHTML(content);
1650 content = Object.toHTML(content);
1625
1651
1626 - range = element.ownerDocument.createRange();
1652 + tagName = ((position == 'before' || position == 'after')
1627 - t.initializeRange(element, range);
1653 + ? element.parentNode : element).tagName.toUpperCase();
1628 - t.insert(element, range.createContextualFragment(content.stripScripts()));
1654 +
1655 + childNodes = Element._getContentFromAnonymousElement(tagName, content.stripScripts());
1656 +
1657 + if (position == 'top' || position == 'after') childNodes.reverse();
1658 + childNodes.each(insert.curry(element));
1629
1659
1630 content.evalScripts.bind(content).defer();
1660 content.evalScripts.bind(content).defer();
1631 }
1661 }
1632
1662
1633 return element;
1663 return element;
1634 },
1664 },
1635
1665
1636 wrap: function(element, wrapper, attributes) {
1666 wrap: function(element, wrapper, attributes) {
1637 element = $(element);
1667 element = $(element);
1638 if (Object.isElement(wrapper))
1668 if (Object.isElement(wrapper))
1639 $(wrapper).writeAttribute(attributes || { });
1669 $(wrapper).writeAttribute(attributes || { });
1640 else if (Object.isString(wrapper)) wrapper = new Element(wrapper, attributes);
1670 else if (Object.isString(wrapper)) wrapper = new Element(wrapper, attributes);
1641 else wrapper = new Element('div', wrapper);
1671 else wrapper = new Element('div', wrapper);
1642 if (element.parentNode)
1672 if (element.parentNode)
1643 element.parentNode.replaceChild(wrapper, element);
1673 element.parentNode.replaceChild(wrapper, element);
1644 wrapper.appendChild(element);
1674 wrapper.appendChild(element);
1645 return wrapper;
1675 return wrapper;
1646 },
1676 },
1647
1677
1648 inspect: function(element) {
1678 inspect: function(element) {
1649 element = $(element);
1679 element = $(element);
1650 var result = '<' + element.tagName.toLowerCase();
1680 var result = '<' + element.tagName.toLowerCase();
1651 $H({'id': 'id', 'className': 'class'}).each(function(pair) {
1681 $H({'id': 'id', 'className': 'class'}).each(function(pair) {
1652 var property = pair.first(), attribute = pair.last();
1682 var property = pair.first(), attribute = pair.last();
1653 var value = (element[property] || '').toString();
1683 var value = (element[property] || '').toString();
1654 if (value) result += ' ' + attribute + '=' + value.inspect(true);
1684 if (value) result += ' ' + attribute + '=' + value.inspect(true);
1655 });
1685 });
1656 return result + '>';
1686 return result + '>';
1657 },
1687 },
1658
1688
1659 recursivelyCollect: function(element, property) {
1689 recursivelyCollect: function(element, property) {
1660 element = $(element);
1690 element = $(element);
1661 var elements = [];
1691 var elements = [];
1662 while (element = element[property])
1692 while (element = element[property])
1663 if (element.nodeType == 1)
1693 if (element.nodeType == 1)
1664 elements.push(Element.extend(element));
1694 elements.push(Element.extend(element));
1665 return elements;
1695 return elements;
1666 },
1696 },
1667
1697
1668 ancestors: function(element) {
1698 ancestors: function(element) {
1669 return $(element).recursivelyCollect('parentNode');
1699 return $(element).recursivelyCollect('parentNode');
1670 },
1700 },
1671
1701
1672 descendants: function(element) {
1702 descendants: function(element) {
1673 - return $(element).getElementsBySelector("*");
1703 + return $(element).select("*");
1674 },
1704 },
1675
1705
1676 firstDescendant: function(element) {
1706 firstDescendant: function(element) {
1677 element = $(element).firstChild;
1707 element = $(element).firstChild;
1678 while (element && element.nodeType != 1) element = element.nextSibling;
1708 while (element && element.nodeType != 1) element = element.nextSibling;
1679 return $(element);
1709 return $(element);
1680 },
1710 },
1681
1711
1682 immediateDescendants: function(element) {
1712 immediateDescendants: function(element) {
1683 if (!(element = $(element).firstChild)) return [];
1713 if (!(element = $(element).firstChild)) return [];
1684 while (element && element.nodeType != 1) element = element.nextSibling;
1714 while (element && element.nodeType != 1) element = element.nextSibling;
1685 if (element) return [element].concat($(element).nextSiblings());
1715 if (element) return [element].concat($(element).nextSiblings());
1686 return [];
1716 return [];
1687 },
1717 },
1688
1718
1689 previousSiblings: function(element) {
1719 previousSiblings: function(element) {
1690 return $(element).recursivelyCollect('previousSibling');
1720 return $(element).recursivelyCollect('previousSibling');
1691 },
1721 },
1692
1722
1693 nextSiblings: function(element) {
1723 nextSiblings: function(element) {
1694 return $(element).recursivelyCollect('nextSibling');
1724 return $(element).recursivelyCollect('nextSibling');
1695 },
1725 },
1696
1726
1697 siblings: function(element) {
1727 siblings: function(element) {
1698 element = $(element);
1728 element = $(element);
1699 return element.previousSiblings().reverse().concat(element.nextSiblings());
1729 return element.previousSiblings().reverse().concat(element.nextSiblings());
1700 },
1730 },
1701
1731
1702 match: function(element, selector) {
1732 match: function(element, selector) {
1703 if (Object.isString(selector))
1733 if (Object.isString(selector))
1704 selector = new Selector(selector);
1734 selector = new Selector(selector);
1705 return selector.match($(element));
1735 return selector.match($(element));
1706 },
1736 },
1707
1737
1708 up: function(element, expression, index) {
1738 up: function(element, expression, index) {
1709 element = $(element);
1739 element = $(element);
1710 if (arguments.length == 1) return $(element.parentNode);
1740 if (arguments.length == 1) return $(element.parentNode);
1711 var ancestors = element.ancestors();
1741 var ancestors = element.ancestors();
1712 - return expression ? Selector.findElement(ancestors, expression, index) :
1742 + return Object.isNumber(expression) ? ancestors[expression] :
1713 - ancestors[index || 0];
1743 + Selector.findElement(ancestors, expression, index);
1714 },
1744 },
1715
1745
1716 down: function(element, expression, index) {
1746 down: function(element, expression, index) {
1717 element = $(element);
1747 element = $(element);
1718 if (arguments.length == 1) return element.firstDescendant();
1748 if (arguments.length == 1) return element.firstDescendant();
1719 - var descendants = element.descendants();
1749 + return Object.isNumber(expression) ? element.descendants()[expression] :
1720 - return expression ? Selector.findElement(descendants, expression, index) :
1750 + Element.select(element, expression)[index || 0];
1721 - descendants[index || 0];
1722 },
1751 },
1723
1752
1724 previous: function(element, expression, index) {
1753 previous: function(element, expression, index) {
1725 element = $(element);
1754 element = $(element);
1726 if (arguments.length == 1) return $(Selector.handlers.previousElementSibling(element));
1755 if (arguments.length == 1) return $(Selector.handlers.previousElementSibling(element));
1727 var previousSiblings = element.previousSiblings();
1756 var previousSiblings = element.previousSiblings();
1728 - return expression ? Selector.findElement(previousSiblings, expression, index) :
1757 + return Object.isNumber(expression) ? previousSiblings[expression] :
1729 - previousSiblings[index || 0];
1758 + Selector.findElement(previousSiblings, expression, index);
1730 },
1759 },
1731
1760
1732 next: function(element, expression, index) {
1761 next: function(element, expression, index) {
1733 element = $(element);
1762 element = $(element);
1734 if (arguments.length == 1) return $(Selector.handlers.nextElementSibling(element));
1763 if (arguments.length == 1) return $(Selector.handlers.nextElementSibling(element));
1735 var nextSiblings = element.nextSiblings();
1764 var nextSiblings = element.nextSiblings();
1736 - return expression ? Selector.findElement(nextSiblings, expression, index) :
1765 + return Object.isNumber(expression) ? nextSiblings[expression] :
1737 - nextSiblings[index || 0];
1766 + Selector.findElement(nextSiblings, expression, index);
1738 },
1767 },
1739
1768
1740 select: function() {
1769 select: function() {
1741 var args = $A(arguments), element = $(args.shift());
1770 var args = $A(arguments), element = $(args.shift());
1742 return Selector.findChildElements(element, args);
1771 return Selector.findChildElements(element, args);
1743 },
1772 },
1744
1773
1745 adjacent: function() {
1774 adjacent: function() {
1746 var args = $A(arguments), element = $(args.shift());
1775 var args = $A(arguments), element = $(args.shift());
1747 return Selector.findChildElements(element.parentNode, args).without(element);
1776 return Selector.findChildElements(element.parentNode, args).without(element);
1748 },
1777 },
1749
1778
1750 identify: function(element) {
1779 identify: function(element) {
1751 element = $(element);
1780 element = $(element);
1752 var id = element.readAttribute('id'), self = arguments.callee;
1781 var id = element.readAttribute('id'), self = arguments.callee;
1753 if (id) return id;
1782 if (id) return id;
1754 do { id = 'anonymous_element_' + self.counter++ } while ($(id));
1783 do { id = 'anonymous_element_' + self.counter++ } while ($(id));
1755 element.writeAttribute('id', id);
1784 element.writeAttribute('id', id);
1756 return id;
1785 return id;
1757 },
1786 },
1758
1787
1759 readAttribute: function(element, name) {
1788 readAttribute: function(element, name) {
1760 element = $(element);
1789 element = $(element);
1761 if (Prototype.Browser.IE) {
1790 if (Prototype.Browser.IE) {
1762 var t = Element._attributeTranslations.read;
1791 var t = Element._attributeTranslations.read;
1763 if (t.values[name]) return t.values[name](element, name);
1792 if (t.values[name]) return t.values[name](element, name);
1764 if (t.names[name]) name = t.names[name];
1793 if (t.names[name]) name = t.names[name];
1765 if (name.include(':')) {
1794 if (name.include(':')) {
1766 return (!element.attributes || !element.attributes[name]) ? null :
1795 return (!element.attributes || !element.attributes[name]) ? null :
1767 element.attributes[name].value;
1796 element.attributes[name].value;
1768 }
1797 }
1769 }
1798 }
1770 return element.getAttribute(name);
1799 return element.getAttribute(name);
1771 },
1800 },
1772
1801
1773 writeAttribute: function(element, name, value) {
1802 writeAttribute: function(element, name, value) {
1774 element = $(element);
1803 element = $(element);
1775 var attributes = { }, t = Element._attributeTranslations.write;
1804 var attributes = { }, t = Element._attributeTranslations.write;
1776
1805
1777 if (typeof name == 'object') attributes = name;
1806 if (typeof name == 'object') attributes = name;
1778 else attributes[name] = Object.isUndefined(value) ? true : value;
1807 else attributes[name] = Object.isUndefined(value) ? true : value;
1779
1808
1780 for (var attr in attributes) {
1809 for (var attr in attributes) {
1781 name = t.names[attr] || attr;
1810 name = t.names[attr] || attr;
1782 value = attributes[attr];
1811 value = attributes[attr];
1783 if (t.values[attr]) name = t.values[attr](element, value);
1812 if (t.values[attr]) name = t.values[attr](element, value);
1784 if (value === false || value === null)
1813 if (value === false || value === null)
1785 element.removeAttribute(name);
1814 element.removeAttribute(name);
@@ -1803,1641 +1832,1677
1803 },
1832 },
1804
1833
1805 hasClassName: function(element, className) {
1834 hasClassName: function(element, className) {
1806 if (!(element = $(element))) return;
1835 if (!(element = $(element))) return;
1807 var elementClassName = element.className;
1836 var elementClassName = element.className;
1808 return (elementClassName.length > 0 && (elementClassName == className ||
1837 return (elementClassName.length > 0 && (elementClassName == className ||
1809 new RegExp("(^|\\s)" + className + "(\\s|$)").test(elementClassName)));
1838 new RegExp("(^|\\s)" + className + "(\\s|$)").test(elementClassName)));
1810 },
1839 },
1811
1840
1812 addClassName: function(element, className) {
1841 addClassName: function(element, className) {
1813 if (!(element = $(element))) return;
1842 if (!(element = $(element))) return;
1814 if (!element.hasClassName(className))
1843 if (!element.hasClassName(className))
1815 element.className += (element.className ? ' ' : '') + className;
1844 element.className += (element.className ? ' ' : '') + className;
1816 return element;
1845 return element;
1817 },
1846 },
1818
1847
1819 removeClassName: function(element, className) {
1848 removeClassName: function(element, className) {
1820 if (!(element = $(element))) return;
1849 if (!(element = $(element))) return;
1821 element.className = element.className.replace(
1850 element.className = element.className.replace(
1822 new RegExp("(^|\\s+)" + className + "(\\s+|$)"), ' ').strip();
1851 new RegExp("(^|\\s+)" + className + "(\\s+|$)"), ' ').strip();
1823 return element;
1852 return element;
1824 },
1853 },
1825
1854
1826 toggleClassName: function(element, className) {
1855 toggleClassName: function(element, className) {
1827 if (!(element = $(element))) return;
1856 if (!(element = $(element))) return;
1828 return element[element.hasClassName(className) ?
1857 return element[element.hasClassName(className) ?
1829 'removeClassName' : 'addClassName'](className);
1858 'removeClassName' : 'addClassName'](className);
1830 },
1859 },
1831
1860
1832 // removes whitespace-only text node children
1861 // removes whitespace-only text node children
1833 cleanWhitespace: function(element) {
1862 cleanWhitespace: function(element) {
1834 element = $(element);
1863 element = $(element);
1835 var node = element.firstChild;
1864 var node = element.firstChild;
1836 while (node) {
1865 while (node) {
1837 var nextNode = node.nextSibling;
1866 var nextNode = node.nextSibling;
1838 if (node.nodeType == 3 && !/\S/.test(node.nodeValue))
1867 if (node.nodeType == 3 && !/\S/.test(node.nodeValue))
1839 element.removeChild(node);
1868 element.removeChild(node);
1840 node = nextNode;
1869 node = nextNode;
1841 }
1870 }
1842 return element;
1871 return element;
1843 },
1872 },
1844
1873
1845 empty: function(element) {
1874 empty: function(element) {
1846 return $(element).innerHTML.blank();
1875 return $(element).innerHTML.blank();
1847 },
1876 },
1848
1877
1849 descendantOf: function(element, ancestor) {
1878 descendantOf: function(element, ancestor) {
1850 element = $(element), ancestor = $(ancestor);
1879 element = $(element), ancestor = $(ancestor);
1851 - var originalAncestor = ancestor;
1852
1880
1853 if (element.compareDocumentPosition)
1881 if (element.compareDocumentPosition)
1854 return (element.compareDocumentPosition(ancestor) & 8) === 8;
1882 return (element.compareDocumentPosition(ancestor) & 8) === 8;
1855
1883
1856 - if (element.sourceIndex && !Prototype.Browser.Opera) {
1884 + if (ancestor.contains)
1857 - var e = element.sourceIndex, a = ancestor.sourceIndex,
1885 + return ancestor.contains(element) && ancestor !== element;
1858 - nextAncestor = ancestor.nextSibling;
1859 - if (!nextAncestor) {
1860 - do { ancestor = ancestor.parentNode; }
1861 - while (!(nextAncestor = ancestor.nextSibling) && ancestor.parentNode);
1862 - }
1863 - if (nextAncestor) return (e > a && e < nextAncestor.sourceIndex);
1864 - }
1865
1886
1866 while (element = element.parentNode)
1887 while (element = element.parentNode)
1867 - if (element == originalAncestor) return true;
1888 + if (element == ancestor) return true;
1889 +
1868 return false;
1890 return false;
1869 },
1891 },
1870
1892
1871 scrollTo: function(element) {
1893 scrollTo: function(element) {
1872 element = $(element);
1894 element = $(element);
1873 var pos = element.cumulativeOffset();
1895 var pos = element.cumulativeOffset();
1874 window.scrollTo(pos[0], pos[1]);
1896 window.scrollTo(pos[0], pos[1]);
1875 return element;
1897 return element;
1876 },
1898 },
1877
1899
1878 getStyle: function(element, style) {
1900 getStyle: function(element, style) {
1879 element = $(element);
1901 element = $(element);
1880 style = style == 'float' ? 'cssFloat' : style.camelize();
1902 style = style == 'float' ? 'cssFloat' : style.camelize();
1881 var value = element.style[style];
1903 var value = element.style[style];
1882 - if (!value) {
1904 + if (!value || value == 'auto') {
1883 var css = document.defaultView.getComputedStyle(element, null);
1905 var css = document.defaultView.getComputedStyle(element, null);
1884 value = css ? css[style] : null;
1906 value = css ? css[style] : null;
1885 }
1907 }
1886 if (style == 'opacity') return value ? parseFloat(value) : 1.0;
1908 if (style == 'opacity') return value ? parseFloat(value) : 1.0;
1887 return value == 'auto' ? null : value;
1909 return value == 'auto' ? null : value;
1888 },
1910 },
1889
1911
1890 getOpacity: function(element) {
1912 getOpacity: function(element) {
1891 return $(element).getStyle('opacity');
1913 return $(element).getStyle('opacity');
1892 },
1914 },
1893
1915
1894 setStyle: function(element, styles) {
1916 setStyle: function(element, styles) {
1895 element = $(element);
1917 element = $(element);
1896 var elementStyle = element.style, match;
1918 var elementStyle = element.style, match;
1897 if (Object.isString(styles)) {
1919 if (Object.isString(styles)) {
1898 element.style.cssText += ';' + styles;
1920 element.style.cssText += ';' + styles;
1899 return styles.include('opacity') ?
1921 return styles.include('opacity') ?
1900 element.setOpacity(styles.match(/opacity:\s*(\d?\.?\d*)/)[1]) : element;
1922 element.setOpacity(styles.match(/opacity:\s*(\d?\.?\d*)/)[1]) : element;
1901 }
1923 }
1902 for (var property in styles)
1924 for (var property in styles)
1903 if (property == 'opacity') element.setOpacity(styles[property]);
1925 if (property == 'opacity') element.setOpacity(styles[property]);
1904 else
1926 else
1905 elementStyle[(property == 'float' || property == 'cssFloat') ?
1927 elementStyle[(property == 'float' || property == 'cssFloat') ?
1906 (Object.isUndefined(elementStyle.styleFloat) ? 'cssFloat' : 'styleFloat') :
1928 (Object.isUndefined(elementStyle.styleFloat) ? 'cssFloat' : 'styleFloat') :
1907 property] = styles[property];
1929 property] = styles[property];
1908
1930
1909 return element;
1931 return element;
1910 },
1932 },
1911
1933
1912 setOpacity: function(element, value) {
1934 setOpacity: function(element, value) {
1913 element = $(element);
1935 element = $(element);
1914 element.style.opacity = (value == 1 || value === '') ? '' :
1936 element.style.opacity = (value == 1 || value === '') ? '' :
1915 (value < 0.00001) ? 0 : value;
1937 (value < 0.00001) ? 0 : value;
1916 return element;
1938 return element;
1917 },
1939 },
1918
1940
1919 getDimensions: function(element) {
1941 getDimensions: function(element) {
1920 element = $(element);
1942 element = $(element);
1921 - var display = $(element).getStyle('display');
1943 + var display = element.getStyle('display');
1922 if (display != 'none' && display != null) // Safari bug
1944 if (display != 'none' && display != null) // Safari bug
1923 return {width: element.offsetWidth, height: element.offsetHeight};
1945 return {width: element.offsetWidth, height: element.offsetHeight};
1924
1946
1925 // All *Width and *Height properties give 0 on elements with display none,
1947 // All *Width and *Height properties give 0 on elements with display none,
1926 // so enable the element temporarily
1948 // so enable the element temporarily
1927 var els = element.style;
1949 var els = element.style;
1928 var originalVisibility = els.visibility;
1950 var originalVisibility = els.visibility;
1929 var originalPosition = els.position;
1951 var originalPosition = els.position;
1930 var originalDisplay = els.display;
1952 var originalDisplay = els.display;
1931 els.visibility = 'hidden';
1953 els.visibility = 'hidden';
1932 els.position = 'absolute';
1954 els.position = 'absolute';
1933 els.display = 'block';
1955 els.display = 'block';
1934 var originalWidth = element.clientWidth;
1956 var originalWidth = element.clientWidth;
1935 var originalHeight = element.clientHeight;
1957 var originalHeight = element.clientHeight;
1936 els.display = originalDisplay;
1958 els.display = originalDisplay;
1937 els.position = originalPosition;
1959 els.position = originalPosition;
1938 els.visibility = originalVisibility;
1960 els.visibility = originalVisibility;
1939 return {width: originalWidth, height: originalHeight};
1961 return {width: originalWidth, height: originalHeight};
1940 },
1962 },
1941
1963
1942 makePositioned: function(element) {
1964 makePositioned: function(element) {
1943 element = $(element);
1965 element = $(element);
1944 var pos = Element.getStyle(element, 'position');
1966 var pos = Element.getStyle(element, 'position');
1945 if (pos == 'static' || !pos) {
1967 if (pos == 'static' || !pos) {
1946 element._madePositioned = true;
1968 element._madePositioned = true;
1947 element.style.position = 'relative';
1969 element.style.position = 'relative';
1948 // Opera returns the offset relative to the positioning context, when an
1970 // Opera returns the offset relative to the positioning context, when an
1949 // element is position relative but top and left have not been defined
1971 // element is position relative but top and left have not been defined
1950 - if (window.opera) {
1972 + if (Prototype.Browser.Opera) {
1951 element.style.top = 0;
1973 element.style.top = 0;
1952 element.style.left = 0;
1974 element.style.left = 0;
1953 }
1975 }
1954 }
1976 }
1955 return element;
1977 return element;
1956 },
1978 },
1957
1979
1958 undoPositioned: function(element) {
1980 undoPositioned: function(element) {
1959 element = $(element);
1981 element = $(element);
1960 if (element._madePositioned) {
1982 if (element._madePositioned) {
1961 element._madePositioned = undefined;
1983 element._madePositioned = undefined;
1962 element.style.position =
1984 element.style.position =
1963 element.style.top =
1985 element.style.top =
1964 element.style.left =
1986 element.style.left =
1965 element.style.bottom =
1987 element.style.bottom =
1966 element.style.right = '';
1988 element.style.right = '';
1967 }
1989 }
1968 return element;
1990 return element;
1969 },
1991 },
1970
1992
1971 makeClipping: function(element) {
1993 makeClipping: function(element) {
1972 element = $(element);
1994 element = $(element);
1973 if (element._overflow) return element;
1995 if (element._overflow) return element;
1974 element._overflow = Element.getStyle(element, 'overflow') || 'auto';
1996 element._overflow = Element.getStyle(element, 'overflow') || 'auto';
1975 if (element._overflow !== 'hidden')
1997 if (element._overflow !== 'hidden')
1976 element.style.overflow = 'hidden';
1998 element.style.overflow = 'hidden';
1977 return element;
1999 return element;
1978 },
2000 },
1979
2001
1980 undoClipping: function(element) {
2002 undoClipping: function(element) {
1981 element = $(element);
2003 element = $(element);
1982 if (!element._overflow) return element;
2004 if (!element._overflow) return element;
1983 element.style.overflow = element._overflow == 'auto' ? '' : element._overflow;
2005 element.style.overflow = element._overflow == 'auto' ? '' : element._overflow;
1984 element._overflow = null;
2006 element._overflow = null;
1985 return element;
2007 return element;
1986 },
2008 },
1987
2009
1988 cumulativeOffset: function(element) {
2010 cumulativeOffset: function(element) {
1989 var valueT = 0, valueL = 0;
2011 var valueT = 0, valueL = 0;
1990 do {
2012 do {
1991 valueT += element.offsetTop || 0;
2013 valueT += element.offsetTop || 0;
1992 valueL += element.offsetLeft || 0;
2014 valueL += element.offsetLeft || 0;
1993 element = element.offsetParent;
2015 element = element.offsetParent;
1994 } while (element);
2016 } while (element);
1995 return Element._returnOffset(valueL, valueT);
2017 return Element._returnOffset(valueL, valueT);
1996 },
2018 },
1997
2019
1998 positionedOffset: function(element) {
2020 positionedOffset: function(element) {
1999 var valueT = 0, valueL = 0;
2021 var valueT = 0, valueL = 0;
2000 do {
2022 do {
2001 valueT += element.offsetTop || 0;
2023 valueT += element.offsetTop || 0;
2002 valueL += element.offsetLeft || 0;
2024 valueL += element.offsetLeft || 0;
2003 element = element.offsetParent;
2025 element = element.offsetParent;
2004 if (element) {
2026 if (element) {
2005 - if (element.tagName == 'BODY') break;
2027 + if (element.tagName.toUpperCase() == 'BODY') break;
2006 var p = Element.getStyle(element, 'position');
2028 var p = Element.getStyle(element, 'position');
2007 - if (p == 'relative' || p == 'absolute') break;
2029 + if (p !== 'static') break;
2008 }
2030 }
2009 } while (element);
2031 } while (element);
2010 return Element._returnOffset(valueL, valueT);
2032 return Element._returnOffset(valueL, valueT);
2011 },
2033 },
2012
2034
2013 absolutize: function(element) {
2035 absolutize: function(element) {
2014 element = $(element);
2036 element = $(element);
2015 - if (element.getStyle('position') == 'absolute') return;
2037 + if (element.getStyle('position') == 'absolute') return element;
2016 // Position.prepare(); // To be done manually by Scripty when it needs it.
2038 // Position.prepare(); // To be done manually by Scripty when it needs it.
2017
2039
2018 var offsets = element.positionedOffset();
2040 var offsets = element.positionedOffset();
2019 var top = offsets[1];
2041 var top = offsets[1];
2020 var left = offsets[0];
2042 var left = offsets[0];
2021 var width = element.clientWidth;
2043 var width = element.clientWidth;
2022 var height = element.clientHeight;
2044 var height = element.clientHeight;
2023
2045
2024 element._originalLeft = left - parseFloat(element.style.left || 0);
2046 element._originalLeft = left - parseFloat(element.style.left || 0);
2025 element._originalTop = top - parseFloat(element.style.top || 0);
2047 element._originalTop = top - parseFloat(element.style.top || 0);
2026 element._originalWidth = element.style.width;
2048 element._originalWidth = element.style.width;
2027 element._originalHeight = element.style.height;
2049 element._originalHeight = element.style.height;
2028
2050
2029 element.style.position = 'absolute';
2051 element.style.position = 'absolute';
2030 element.style.top = top + 'px';
2052 element.style.top = top + 'px';
2031 element.style.left = left + 'px';
2053 element.style.left = left + 'px';
2032 element.style.width = width + 'px';
2054 element.style.width = width + 'px';
2033 element.style.height = height + 'px';
2055 element.style.height = height + 'px';
2034 return element;
2056 return element;
2035 },
2057 },
2036
2058
2037 relativize: function(element) {
2059 relativize: function(element) {
2038 element = $(element);
2060 element = $(element);
2039 - if (element.getStyle('position') == 'relative') return;
2061 + if (element.getStyle('position') == 'relative') return element;
2040 // Position.prepare(); // To be done manually by Scripty when it needs it.
2062 // Position.prepare(); // To be done manually by Scripty when it needs it.
2041
2063
2042 element.style.position = 'relative';
2064 element.style.position = 'relative';
2043 var top = parseFloat(element.style.top || 0) - (element._originalTop || 0);
2065 var top = parseFloat(element.style.top || 0) - (element._originalTop || 0);
2044 var left = parseFloat(element.style.left || 0) - (element._originalLeft || 0);
2066 var left = parseFloat(element.style.left || 0) - (element._originalLeft || 0);
2045
2067
2046 element.style.top = top + 'px';
2068 element.style.top = top + 'px';
2047 element.style.left = left + 'px';
2069 element.style.left = left + 'px';
2048 element.style.height = element._originalHeight;
2070 element.style.height = element._originalHeight;
2049 element.style.width = element._originalWidth;
2071 element.style.width = element._originalWidth;
2050 return element;
2072 return element;
2051 },
2073 },
2052
2074
2053 cumulativeScrollOffset: function(element) {
2075 cumulativeScrollOffset: function(element) {
2054 var valueT = 0, valueL = 0;
2076 var valueT = 0, valueL = 0;
2055 do {
2077 do {
2056 valueT += element.scrollTop || 0;
2078 valueT += element.scrollTop || 0;
2057 valueL += element.scrollLeft || 0;
2079 valueL += element.scrollLeft || 0;
2058 element = element.parentNode;
2080 element = element.parentNode;
2059 } while (element);
2081 } while (element);
2060 return Element._returnOffset(valueL, valueT);
2082 return Element._returnOffset(valueL, valueT);
2061 },
2083 },
2062
2084
2063 getOffsetParent: function(element) {
2085 getOffsetParent: function(element) {
2064 if (element.offsetParent) return $(element.offsetParent);
2086 if (element.offsetParent) return $(element.offsetParent);
2065 if (element == document.body) return $(element);
2087 if (element == document.body) return $(element);
2066
2088
2067 while ((element = element.parentNode) && element != document.body)
2089 while ((element = element.parentNode) && element != document.body)
2068 if (Element.getStyle(element, 'position') != 'static')
2090 if (Element.getStyle(element, 'position') != 'static')
2069 return $(element);
2091 return $(element);
2070
2092
2071 return $(document.body);
2093 return $(document.body);
2072 },
2094 },
2073
2095
2074 viewportOffset: function(forElement) {
2096 viewportOffset: function(forElement) {
2075 var valueT = 0, valueL = 0;
2097 var valueT = 0, valueL = 0;
2076
2098
2077 var element = forElement;
2099 var element = forElement;
2078 do {
2100 do {
2079 valueT += element.offsetTop || 0;
2101 valueT += element.offsetTop || 0;
2080 valueL += element.offsetLeft || 0;
2102 valueL += element.offsetLeft || 0;
2081
2103
2082 // Safari fix
2104 // Safari fix
2083 if (element.offsetParent == document.body &&
2105 if (element.offsetParent == document.body &&
2084 Element.getStyle(element, 'position') == 'absolute') break;
2106 Element.getStyle(element, 'position') == 'absolute') break;
2085
2107
2086 } while (element = element.offsetParent);
2108 } while (element = element.offsetParent);
2087
2109
2088 element = forElement;
2110 element = forElement;
2089 do {
2111 do {
2090 - if (!Prototype.Browser.Opera || element.tagName == 'BODY') {
2112 + if (!Prototype.Browser.Opera || (element.tagName && (element.tagName.toUpperCase() == 'BODY'))) {
2091 valueT -= element.scrollTop || 0;
2113 valueT -= element.scrollTop || 0;
2092 valueL -= element.scrollLeft || 0;
2114 valueL -= element.scrollLeft || 0;
2093 }
2115 }
2094 } while (element = element.parentNode);
2116 } while (element = element.parentNode);
2095
2117
2096 return Element._returnOffset(valueL, valueT);
2118 return Element._returnOffset(valueL, valueT);
2097 },
2119 },
2098
2120
2099 clonePosition: function(element, source) {
2121 clonePosition: function(element, source) {
2100 var options = Object.extend({
2122 var options = Object.extend({
2101 setLeft: true,
2123 setLeft: true,
2102 setTop: true,
2124 setTop: true,
2103 setWidth: true,
2125 setWidth: true,
2104 setHeight: true,
2126 setHeight: true,
2105 offsetTop: 0,
2127 offsetTop: 0,
2106 offsetLeft: 0
2128 offsetLeft: 0
2107 }, arguments[2] || { });
2129 }, arguments[2] || { });
2108
2130
2109 // find page position of source
2131 // find page position of source
2110 source = $(source);
2132 source = $(source);
2111 var p = source.viewportOffset();
2133 var p = source.viewportOffset();
2112
2134
2113 // find coordinate system to use
2135 // find coordinate system to use
2114 element = $(element);
2136 element = $(element);
2115 var delta = [0, 0];
2137 var delta = [0, 0];
2116 var parent = null;
2138 var parent = null;
2117 // delta [0,0] will do fine with position: fixed elements,
2139 // delta [0,0] will do fine with position: fixed elements,
2118 // position:absolute needs offsetParent deltas
2140 // position:absolute needs offsetParent deltas
2119 if (Element.getStyle(element, 'position') == 'absolute') {
2141 if (Element.getStyle(element, 'position') == 'absolute') {
2120 parent = element.getOffsetParent();
2142 parent = element.getOffsetParent();
2121 delta = parent.viewportOffset();
2143 delta = parent.viewportOffset();
2122 }
2144 }
2123
2145
2124 // correct by body offsets (fixes Safari)
2146 // correct by body offsets (fixes Safari)
2125 if (parent == document.body) {
2147 if (parent == document.body) {
2126 delta[0] -= document.body.offsetLeft;
2148 delta[0] -= document.body.offsetLeft;
2127 delta[1] -= document.body.offsetTop;
2149 delta[1] -= document.body.offsetTop;
2128 }
2150 }
2129
2151
2130 // set position
2152 // set position
2131 if (options.setLeft) element.style.left = (p[0] - delta[0] + options.offsetLeft) + 'px';
2153 if (options.setLeft) element.style.left = (p[0] - delta[0] + options.offsetLeft) + 'px';
2132 if (options.setTop) element.style.top = (p[1] - delta[1] + options.offsetTop) + 'px';
2154 if (options.setTop) element.style.top = (p[1] - delta[1] + options.offsetTop) + 'px';
2133 if (options.setWidth) element.style.width = source.offsetWidth + 'px';
2155 if (options.setWidth) element.style.width = source.offsetWidth + 'px';
2134 if (options.setHeight) element.style.height = source.offsetHeight + 'px';
2156 if (options.setHeight) element.style.height = source.offsetHeight + 'px';
2135 return element;
2157 return element;
2136 }
2158 }
2137 };
2159 };
2138
2160
2139 Element.Methods.identify.counter = 1;
2161 Element.Methods.identify.counter = 1;
2140
2162
2141 Object.extend(Element.Methods, {
2163 Object.extend(Element.Methods, {
2142 getElementsBySelector: Element.Methods.select,
2164 getElementsBySelector: Element.Methods.select,
2143 childElements: Element.Methods.immediateDescendants
2165 childElements: Element.Methods.immediateDescendants
2144 });
2166 });
2145
2167
2146 Element._attributeTranslations = {
2168 Element._attributeTranslations = {
2147 write: {
2169 write: {
2148 names: {
2170 names: {
2149 className: 'class',
2171 className: 'class',
2150 htmlFor: 'for'
2172 htmlFor: 'for'
2151 },
2173 },
2152 values: { }
2174 values: { }
2153 }
2175 }
2154 };
2176 };
2155
2177
2156 -
2157 - if (!document.createRange || Prototype.Browser.Opera) {
2158 - Element.Methods.insert = function(element, insertions) {
2159 - element = $(element);
2160 -
2161 - if (Object.isString(insertions) || Object.isNumber(insertions) ||
2162 - Object.isElement(insertions) || (insertions && (insertions.toElement || insertions.toHTML)))
2163 - insertions = { bottom: insertions };
2164 -
2165 - var t = Element._insertionTranslations, content, position, pos, tagName;
2166 -
2167 - for (position in insertions) {
2168 - content = insertions[position];
2169 - position = position.toLowerCase();
2170 - pos = t[position];
2171 -
2172 - if (content && content.toElement) content = content.toElement();
2173 - if (Object.isElement(content)) {
2174 - pos.insert(element, content);
2175 - continue;
2176 - }
2177 -
2178 - content = Object.toHTML(content);
2179 - tagName = ((position == 'before' || position == 'after')
2180 - ? element.parentNode : element).tagName.toUpperCase();
2181 -
2182 - if (t.tags[tagName]) {
2183 - var fragments = Element._getContentFromAnonymousElement(tagName, content.stripScripts());
2184 - if (position == 'top' || position == 'after') fragments.reverse();
2185 - fragments.each(pos.insert.curry(element));
2186 - }
2187 - else element.insertAdjacentHTML(pos.adjacency, content.stripScripts());
2188 -
2189 - content.evalScripts.bind(content).defer();
2190 - }
2191 -
2192 - return element;
2193 - };
2194 - }
2195 -
2196 if (Prototype.Browser.Opera) {
2178 if (Prototype.Browser.Opera) {
2197 Element.Methods.getStyle = Element.Methods.getStyle.wrap(
2179 Element.Methods.getStyle = Element.Methods.getStyle.wrap(
2198 function(proceed, element, style) {
2180 function(proceed, element, style) {
2199 switch (style) {
2181 switch (style) {
2200 case 'left': case 'top': case 'right': case 'bottom':
2182 case 'left': case 'top': case 'right': case 'bottom':
2201 if (proceed(element, 'position') === 'static') return null;
2183 if (proceed(element, 'position') === 'static') return null;
2202 case 'height': case 'width':
2184 case 'height': case 'width':
2203 // returns '0px' for hidden elements; we want it to return null
2185 // returns '0px' for hidden elements; we want it to return null
2204 if (!Element.visible(element)) return null;
2186 if (!Element.visible(element)) return null;
2205
2187
2206 // returns the border-box dimensions rather than the content-box
2188 // returns the border-box dimensions rather than the content-box
2207 // dimensions, so we subtract padding and borders from the value
2189 // dimensions, so we subtract padding and borders from the value
2208 var dim = parseInt(proceed(element, style), 10);
2190 var dim = parseInt(proceed(element, style), 10);
2209
2191
2210 if (dim !== element['offset' + style.capitalize()])
2192 if (dim !== element['offset' + style.capitalize()])
2211 return dim + 'px';
2193 return dim + 'px';
2212
2194
2213 var properties;
2195 var properties;
2214 if (style === 'height') {
2196 if (style === 'height') {
2215 properties = ['border-top-width', 'padding-top',
2197 properties = ['border-top-width', 'padding-top',
2216 'padding-bottom', 'border-bottom-width'];
2198 'padding-bottom', 'border-bottom-width'];
2217 }
2199 }
2218 else {
2200 else {
2219 properties = ['border-left-width', 'padding-left',
2201 properties = ['border-left-width', 'padding-left',
2220 'padding-right', 'border-right-width'];
2202 'padding-right', 'border-right-width'];
2221 }
2203 }
2222 return properties.inject(dim, function(memo, property) {
2204 return properties.inject(dim, function(memo, property) {
2223 var val = proceed(element, property);
2205 var val = proceed(element, property);
2224 return val === null ? memo : memo - parseInt(val, 10);
2206 return val === null ? memo : memo - parseInt(val, 10);
2225 }) + 'px';
2207 }) + 'px';
2226 default: return proceed(element, style);
2208 default: return proceed(element, style);
2227 }
2209 }
2228 }
2210 }
2229 );
2211 );
2230
2212
2231 Element.Methods.readAttribute = Element.Methods.readAttribute.wrap(
2213 Element.Methods.readAttribute = Element.Methods.readAttribute.wrap(
2232 function(proceed, element, attribute) {
2214 function(proceed, element, attribute) {
2233 if (attribute === 'title') return element.title;
2215 if (attribute === 'title') return element.title;
2234 return proceed(element, attribute);
2216 return proceed(element, attribute);
2235 }
2217 }
2236 );
2218 );
2237 }
2219 }
2238
2220
2239 else if (Prototype.Browser.IE) {
2221 else if (Prototype.Browser.IE) {
2240 - $w('positionedOffset getOffsetParent viewportOffset').each(function(method) {
2222 + // IE doesn't report offsets correctly for static elements, so we change them
2223 + // to "relative" to get the values, then change them back.
2224 + Element.Methods.getOffsetParent = Element.Methods.getOffsetParent.wrap(
2225 + function(proceed, element) {
2226 + element = $(element);
2227 + // IE throws an error if element is not in document
2228 + try { element.offsetParent }
2229 + catch(e) { return $(document.body) }
2230 + var position = element.getStyle('position');
2231 + if (position !== 'static') return proceed(element);
2232 + element.setStyle({ position: 'relative' });
2233 + var value = proceed(element);
2234 + element.setStyle({ position: position });
2235 + return value;
2236 + }
2237 + );
2238 +
2239 + $w('positionedOffset viewportOffset').each(function(method) {
2241 Element.Methods[method] = Element.Methods[method].wrap(
2240 Element.Methods[method] = Element.Methods[method].wrap(
2242 function(proceed, element) {
2241 function(proceed, element) {
2243 element = $(element);
2242 element = $(element);
2243 + try { element.offsetParent }
2244 + catch(e) { return Element._returnOffset(0,0) }
2244 var position = element.getStyle('position');
2245 var position = element.getStyle('position');
2245 - if (position != 'static') return proceed(element);
2246 + if (position !== 'static') return proceed(element);
2247 + // Trigger hasLayout on the offset parent so that IE6 reports
2248 + // accurate offsetTop and offsetLeft values for position: fixed.
2249 + var offsetParent = element.getOffsetParent();
2250 + if (offsetParent && offsetParent.getStyle('position') === 'fixed')
2251 + offsetParent.setStyle({ zoom: 1 });
2246 element.setStyle({ position: 'relative' });
2252 element.setStyle({ position: 'relative' });
2247 var value = proceed(element);
2253 var value = proceed(element);
2248 element.setStyle({ position: position });
2254 element.setStyle({ position: position });
2249 return value;
2255 return value;
2250 }
2256 }
2251 );
2257 );
2252 });
2258 });
2253
2259
2260 + Element.Methods.cumulativeOffset = Element.Methods.cumulativeOffset.wrap(
2261 + function(proceed, element) {
2262 + try { element.offsetParent }
2263 + catch(e) { return Element._returnOffset(0,0) }
2264 + return proceed(element);
2265 + }
2266 + );
2267 +
2254 Element.Methods.getStyle = function(element, style) {
2268 Element.Methods.getStyle = function(element, style) {
2255 element = $(element);
2269 element = $(element);
2256 style = (style == 'float' || style == 'cssFloat') ? 'styleFloat' : style.camelize();
2270 style = (style == 'float' || style == 'cssFloat') ? 'styleFloat' : style.camelize();
2257 var value = element.style[style];
2271 var value = element.style[style];
2258 if (!value && element.currentStyle) value = element.currentStyle[style];
2272 if (!value && element.currentStyle) value = element.currentStyle[style];
2259
2273
2260 if (style == 'opacity') {
2274 if (style == 'opacity') {
2261 if (value = (element.getStyle('filter') || '').match(/alpha\(opacity=(.*)\)/))
2275 if (value = (element.getStyle('filter') || '').match(/alpha\(opacity=(.*)\)/))
2262 if (value[1]) return parseFloat(value[1]) / 100;
2276 if (value[1]) return parseFloat(value[1]) / 100;
2263 return 1.0;
2277 return 1.0;
2264 }
2278 }
2265
2279
2266 if (value == 'auto') {
2280 if (value == 'auto') {
2267 if ((style == 'width' || style == 'height') && (element.getStyle('display') != 'none'))
2281 if ((style == 'width' || style == 'height') && (element.getStyle('display') != 'none'))
2268 return element['offset' + style.capitalize()] + 'px';
2282 return element['offset' + style.capitalize()] + 'px';
2269 return null;
2283 return null;
2270 }
2284 }
2271 return value;
2285 return value;
2272 };
2286 };
2273
2287
2274 Element.Methods.setOpacity = function(element, value) {
2288 Element.Methods.setOpacity = function(element, value) {
2275 function stripAlpha(filter){
2289 function stripAlpha(filter){
2276 return filter.replace(/alpha\([^\)]*\)/gi,'');
2290 return filter.replace(/alpha\([^\)]*\)/gi,'');
2277 }
2291 }
2278 element = $(element);
2292 element = $(element);
2279 var currentStyle = element.currentStyle;
2293 var currentStyle = element.currentStyle;
2280 if ((currentStyle && !currentStyle.hasLayout) ||
2294 if ((currentStyle && !currentStyle.hasLayout) ||
2281 (!currentStyle && element.style.zoom == 'normal'))
2295 (!currentStyle && element.style.zoom == 'normal'))
2282 element.style.zoom = 1;
2296 element.style.zoom = 1;
2283
2297
2284 var filter = element.getStyle('filter'), style = element.style;
2298 var filter = element.getStyle('filter'), style = element.style;
2285 if (value == 1 || value === '') {
2299 if (value == 1 || value === '') {
2286 (filter = stripAlpha(filter)) ?
2300 (filter = stripAlpha(filter)) ?
2287 style.filter = filter : style.removeAttribute('filter');
2301 style.filter = filter : style.removeAttribute('filter');
2288 return element;
2302 return element;
2289 } else if (value < 0.00001) value = 0;
2303 } else if (value < 0.00001) value = 0;
2290 style.filter = stripAlpha(filter) +
2304 style.filter = stripAlpha(filter) +
2291 'alpha(opacity=' + (value * 100) + ')';
2305 'alpha(opacity=' + (value * 100) + ')';
2292 return element;
2306 return element;
2293 };
2307 };
2294
2308
2295 Element._attributeTranslations = {
2309 Element._attributeTranslations = {
2296 read: {
2310 read: {
2297 names: {
2311 names: {
2298 'class': 'className',
2312 'class': 'className',
2299 'for': 'htmlFor'
2313 'for': 'htmlFor'
2300 },
2314 },
2301 values: {
2315 values: {
2302 _getAttr: function(element, attribute) {
2316 _getAttr: function(element, attribute) {
2303 return element.getAttribute(attribute, 2);
2317 return element.getAttribute(attribute, 2);
2304 },
2318 },
2305 _getAttrNode: function(element, attribute) {
2319 _getAttrNode: function(element, attribute) {
2306 var node = element.getAttributeNode(attribute);
2320 var node = element.getAttributeNode(attribute);
2307 return node ? node.value : "";
2321 return node ? node.value : "";
2308 },
2322 },
2309 _getEv: function(element, attribute) {
2323 _getEv: function(element, attribute) {
2310 attribute = element.getAttribute(attribute);
2324 attribute = element.getAttribute(attribute);
2311 return attribute ? attribute.toString().slice(23, -2) : null;
2325 return attribute ? attribute.toString().slice(23, -2) : null;
2312 },
2326 },
2313 _flag: function(element, attribute) {
2327 _flag: function(element, attribute) {
2314 return $(element).hasAttribute(attribute) ? attribute : null;
2328 return $(element).hasAttribute(attribute) ? attribute : null;
2315 },
2329 },
2316 style: function(element) {
2330 style: function(element) {
2317 return element.style.cssText.toLowerCase();
2331 return element.style.cssText.toLowerCase();
2318 },
2332 },
2319 title: function(element) {
2333 title: function(element) {
2320 return element.title;
2334 return element.title;
2321 }
2335 }
2322 }
2336 }
2323 }
2337 }
2324 };
2338 };
2325
2339
2326 Element._attributeTranslations.write = {
2340 Element._attributeTranslations.write = {
2327 - names: Object.clone(Element._attributeTranslations.read.names),
2341 + names: Object.extend({
2342 + cellpadding: 'cellPadding',
2343 + cellspacing: 'cellSpacing'
2344 + }, Element._attributeTranslations.read.names),
2328 values: {
2345 values: {
2329 checked: function(element, value) {
2346 checked: function(element, value) {
2330 element.checked = !!value;
2347 element.checked = !!value;
2331 },
2348 },
2332
2349
2333 style: function(element, value) {
2350 style: function(element, value) {
2334 element.style.cssText = value ? value : '';
2351 element.style.cssText = value ? value : '';
2335 }
2352 }
2336 }
2353 }
2337 };
2354 };
2338
2355
2339 Element._attributeTranslations.has = {};
2356 Element._attributeTranslations.has = {};
2340
2357
2341 $w('colSpan rowSpan vAlign dateTime accessKey tabIndex ' +
2358 $w('colSpan rowSpan vAlign dateTime accessKey tabIndex ' +
2342 - 'encType maxLength readOnly longDesc').each(function(attr) {
2359 + 'encType maxLength readOnly longDesc frameBorder').each(function(attr) {
2343 Element._attributeTranslations.write.names[attr.toLowerCase()] = attr;
2360 Element._attributeTranslations.write.names[attr.toLowerCase()] = attr;
2344 Element._attributeTranslations.has[attr.toLowerCase()] = attr;
2361 Element._attributeTranslations.has[attr.toLowerCase()] = attr;
2345 });
2362 });
2346
2363
2347 (function(v) {
2364 (function(v) {
2348 Object.extend(v, {
2365 Object.extend(v, {
2349 href: v._getAttr,
2366 href: v._getAttr,
2350 src: v._getAttr,
2367 src: v._getAttr,
2351 type: v._getAttr,
2368 type: v._getAttr,
2352 action: v._getAttrNode,
2369 action: v._getAttrNode,
2353 disabled: v._flag,
2370 disabled: v._flag,
2354 checked: v._flag,
2371 checked: v._flag,
2355 readonly: v._flag,
2372 readonly: v._flag,
2356 multiple: v._flag,
2373 multiple: v._flag,
2357 onload: v._getEv,
2374 onload: v._getEv,
2358 onunload: v._getEv,
2375 onunload: v._getEv,
2359 onclick: v._getEv,
2376 onclick: v._getEv,
2360 ondblclick: v._getEv,
2377 ondblclick: v._getEv,
2361 onmousedown: v._getEv,
2378 onmousedown: v._getEv,
2362 onmouseup: v._getEv,
2379 onmouseup: v._getEv,
2363 onmouseover: v._getEv,
2380 onmouseover: v._getEv,
2364 onmousemove: v._getEv,
2381 onmousemove: v._getEv,
2365 onmouseout: v._getEv,
2382 onmouseout: v._getEv,
2366 onfocus: v._getEv,
2383 onfocus: v._getEv,
2367 onblur: v._getEv,
2384 onblur: v._getEv,
2368 onkeypress: v._getEv,
2385 onkeypress: v._getEv,
2369 onkeydown: v._getEv,
2386 onkeydown: v._getEv,
2370 onkeyup: v._getEv,
2387 onkeyup: v._getEv,
2371 onsubmit: v._getEv,
2388 onsubmit: v._getEv,
2372 onreset: v._getEv,
2389 onreset: v._getEv,
2373 onselect: v._getEv,
2390 onselect: v._getEv,
2374 onchange: v._getEv
2391 onchange: v._getEv
2375 });
2392 });
2376 })(Element._attributeTranslations.read.values);
2393 })(Element._attributeTranslations.read.values);
2377 }
2394 }
2378
2395
2379 else if (Prototype.Browser.Gecko && /rv:1\.8\.0/.test(navigator.userAgent)) {
2396 else if (Prototype.Browser.Gecko && /rv:1\.8\.0/.test(navigator.userAgent)) {
2380 Element.Methods.setOpacity = function(element, value) {
2397 Element.Methods.setOpacity = function(element, value) {
2381 element = $(element);
2398 element = $(element);
2382 element.style.opacity = (value == 1) ? 0.999999 :
2399 element.style.opacity = (value == 1) ? 0.999999 :
2383 (value === '') ? '' : (value < 0.00001) ? 0 : value;
2400 (value === '') ? '' : (value < 0.00001) ? 0 : value;
2384 return element;
2401 return element;
2385 };
2402 };
2386 }
2403 }
2387
2404
2388 else if (Prototype.Browser.WebKit) {
2405 else if (Prototype.Browser.WebKit) {
2389 Element.Methods.setOpacity = function(element, value) {
2406 Element.Methods.setOpacity = function(element, value) {
2390 element = $(element);
2407 element = $(element);
2391 element.style.opacity = (value == 1 || value === '') ? '' :
2408 element.style.opacity = (value == 1 || value === '') ? '' :
2392 (value < 0.00001) ? 0 : value;
2409 (value < 0.00001) ? 0 : value;
2393
2410
2394 if (value == 1)
2411 if (value == 1)
2395 - if(element.tagName == 'IMG' && element.width) {
2412 + if(element.tagName.toUpperCase() == 'IMG' && element.width) {
2396 element.width++; element.width--;
2413 element.width++; element.width--;
2397 } else try {
2414 } else try {
2398 var n = document.createTextNode(' ');
2415 var n = document.createTextNode(' ');
2399 element.appendChild(n);
2416 element.appendChild(n);
2400 element.removeChild(n);
2417 element.removeChild(n);
2401 } catch (e) { }
2418 } catch (e) { }
2402
2419
2403 return element;
2420 return element;
2404 };
2421 };
2405
2422
2406 // Safari returns margins on body which is incorrect if the child is absolutely
2423 // Safari returns margins on body which is incorrect if the child is absolutely
2407 // positioned. For performance reasons, redefine Element#cumulativeOffset for
2424 // positioned. For performance reasons, redefine Element#cumulativeOffset for
2408 // KHTML/WebKit only.
2425 // KHTML/WebKit only.
2409 Element.Methods.cumulativeOffset = function(element) {
2426 Element.Methods.cumulativeOffset = function(element) {
2410 var valueT = 0, valueL = 0;
2427 var valueT = 0, valueL = 0;
2411 do {
2428 do {
2412 valueT += element.offsetTop || 0;
2429 valueT += element.offsetTop || 0;
2413 valueL += element.offsetLeft || 0;
2430 valueL += element.offsetLeft || 0;
2414 if (element.offsetParent == document.body)
2431 if (element.offsetParent == document.body)
2415 if (Element.getStyle(element, 'position') == 'absolute') break;
2432 if (Element.getStyle(element, 'position') == 'absolute') break;
2416
2433
2417 element = element.offsetParent;
2434 element = element.offsetParent;
2418 } while (element);
2435 } while (element);
2419
2436
2420 return Element._returnOffset(valueL, valueT);
2437 return Element._returnOffset(valueL, valueT);
2421 };
2438 };
2422 }
2439 }
2423
2440
2424 if (Prototype.Browser.IE || Prototype.Browser.Opera) {
2441 if (Prototype.Browser.IE || Prototype.Browser.Opera) {
2425 // IE and Opera are missing .innerHTML support for TABLE-related and SELECT elements
2442 // IE and Opera are missing .innerHTML support for TABLE-related and SELECT elements
2426 Element.Methods.update = function(element, content) {
2443 Element.Methods.update = function(element, content) {
2427 element = $(element);
2444 element = $(element);
2428
2445
2429 if (content && content.toElement) content = content.toElement();
2446 if (content && content.toElement) content = content.toElement();
2430 if (Object.isElement(content)) return element.update().insert(content);
2447 if (Object.isElement(content)) return element.update().insert(content);
2431
2448
2432 content = Object.toHTML(content);
2449 content = Object.toHTML(content);
2433 var tagName = element.tagName.toUpperCase();
2450 var tagName = element.tagName.toUpperCase();
2434
2451
2435 if (tagName in Element._insertionTranslations.tags) {
2452 if (tagName in Element._insertionTranslations.tags) {
2436 $A(element.childNodes).each(function(node) { element.removeChild(node) });
2453 $A(element.childNodes).each(function(node) { element.removeChild(node) });
2437 Element._getContentFromAnonymousElement(tagName, content.stripScripts())
2454 Element._getContentFromAnonymousElement(tagName, content.stripScripts())
2438 .each(function(node) { element.appendChild(node) });
2455 .each(function(node) { element.appendChild(node) });
2439 }
2456 }
2440 else element.innerHTML = content.stripScripts();
2457 else element.innerHTML = content.stripScripts();
2441
2458
2442 content.evalScripts.bind(content).defer();
2459 content.evalScripts.bind(content).defer();
2443 return element;
2460 return element;
2444 };
2461 };
2445 }
2462 }
2446
2463
2447 - if (document.createElement('div').outerHTML) {
2464 + if ('outerHTML' in document.createElement('div')) {
2448 Element.Methods.replace = function(element, content) {
2465 Element.Methods.replace = function(element, content) {
2449 element = $(element);
2466 element = $(element);
2450
2467
2451 if (content && content.toElement) content = content.toElement();
2468 if (content && content.toElement) content = content.toElement();
2452 if (Object.isElement(content)) {
2469 if (Object.isElement(content)) {
2453 element.parentNode.replaceChild(content, element);
2470 element.parentNode.replaceChild(content, element);
2454 return element;
2471 return element;
2455 }
2472 }
2456
2473
2457 content = Object.toHTML(content);
2474 content = Object.toHTML(content);
2458 var parent = element.parentNode, tagName = parent.tagName.toUpperCase();
2475 var parent = element.parentNode, tagName = parent.tagName.toUpperCase();
2459
2476
2460 if (Element._insertionTranslations.tags[tagName]) {
2477 if (Element._insertionTranslations.tags[tagName]) {
2461 var nextSibling = element.next();
2478 var nextSibling = element.next();
2462 var fragments = Element._getContentFromAnonymousElement(tagName, content.stripScripts());
2479 var fragments = Element._getContentFromAnonymousElement(tagName, content.stripScripts());
2463 parent.removeChild(element);
2480 parent.removeChild(element);
2464 if (nextSibling)
2481 if (nextSibling)
2465 fragments.each(function(node) { parent.insertBefore(node, nextSibling) });
2482 fragments.each(function(node) { parent.insertBefore(node, nextSibling) });
2466 else
2483 else
2467 fragments.each(function(node) { parent.appendChild(node) });
2484 fragments.each(function(node) { parent.appendChild(node) });
2468 }
2485 }
2469 else element.outerHTML = content.stripScripts();
2486 else element.outerHTML = content.stripScripts();
2470
2487
2471 content.evalScripts.bind(content).defer();
2488 content.evalScripts.bind(content).defer();
2472 return element;
2489 return element;
2473 };
2490 };
2474 }
2491 }
2475
2492
2476 Element._returnOffset = function(l, t) {
2493 Element._returnOffset = function(l, t) {
2477 var result = [l, t];
2494 var result = [l, t];
2478 result.left = l;
2495 result.left = l;
2479 result.top = t;
2496 result.top = t;
2480 return result;
2497 return result;
2481 };
2498 };
2482
2499
2483 Element._getContentFromAnonymousElement = function(tagName, html) {
2500 Element._getContentFromAnonymousElement = function(tagName, html) {
2484 var div = new Element('div'), t = Element._insertionTranslations.tags[tagName];
2501 var div = new Element('div'), t = Element._insertionTranslations.tags[tagName];
2502 + if (t) {
2485 div.innerHTML = t[0] + html + t[1];
2503 div.innerHTML = t[0] + html + t[1];
2486 t[2].times(function() { div = div.firstChild });
2504 t[2].times(function() { div = div.firstChild });
2505 + } else div.innerHTML = html;
2487 return $A(div.childNodes);
2506 return $A(div.childNodes);
2488 };
2507 };
2489
2508
2490 Element._insertionTranslations = {
2509 Element._insertionTranslations = {
2491 - before: {
2510 + before: function(element, node) {
2492 - adjacency: 'beforeBegin',
2493 - insert: function(element, node) {
2494 element.parentNode.insertBefore(node, element);
2511 element.parentNode.insertBefore(node, element);
2495 },
2512 },
2496 - initializeRange: function(element, range) {
2513 + top: function(element, node) {
2497 - range.setStartBefore(element);
2498 - }
2499 - },
2500 - top: {
2501 - adjacency: 'afterBegin',
2502 - insert: function(element, node) {
2503 element.insertBefore(node, element.firstChild);
2514 element.insertBefore(node, element.firstChild);
2504 },
2515 },
2505 - initializeRange: function(element, range) {
2516 + bottom: function(element, node) {
2506 - range.selectNodeContents(element);
2507 - range.collapse(true);
2508 - }
2509 - },
2510 - bottom: {
2511 - adjacency: 'beforeEnd',
2512 - insert: function(element, node) {
2513 element.appendChild(node);
2517 element.appendChild(node);
2514 - }
2518 + },
2515 - },
2519 + after: function(element, node) {
2516 - after: {
2517 - adjacency: 'afterEnd',
2518 - insert: function(element, node) {
2519 element.parentNode.insertBefore(node, element.nextSibling);
2520 element.parentNode.insertBefore(node, element.nextSibling);
2520 },
2521 },
2521 - initializeRange: function(element, range) {
2522 - range.setStartAfter(element);
2523 - }
2524 - },
2525 tags: {
2522 tags: {
2526 TABLE: ['<table>', '</table>', 1],
2523 TABLE: ['<table>', '</table>', 1],
2527 TBODY: ['<table><tbody>', '</tbody></table>', 2],
2524 TBODY: ['<table><tbody>', '</tbody></table>', 2],
2528 TR: ['<table><tbody><tr>', '</tr></tbody></table>', 3],
2525 TR: ['<table><tbody><tr>', '</tr></tbody></table>', 3],
2529 TD: ['<table><tbody><tr><td>', '</td></tr></tbody></table>', 4],
2526 TD: ['<table><tbody><tr><td>', '</td></tr></tbody></table>', 4],
2530 SELECT: ['<select>', '</select>', 1]
2527 SELECT: ['<select>', '</select>', 1]
2531 }
2528 }
2532 };
2529 };
2533
2530
2534 (function() {
2531 (function() {
2535 - this.bottom.initializeRange = this.top.initializeRange;
2536 Object.extend(this.tags, {
2532 Object.extend(this.tags, {
2537 THEAD: this.tags.TBODY,
2533 THEAD: this.tags.TBODY,
2538 TFOOT: this.tags.TBODY,
2534 TFOOT: this.tags.TBODY,
2539 TH: this.tags.TD
2535 TH: this.tags.TD
2540 });
2536 });
2541 }).call(Element._insertionTranslations);
2537 }).call(Element._insertionTranslations);
2542
2538
2543 Element.Methods.Simulated = {
2539 Element.Methods.Simulated = {
2544 hasAttribute: function(element, attribute) {
2540 hasAttribute: function(element, attribute) {
2545 attribute = Element._attributeTranslations.has[attribute] || attribute;
2541 attribute = Element._attributeTranslations.has[attribute] || attribute;
2546 var node = $(element).getAttributeNode(attribute);
2542 var node = $(element).getAttributeNode(attribute);
2547 - return node && node.specified;
2543 + return !!(node && node.specified);
2548 }
2544 }
2549 };
2545 };
2550
2546
2551 Element.Methods.ByTag = { };
2547 Element.Methods.ByTag = { };
2552
2548
2553 Object.extend(Element, Element.Methods);
2549 Object.extend(Element, Element.Methods);
2554
2550
2555 if (!Prototype.BrowserFeatures.ElementExtensions &&
2551 if (!Prototype.BrowserFeatures.ElementExtensions &&
2556 - document.createElement('div').__proto__) {
2552 + document.createElement('div')['__proto__']) {
2557 window.HTMLElement = { };
2553 window.HTMLElement = { };
2558 - window.HTMLElement.prototype = document.createElement('div').__proto__;
2554 + window.HTMLElement.prototype = document.createElement('div')['__proto__'];
2559 Prototype.BrowserFeatures.ElementExtensions = true;
2555 Prototype.BrowserFeatures.ElementExtensions = true;
2560 }
2556 }
2561
2557
2562 Element.extend = (function() {
2558 Element.extend = (function() {
2563 if (Prototype.BrowserFeatures.SpecificElementExtensions)
2559 if (Prototype.BrowserFeatures.SpecificElementExtensions)
2564 return Prototype.K;
2560 return Prototype.K;
2565
2561
2566 var Methods = { }, ByTag = Element.Methods.ByTag;
2562 var Methods = { }, ByTag = Element.Methods.ByTag;
2567
2563
2568 var extend = Object.extend(function(element) {
2564 var extend = Object.extend(function(element) {
2569 if (!element || element._extendedByPrototype ||
2565 if (!element || element._extendedByPrototype ||
2570 element.nodeType != 1 || element == window) return element;
2566 element.nodeType != 1 || element == window) return element;
2571
2567
2572 var methods = Object.clone(Methods),
2568 var methods = Object.clone(Methods),
2573 - tagName = element.tagName, property, value;
2569 + tagName = element.tagName.toUpperCase(), property, value;
2574
2570
2575 // extend methods for specific tags
2571 // extend methods for specific tags
2576 if (ByTag[tagName]) Object.extend(methods, ByTag[tagName]);
2572 if (ByTag[tagName]) Object.extend(methods, ByTag[tagName]);
2577
2573
2578 for (property in methods) {
2574 for (property in methods) {
2579 value = methods[property];
2575 value = methods[property];
2580 if (Object.isFunction(value) && !(property in element))
2576 if (Object.isFunction(value) && !(property in element))
2581 element[property] = value.methodize();
2577 element[property] = value.methodize();
2582 }
2578 }
2583
2579
2584 element._extendedByPrototype = Prototype.emptyFunction;
2580 element._extendedByPrototype = Prototype.emptyFunction;
2585 return element;
2581 return element;
2586
2582
2587 }, {
2583 }, {
2588 refresh: function() {
2584 refresh: function() {
2589 // extend methods for all tags (Safari doesn't need this)
2585 // extend methods for all tags (Safari doesn't need this)
2590 if (!Prototype.BrowserFeatures.ElementExtensions) {
2586 if (!Prototype.BrowserFeatures.ElementExtensions) {
2591 Object.extend(Methods, Element.Methods);
2587 Object.extend(Methods, Element.Methods);
2592 Object.extend(Methods, Element.Methods.Simulated);
2588 Object.extend(Methods, Element.Methods.Simulated);
2593 }
2589 }
2594 }
2590 }
2595 });
2591 });
2596
2592
2597 extend.refresh();
2593 extend.refresh();
2598 return extend;
2594 return extend;
2599 })();
2595 })();
2600
2596
2601 Element.hasAttribute = function(element, attribute) {
2597 Element.hasAttribute = function(element, attribute) {
2602 if (element.hasAttribute) return element.hasAttribute(attribute);
2598 if (element.hasAttribute) return element.hasAttribute(attribute);
2603 return Element.Methods.Simulated.hasAttribute(element, attribute);
2599 return Element.Methods.Simulated.hasAttribute(element, attribute);
2604 };
2600 };
2605
2601
2606 Element.addMethods = function(methods) {
2602 Element.addMethods = function(methods) {
2607 var F = Prototype.BrowserFeatures, T = Element.Methods.ByTag;
2603 var F = Prototype.BrowserFeatures, T = Element.Methods.ByTag;
2608
2604
2609 if (!methods) {
2605 if (!methods) {
2610 Object.extend(Form, Form.Methods);
2606 Object.extend(Form, Form.Methods);
2611 Object.extend(Form.Element, Form.Element.Methods);
2607 Object.extend(Form.Element, Form.Element.Methods);
2612 Object.extend(Element.Methods.ByTag, {
2608 Object.extend(Element.Methods.ByTag, {
2613 "FORM": Object.clone(Form.Methods),
2609 "FORM": Object.clone(Form.Methods),
2614 "INPUT": Object.clone(Form.Element.Methods),
2610 "INPUT": Object.clone(Form.Element.Methods),
2615 "SELECT": Object.clone(Form.Element.Methods),
2611 "SELECT": Object.clone(Form.Element.Methods),
2616 "TEXTAREA": Object.clone(Form.Element.Methods)
2612 "TEXTAREA": Object.clone(Form.Element.Methods)
2617 });
2613 });
2618 }
2614 }
2619
2615
2620 if (arguments.length == 2) {
2616 if (arguments.length == 2) {
2621 var tagName = methods;
2617 var tagName = methods;
2622 methods = arguments[1];
2618 methods = arguments[1];
2623 }
2619 }
2624
2620
2625 if (!tagName) Object.extend(Element.Methods, methods || { });
2621 if (!tagName) Object.extend(Element.Methods, methods || { });
2626 else {
2622 else {
2627 if (Object.isArray(tagName)) tagName.each(extend);
2623 if (Object.isArray(tagName)) tagName.each(extend);
2628 else extend(tagName);
2624 else extend(tagName);
2629 }
2625 }
2630
2626
2631 function extend(tagName) {
2627 function extend(tagName) {
2632 tagName = tagName.toUpperCase();
2628 tagName = tagName.toUpperCase();
2633 if (!Element.Methods.ByTag[tagName])
2629 if (!Element.Methods.ByTag[tagName])
2634 Element.Methods.ByTag[tagName] = { };
2630 Element.Methods.ByTag[tagName] = { };
2635 Object.extend(Element.Methods.ByTag[tagName], methods);
2631 Object.extend(Element.Methods.ByTag[tagName], methods);
2636 }
2632 }
2637
2633
2638 function copy(methods, destination, onlyIfAbsent) {
2634 function copy(methods, destination, onlyIfAbsent) {
2639 onlyIfAbsent = onlyIfAbsent || false;
2635 onlyIfAbsent = onlyIfAbsent || false;
2640 for (var property in methods) {
2636 for (var property in methods) {
2641 var value = methods[property];
2637 var value = methods[property];
2642 if (!Object.isFunction(value)) continue;
2638 if (!Object.isFunction(value)) continue;
2643 if (!onlyIfAbsent || !(property in destination))
2639 if (!onlyIfAbsent || !(property in destination))
2644 destination[property] = value.methodize();
2640 destination[property] = value.methodize();
2645 }
2641 }
2646 }
2642 }
2647
2643
2648 function findDOMClass(tagName) {
2644 function findDOMClass(tagName) {
2649 var klass;
2645 var klass;
2650 var trans = {
2646 var trans = {
2651 "OPTGROUP": "OptGroup", "TEXTAREA": "TextArea", "P": "Paragraph",
2647 "OPTGROUP": "OptGroup", "TEXTAREA": "TextArea", "P": "Paragraph",
2652 "FIELDSET": "FieldSet", "UL": "UList", "OL": "OList", "DL": "DList",
2648 "FIELDSET": "FieldSet", "UL": "UList", "OL": "OList", "DL": "DList",
2653 "DIR": "Directory", "H1": "Heading", "H2": "Heading", "H3": "Heading",
2649 "DIR": "Directory", "H1": "Heading", "H2": "Heading", "H3": "Heading",
2654 "H4": "Heading", "H5": "Heading", "H6": "Heading", "Q": "Quote",
2650 "H4": "Heading", "H5": "Heading", "H6": "Heading", "Q": "Quote",
2655 "INS": "Mod", "DEL": "Mod", "A": "Anchor", "IMG": "Image", "CAPTION":
2651 "INS": "Mod", "DEL": "Mod", "A": "Anchor", "IMG": "Image", "CAPTION":
2656 "TableCaption", "COL": "TableCol", "COLGROUP": "TableCol", "THEAD":
2652 "TableCaption", "COL": "TableCol", "COLGROUP": "TableCol", "THEAD":
2657 "TableSection", "TFOOT": "TableSection", "TBODY": "TableSection", "TR":
2653 "TableSection", "TFOOT": "TableSection", "TBODY": "TableSection", "TR":
2658 "TableRow", "TH": "TableCell", "TD": "TableCell", "FRAMESET":
2654 "TableRow", "TH": "TableCell", "TD": "TableCell", "FRAMESET":
2659 "FrameSet", "IFRAME": "IFrame"
2655 "FrameSet", "IFRAME": "IFrame"
2660 };
2656 };
2661 if (trans[tagName]) klass = 'HTML' + trans[tagName] + 'Element';
2657 if (trans[tagName]) klass = 'HTML' + trans[tagName] + 'Element';
2662 if (window[klass]) return window[klass];
2658 if (window[klass]) return window[klass];
2663 klass = 'HTML' + tagName + 'Element';
2659 klass = 'HTML' + tagName + 'Element';
2664 if (window[klass]) return window[klass];
2660 if (window[klass]) return window[klass];
2665 klass = 'HTML' + tagName.capitalize() + 'Element';
2661 klass = 'HTML' + tagName.capitalize() + 'Element';
2666 if (window[klass]) return window[klass];
2662 if (window[klass]) return window[klass];
2667
2663
2668 window[klass] = { };
2664 window[klass] = { };
2669 - window[klass].prototype = document.createElement(tagName).__proto__;
2665 + window[klass].prototype = document.createElement(tagName)['__proto__'];
2670 return window[klass];
2666 return window[klass];
2671 }
2667 }
2672
2668
2673 if (F.ElementExtensions) {
2669 if (F.ElementExtensions) {
2674 copy(Element.Methods, HTMLElement.prototype);
2670 copy(Element.Methods, HTMLElement.prototype);
2675 copy(Element.Methods.Simulated, HTMLElement.prototype, true);
2671 copy(Element.Methods.Simulated, HTMLElement.prototype, true);
2676 }
2672 }
2677
2673
2678 if (F.SpecificElementExtensions) {
2674 if (F.SpecificElementExtensions) {
2679 for (var tag in Element.Methods.ByTag) {
2675 for (var tag in Element.Methods.ByTag) {
2680 var klass = findDOMClass(tag);
2676 var klass = findDOMClass(tag);
2681 if (Object.isUndefined(klass)) continue;
2677 if (Object.isUndefined(klass)) continue;
2682 copy(T[tag], klass.prototype);
2678 copy(T[tag], klass.prototype);
2683 }
2679 }
2684 }
2680 }
2685
2681
2686 Object.extend(Element, Element.Methods);
2682 Object.extend(Element, Element.Methods);
2687 delete Element.ByTag;
2683 delete Element.ByTag;
2688
2684
2689 if (Element.extend.refresh) Element.extend.refresh();
2685 if (Element.extend.refresh) Element.extend.refresh();
2690 Element.cache = { };
2686 Element.cache = { };
2691 };
2687 };
2692
2688
2693 document.viewport = {
2689 document.viewport = {
2694 getDimensions: function() {
2690 getDimensions: function() {
2695 - var dimensions = { };
2691 + var dimensions = { }, B = Prototype.Browser;
2696 - var B = Prototype.Browser;
2697 $w('width height').each(function(d) {
2692 $w('width height').each(function(d) {
2698 var D = d.capitalize();
2693 var D = d.capitalize();
2699 - dimensions[d] = (B.WebKit && !document.evaluate) ? self['inner' + D] :
2694 + if (B.WebKit && !document.evaluate) {
2700 - (B.Opera) ? document.body['client' + D] : document.documentElement['client' + D];
2695 + // Safari <3.0 needs self.innerWidth/Height
2696 + dimensions[d] = self['inner' + D];
2697 + } else if (B.Opera && parseFloat(window.opera.version()) < 9.5) {
2698 + // Opera <9.5 needs document.body.clientWidth/Height
2699 + dimensions[d] = document.body['client' + D]
2700 + } else {
2701 + dimensions[d] = document.documentElement['client' + D];
2702 + }
2701 });
2703 });
2702 return dimensions;
2704 return dimensions;
2703 },
2705 },
2704
2706
2705 getWidth: function() {
2707 getWidth: function() {
2706 return this.getDimensions().width;
2708 return this.getDimensions().width;
2707 },
2709 },
2708
2710
2709 getHeight: function() {
2711 getHeight: function() {
2710 return this.getDimensions().height;
2712 return this.getDimensions().height;
2711 },
2713 },
2712
2714
2713 getScrollOffsets: function() {
2715 getScrollOffsets: function() {
2714 return Element._returnOffset(
2716 return Element._returnOffset(
2715 window.pageXOffset || document.documentElement.scrollLeft || document.body.scrollLeft,
2717 window.pageXOffset || document.documentElement.scrollLeft || document.body.scrollLeft,
2716 window.pageYOffset || document.documentElement.scrollTop || document.body.scrollTop);
2718 window.pageYOffset || document.documentElement.scrollTop || document.body.scrollTop);
2717 }
2719 }
2718 };
2720 };
2719 - /* Portions of the Selector class are derived from Jack Slocum’s DomQuery,
2721 + /* Portions of the Selector class are derived from Jack Slocum's DomQuery,
2720 * part of YUI-Ext version 0.40, distributed under the terms of an MIT-style
2722 * part of YUI-Ext version 0.40, distributed under the terms of an MIT-style
2721 * license. Please see http://www.yui-ext.com/ for more information. */
2723 * license. Please see http://www.yui-ext.com/ for more information. */
2722
2724
2723 var Selector = Class.create({
2725 var Selector = Class.create({
2724 initialize: function(expression) {
2726 initialize: function(expression) {
2725 this.expression = expression.strip();
2727 this.expression = expression.strip();
2728 +
2729 + if (this.shouldUseSelectorsAPI()) {
2730 + this.mode = 'selectorsAPI';
2731 + } else if (this.shouldUseXPath()) {
2732 + this.mode = 'xpath';
2733 + this.compileXPathMatcher();
2734 + } else {
2735 + this.mode = "normal";
2726 this.compileMatcher();
2736 this.compileMatcher();
2737 + }
2738 +
2727 },
2739 },
2728
2740
2729 shouldUseXPath: function() {
2741 shouldUseXPath: function() {
2730 if (!Prototype.BrowserFeatures.XPath) return false;
2742 if (!Prototype.BrowserFeatures.XPath) return false;
2731
2743
2732 var e = this.expression;
2744 var e = this.expression;
2733
2745
2734 // Safari 3 chokes on :*-of-type and :empty
2746 // Safari 3 chokes on :*-of-type and :empty
2735 if (Prototype.Browser.WebKit &&
2747 if (Prototype.Browser.WebKit &&
2736 (e.include("-of-type") || e.include(":empty")))
2748 (e.include("-of-type") || e.include(":empty")))
2737 return false;
2749 return false;
2738
2750
2739 // XPath can't do namespaced attributes, nor can it read
2751 // XPath can't do namespaced attributes, nor can it read
2740 // the "checked" property from DOM nodes
2752 // the "checked" property from DOM nodes
2741 - if ((/(\[[\w-]*?:|:checked)/).test(this.expression))
2753 + if ((/(\[[\w-]*?:|:checked)/).test(e))
2742 return false;
2754 return false;
2743
2755
2744 return true;
2756 return true;
2745 },
2757 },
2746
2758
2759 + shouldUseSelectorsAPI: function() {
2760 + if (!Prototype.BrowserFeatures.SelectorsAPI) return false;
2761 +
2762 + if (!Selector._div) Selector._div = new Element('div');
2763 +
2764 + // Make sure the browser treats the selector as valid. Test on an
2765 + // isolated element to minimize cost of this check.
2766 + try {
2767 + Selector._div.querySelector(this.expression);
2768 + } catch(e) {
2769 + return false;
2770 + }
2771 +
2772 + return true;
2773 + },
2774 +
2747 compileMatcher: function() {
2775 compileMatcher: function() {
2748 - if (this.shouldUseXPath())
2749 - return this.compileXPathMatcher();
2750 -
2751 var e = this.expression, ps = Selector.patterns, h = Selector.handlers,
2776 var e = this.expression, ps = Selector.patterns, h = Selector.handlers,
2752 c = Selector.criteria, le, p, m;
2777 c = Selector.criteria, le, p, m;
2753
2778
2754 if (Selector._cache[e]) {
2779 if (Selector._cache[e]) {
2755 this.matcher = Selector._cache[e];
2780 this.matcher = Selector._cache[e];
2756 return;
2781 return;
2757 }
2782 }
2758
2783
2759 this.matcher = ["this.matcher = function(root) {",
2784 this.matcher = ["this.matcher = function(root) {",
2760 "var r = root, h = Selector.handlers, c = false, n;"];
2785 "var r = root, h = Selector.handlers, c = false, n;"];
2761
2786
2762 while (e && le != e && (/\S/).test(e)) {
2787 while (e && le != e && (/\S/).test(e)) {
2763 le = e;
2788 le = e;
2764 for (var i in ps) {
2789 for (var i in ps) {
2765 p = ps[i];
2790 p = ps[i];
2766 if (m = e.match(p)) {
2791 if (m = e.match(p)) {
2767 this.matcher.push(Object.isFunction(c[i]) ? c[i](m) :
2792 this.matcher.push(Object.isFunction(c[i]) ? c[i](m) :
2768 new Template(c[i]).evaluate(m));
2793 new Template(c[i]).evaluate(m));
2769 e = e.replace(m[0], '');
2794 e = e.replace(m[0], '');
2770 break;
2795 break;
2771 }
2796 }
2772 }
2797 }
2773 }
2798 }
2774
2799
2775 this.matcher.push("return h.unique(n);\n}");
2800 this.matcher.push("return h.unique(n);\n}");
2776 eval(this.matcher.join('\n'));
2801 eval(this.matcher.join('\n'));
2777 Selector._cache[this.expression] = this.matcher;
2802 Selector._cache[this.expression] = this.matcher;
2778 },
2803 },
2779
2804
2780 compileXPathMatcher: function() {
2805 compileXPathMatcher: function() {
2781 var e = this.expression, ps = Selector.patterns,
2806 var e = this.expression, ps = Selector.patterns,
2782 x = Selector.xpath, le, m;
2807 x = Selector.xpath, le, m;
2783
2808
2784 if (Selector._cache[e]) {
2809 if (Selector._cache[e]) {
2785 this.xpath = Selector._cache[e]; return;
2810 this.xpath = Selector._cache[e]; return;
2786 }
2811 }
2787
2812
2788 this.matcher = ['.//*'];
2813 this.matcher = ['.//*'];
2789 while (e && le != e && (/\S/).test(e)) {
2814 while (e && le != e && (/\S/).test(e)) {
2790 le = e;
2815 le = e;
2791 for (var i in ps) {
2816 for (var i in ps) {
2792 if (m = e.match(ps[i])) {
2817 if (m = e.match(ps[i])) {
2793 this.matcher.push(Object.isFunction(x[i]) ? x[i](m) :
2818 this.matcher.push(Object.isFunction(x[i]) ? x[i](m) :
2794 new Template(x[i]).evaluate(m));
2819 new Template(x[i]).evaluate(m));
2795 e = e.replace(m[0], '');
2820 e = e.replace(m[0], '');
2796 break;
2821 break;
2797 }
2822 }
2798 }
2823 }
2799 }
2824 }
2800
2825
2801 this.xpath = this.matcher.join('');
2826 this.xpath = this.matcher.join('');
2802 Selector._cache[this.expression] = this.xpath;
2827 Selector._cache[this.expression] = this.xpath;
2803 },
2828 },
2804
2829
2805 findElements: function(root) {
2830 findElements: function(root) {
2806 root = root || document;
2831 root = root || document;
2807 - if (this.xpath) return document._getElementsByXPath(this.xpath, root);
2832 + var e = this.expression, results;
2833 +
2834 + switch (this.mode) {
2835 + case 'selectorsAPI':
2836 + // querySelectorAll queries document-wide, then filters to descendants
2837 + // of the context element. That's not what we want.
2838 + // Add an explicit context to the selector if necessary.
2839 + if (root !== document) {
2840 + var oldId = root.id, id = $(root).identify();
2841 + e = "#" + id + " " + e;
2842 + }
2843 +
2844 + results = $A(root.querySelectorAll(e)).map(Element.extend);
2845 + root.id = oldId;
2846 +
2847 + return results;
2848 + case 'xpath':
2849 + return document._getElementsByXPath(this.xpath, root);
2850 + default:
2808 return this.matcher(root);
2851 return this.matcher(root);
2852 + }
2809 },
2853 },
2810
2854
2811 match: function(element) {
2855 match: function(element) {
2812 this.tokens = [];
2856 this.tokens = [];
2813
2857
2814 var e = this.expression, ps = Selector.patterns, as = Selector.assertions;
2858 var e = this.expression, ps = Selector.patterns, as = Selector.assertions;
2815 var le, p, m;
2859 var le, p, m;
2816
2860
2817 while (e && le !== e && (/\S/).test(e)) {
2861 while (e && le !== e && (/\S/).test(e)) {
2818 le = e;
2862 le = e;
2819 for (var i in ps) {
2863 for (var i in ps) {
2820 p = ps[i];
2864 p = ps[i];
2821 if (m = e.match(p)) {
2865 if (m = e.match(p)) {
2822 // use the Selector.assertions methods unless the selector
2866 // use the Selector.assertions methods unless the selector
2823 // is too complex.
2867 // is too complex.
2824 if (as[i]) {
2868 if (as[i]) {
2825 this.tokens.push([i, Object.clone(m)]);
2869 this.tokens.push([i, Object.clone(m)]);
2826 e = e.replace(m[0], '');
2870 e = e.replace(m[0], '');
2827 } else {
2871 } else {
2828 // reluctantly do a document-wide search
2872 // reluctantly do a document-wide search
2829 // and look for a match in the array
2873 // and look for a match in the array
2830 return this.findElements(document).include(element);
2874 return this.findElements(document).include(element);
2831 }
2875 }
2832 }
2876 }
2833 }
2877 }
2834 }
2878 }
2835
2879
2836 var match = true, name, matches;
2880 var match = true, name, matches;
2837 for (var i = 0, token; token = this.tokens[i]; i++) {
2881 for (var i = 0, token; token = this.tokens[i]; i++) {
2838 name = token[0], matches = token[1];
2882 name = token[0], matches = token[1];
2839 if (!Selector.assertions[name](element, matches)) {
2883 if (!Selector.assertions[name](element, matches)) {
2840 match = false; break;
2884 match = false; break;
2841 }
2885 }
2842 }
2886 }
2843
2887
2844 return match;
2888 return match;
2845 },
2889 },
2846
2890
2847 toString: function() {
2891 toString: function() {
2848 return this.expression;
2892 return this.expression;
2849 },
2893 },
2850
2894
2851 inspect: function() {
2895 inspect: function() {
2852 return "#<Selector:" + this.expression.inspect() + ">";
2896 return "#<Selector:" + this.expression.inspect() + ">";
2853 }
2897 }
2854 });
2898 });
2855
2899
2856 Object.extend(Selector, {
2900 Object.extend(Selector, {
2857 _cache: { },
2901 _cache: { },
2858
2902
2859 xpath: {
2903 xpath: {
2860 descendant: "//*",
2904 descendant: "//*",
2861 child: "/*",
2905 child: "/*",
2862 adjacent: "/following-sibling::*[1]",
2906 adjacent: "/following-sibling::*[1]",
2863 laterSibling: '/following-sibling::*',
2907 laterSibling: '/following-sibling::*',
2864 tagName: function(m) {
2908 tagName: function(m) {
2865 if (m[1] == '*') return '';
2909 if (m[1] == '*') return '';
2866 return "[local-name()='" + m[1].toLowerCase() +
2910 return "[local-name()='" + m[1].toLowerCase() +
2867 "' or local-name()='" + m[1].toUpperCase() + "']";
2911 "' or local-name()='" + m[1].toUpperCase() + "']";
2868 },
2912 },
2869 className: "[contains(concat(' ', @class, ' '), ' #{1} ')]",
2913 className: "[contains(concat(' ', @class, ' '), ' #{1} ')]",
2870 id: "[@id='#{1}']",
2914 id: "[@id='#{1}']",
2871 attrPresence: function(m) {
2915 attrPresence: function(m) {
2872 m[1] = m[1].toLowerCase();
2916 m[1] = m[1].toLowerCase();
2873 return new Template("[@#{1}]").evaluate(m);
2917 return new Template("[@#{1}]").evaluate(m);
2874 },
2918 },
2875 attr: function(m) {
2919 attr: function(m) {
2876 m[1] = m[1].toLowerCase();
2920 m[1] = m[1].toLowerCase();
2877 m[3] = m[5] || m[6];
2921 m[3] = m[5] || m[6];
2878 return new Template(Selector.xpath.operators[m[2]]).evaluate(m);
2922 return new Template(Selector.xpath.operators[m[2]]).evaluate(m);
2879 },
2923 },
2880 pseudo: function(m) {
2924 pseudo: function(m) {
2881 var h = Selector.xpath.pseudos[m[1]];
2925 var h = Selector.xpath.pseudos[m[1]];
2882 if (!h) return '';
2926 if (!h) return '';
2883 if (Object.isFunction(h)) return h(m);
2927 if (Object.isFunction(h)) return h(m);
2884 return new Template(Selector.xpath.pseudos[m[1]]).evaluate(m);
2928 return new Template(Selector.xpath.pseudos[m[1]]).evaluate(m);
2885 },
2929 },
2886 operators: {
2930 operators: {
2887 '=': "[@#{1}='#{3}']",
2931 '=': "[@#{1}='#{3}']",
2888 '!=': "[@#{1}!='#{3}']",
2932 '!=': "[@#{1}!='#{3}']",
2889 '^=': "[starts-with(@#{1}, '#{3}')]",
2933 '^=': "[starts-with(@#{1}, '#{3}')]",
2890 '$=': "[substring(@#{1}, (string-length(@#{1}) - string-length('#{3}') + 1))='#{3}']",
2934 '$=': "[substring(@#{1}, (string-length(@#{1}) - string-length('#{3}') + 1))='#{3}']",
2891 '*=': "[contains(@#{1}, '#{3}')]",
2935 '*=': "[contains(@#{1}, '#{3}')]",
2892 '~=': "[contains(concat(' ', @#{1}, ' '), ' #{3} ')]",
2936 '~=': "[contains(concat(' ', @#{1}, ' '), ' #{3} ')]",
2893 '|=': "[contains(concat('-', @#{1}, '-'), '-#{3}-')]"
2937 '|=': "[contains(concat('-', @#{1}, '-'), '-#{3}-')]"
2894 },
2938 },
2895 pseudos: {
2939 pseudos: {
2896 'first-child': '[not(preceding-sibling::*)]',
2940 'first-child': '[not(preceding-sibling::*)]',
2897 'last-child': '[not(following-sibling::*)]',
2941 'last-child': '[not(following-sibling::*)]',
2898 'only-child': '[not(preceding-sibling::* or following-sibling::*)]',
2942 'only-child': '[not(preceding-sibling::* or following-sibling::*)]',
2899 - 'empty': "[count(*) = 0 and (count(text()) = 0 or translate(text(), ' \t\r\n', '') = '')]",
2943 + 'empty': "[count(*) = 0 and (count(text()) = 0)]",
2900 'checked': "[@checked]",
2944 'checked': "[@checked]",
2901 - 'disabled': "[@disabled]",
2945 + 'disabled': "[(@disabled) and (@type!='hidden')]",
2902 - 'enabled': "[not(@disabled)]",
2946 + 'enabled': "[not(@disabled) and (@type!='hidden')]",
2903 'not': function(m) {
2947 'not': function(m) {
2904 var e = m[6], p = Selector.patterns,
2948 var e = m[6], p = Selector.patterns,
2905 x = Selector.xpath, le, v;
2949 x = Selector.xpath, le, v;
2906
2950
2907 var exclusion = [];
2951 var exclusion = [];
2908 while (e && le != e && (/\S/).test(e)) {
2952 while (e && le != e && (/\S/).test(e)) {
2909 le = e;
2953 le = e;
2910 for (var i in p) {
2954 for (var i in p) {
2911 if (m = e.match(p[i])) {
2955 if (m = e.match(p[i])) {
2912 v = Object.isFunction(x[i]) ? x[i](m) : new Template(x[i]).evaluate(m);
2956 v = Object.isFunction(x[i]) ? x[i](m) : new Template(x[i]).evaluate(m);
2913 exclusion.push("(" + v.substring(1, v.length - 1) + ")");
2957 exclusion.push("(" + v.substring(1, v.length - 1) + ")");
2914 e = e.replace(m[0], '');
2958 e = e.replace(m[0], '');
2915 break;
2959 break;
2916 }
2960 }
2917 }
2961 }
2918 }
2962 }
2919 return "[not(" + exclusion.join(" and ") + ")]";
2963 return "[not(" + exclusion.join(" and ") + ")]";
2920 },
2964 },
2921 'nth-child': function(m) {
2965 'nth-child': function(m) {
2922 return Selector.xpath.pseudos.nth("(count(./preceding-sibling::*) + 1) ", m);
2966 return Selector.xpath.pseudos.nth("(count(./preceding-sibling::*) + 1) ", m);
2923 },
2967 },
2924 'nth-last-child': function(m) {
2968 'nth-last-child': function(m) {
2925 return Selector.xpath.pseudos.nth("(count(./following-sibling::*) + 1) ", m);
2969 return Selector.xpath.pseudos.nth("(count(./following-sibling::*) + 1) ", m);
2926 },
2970 },
2927 'nth-of-type': function(m) {
2971 'nth-of-type': function(m) {
2928 return Selector.xpath.pseudos.nth("position() ", m);
2972 return Selector.xpath.pseudos.nth("position() ", m);
2929 },
2973 },
2930 'nth-last-of-type': function(m) {
2974 'nth-last-of-type': function(m) {
2931 return Selector.xpath.pseudos.nth("(last() + 1 - position()) ", m);
2975 return Selector.xpath.pseudos.nth("(last() + 1 - position()) ", m);
2932 },
2976 },
2933 'first-of-type': function(m) {
2977 'first-of-type': function(m) {
2934 m[6] = "1"; return Selector.xpath.pseudos['nth-of-type'](m);
2978 m[6] = "1"; return Selector.xpath.pseudos['nth-of-type'](m);
2935 },
2979 },
2936 'last-of-type': function(m) {
2980 'last-of-type': function(m) {
2937 m[6] = "1"; return Selector.xpath.pseudos['nth-last-of-type'](m);
2981 m[6] = "1"; return Selector.xpath.pseudos['nth-last-of-type'](m);
2938 },
2982 },
2939 'only-of-type': function(m) {
2983 'only-of-type': function(m) {
2940 var p = Selector.xpath.pseudos; return p['first-of-type'](m) + p['last-of-type'](m);
2984 var p = Selector.xpath.pseudos; return p['first-of-type'](m) + p['last-of-type'](m);
2941 },
2985 },
2942 nth: function(fragment, m) {
2986 nth: function(fragment, m) {
2943 var mm, formula = m[6], predicate;
2987 var mm, formula = m[6], predicate;
2944 if (formula == 'even') formula = '2n+0';
2988 if (formula == 'even') formula = '2n+0';
2945 if (formula == 'odd') formula = '2n+1';
2989 if (formula == 'odd') formula = '2n+1';
2946 if (mm = formula.match(/^(\d+)$/)) // digit only
2990 if (mm = formula.match(/^(\d+)$/)) // digit only
2947 return '[' + fragment + "= " + mm[1] + ']';
2991 return '[' + fragment + "= " + mm[1] + ']';
2948 if (mm = formula.match(/^(-?\d*)?n(([+-])(\d+))?/)) { // an+b
2992 if (mm = formula.match(/^(-?\d*)?n(([+-])(\d+))?/)) { // an+b
2949 if (mm[1] == "-") mm[1] = -1;
2993 if (mm[1] == "-") mm[1] = -1;
2950 var a = mm[1] ? Number(mm[1]) : 1;
2994 var a = mm[1] ? Number(mm[1]) : 1;
2951 var b = mm[2] ? Number(mm[2]) : 0;
2995 var b = mm[2] ? Number(mm[2]) : 0;
2952 predicate = "[((#{fragment} - #{b}) mod #{a} = 0) and " +
2996 predicate = "[((#{fragment} - #{b}) mod #{a} = 0) and " +
2953 "((#{fragment} - #{b}) div #{a} >= 0)]";
2997 "((#{fragment} - #{b}) div #{a} >= 0)]";
2954 return new Template(predicate).evaluate({
2998 return new Template(predicate).evaluate({
2955 fragment: fragment, a: a, b: b });
2999 fragment: fragment, a: a, b: b });
2956 }
3000 }
2957 }
3001 }
2958 }
3002 }
2959 },
3003 },
2960
3004
2961 criteria: {
3005 criteria: {
2962 tagName: 'n = h.tagName(n, r, "#{1}", c); c = false;',
3006 tagName: 'n = h.tagName(n, r, "#{1}", c); c = false;',
2963 className: 'n = h.className(n, r, "#{1}", c); c = false;',
3007 className: 'n = h.className(n, r, "#{1}", c); c = false;',
2964 id: 'n = h.id(n, r, "#{1}", c); c = false;',
3008 id: 'n = h.id(n, r, "#{1}", c); c = false;',
2965 - attrPresence: 'n = h.attrPresence(n, r, "#{1}"); c = false;',
3009 + attrPresence: 'n = h.attrPresence(n, r, "#{1}", c); c = false;',
2966 attr: function(m) {
3010 attr: function(m) {
2967 m[3] = (m[5] || m[6]);
3011 m[3] = (m[5] || m[6]);
2968 - return new Template('n = h.attr(n, r, "#{1}", "#{3}", "#{2}"); c = false;').evaluate(m);
3012 + return new Template('n = h.attr(n, r, "#{1}", "#{3}", "#{2}", c); c = false;').evaluate(m);
2969 },
3013 },
2970 pseudo: function(m) {
3014 pseudo: function(m) {
2971 if (m[6]) m[6] = m[6].replace(/"/g, '\\"');
3015 if (m[6]) m[6] = m[6].replace(/"/g, '\\"');
2972 return new Template('n = h.pseudo(n, "#{1}", "#{6}", r, c); c = false;').evaluate(m);
3016 return new Template('n = h.pseudo(n, "#{1}", "#{6}", r, c); c = false;').evaluate(m);
2973 },
3017 },
2974 descendant: 'c = "descendant";',
3018 descendant: 'c = "descendant";',
2975 child: 'c = "child";',
3019 child: 'c = "child";',
2976 adjacent: 'c = "adjacent";',
3020 adjacent: 'c = "adjacent";',
2977 laterSibling: 'c = "laterSibling";'
3021 laterSibling: 'c = "laterSibling";'
2978 },
3022 },
2979
3023
2980 patterns: {
3024 patterns: {
2981 // combinators must be listed first
3025 // combinators must be listed first
2982 // (and descendant needs to be last combinator)
3026 // (and descendant needs to be last combinator)
2983 laterSibling: /^\s*~\s*/,
3027 laterSibling: /^\s*~\s*/,
2984 child: /^\s*>\s*/,
3028 child: /^\s*>\s*/,
2985 adjacent: /^\s*\+\s*/,
3029 adjacent: /^\s*\+\s*/,
2986 descendant: /^\s/,
3030 descendant: /^\s/,
2987
3031
2988 // selectors follow
3032 // selectors follow
2989 tagName: /^\s*(\*|[\w\-]+)(\b|$)?/,
3033 tagName: /^\s*(\*|[\w\-]+)(\b|$)?/,
2990 id: /^#([\w\-\*]+)(\b|$)/,
3034 id: /^#([\w\-\*]+)(\b|$)/,
2991 className: /^\.([\w\-\*]+)(\b|$)/,
3035 className: /^\.([\w\-\*]+)(\b|$)/,
2992 - pseudo: /^:((first|last|nth|nth-last|only)(-child|-of-type)|empty|checked|(en|dis)abled|not)(\((.*?)\))?(\b|$|(?=\s)|(?=:))/,
3036 + pseudo:
2993 - attrPresence: /^\[([\w]+)\]/,
3037 + /^:((first|last|nth|nth-last|only)(-child|-of-type)|empty|checked|(en|dis)abled|not)(\((.*?)\))?(\b|$|(?=\s|[:+~>]))/,
3038 + attrPresence: /^\[((?:[\w]+:)?[\w]+)\]/,
2994 attr: /\[((?:[\w-]*:)?[\w-]+)\s*(?:([!^$*~|]?=)\s*((['"])([^\4]*?)\4|([^'"][^\]]*?)))?\]/
3039 attr: /\[((?:[\w-]*:)?[\w-]+)\s*(?:([!^$*~|]?=)\s*((['"])([^\4]*?)\4|([^'"][^\]]*?)))?\]/
2995 },
3040 },
2996
3041
2997 // for Selector.match and Element#match
3042 // for Selector.match and Element#match
2998 assertions: {
3043 assertions: {
2999 tagName: function(element, matches) {
3044 tagName: function(element, matches) {
3000 return matches[1].toUpperCase() == element.tagName.toUpperCase();
3045 return matches[1].toUpperCase() == element.tagName.toUpperCase();
3001 },
3046 },
3002
3047
3003 className: function(element, matches) {
3048 className: function(element, matches) {
3004 return Element.hasClassName(element, matches[1]);
3049 return Element.hasClassName(element, matches[1]);
3005 },
3050 },
3006
3051
3007 id: function(element, matches) {
3052 id: function(element, matches) {
3008 return element.id === matches[1];
3053 return element.id === matches[1];
3009 },
3054 },
3010
3055
3011 attrPresence: function(element, matches) {
3056 attrPresence: function(element, matches) {
3012 return Element.hasAttribute(element, matches[1]);
3057 return Element.hasAttribute(element, matches[1]);
3013 },
3058 },
3014
3059
3015 attr: function(element, matches) {
3060 attr: function(element, matches) {
3016 var nodeValue = Element.readAttribute(element, matches[1]);
3061 var nodeValue = Element.readAttribute(element, matches[1]);
3017 - return Selector.operators[matches[2]](nodeValue, matches[3]);
3062 + return nodeValue && Selector.operators[matches[2]](nodeValue, matches[5] || matches[6]);
3018 }
3063 }
3019 },
3064 },
3020
3065
3021 handlers: {
3066 handlers: {
3022 // UTILITY FUNCTIONS
3067 // UTILITY FUNCTIONS
3023 // joins two collections
3068 // joins two collections
3024 concat: function(a, b) {
3069 concat: function(a, b) {
3025 for (var i = 0, node; node = b[i]; i++)
3070 for (var i = 0, node; node = b[i]; i++)
3026 a.push(node);
3071 a.push(node);
3027 return a;
3072 return a;
3028 },
3073 },
3029
3074
3030 // marks an array of nodes for counting
3075 // marks an array of nodes for counting
3031 mark: function(nodes) {
3076 mark: function(nodes) {
3077 + var _true = Prototype.emptyFunction;
3032 for (var i = 0, node; node = nodes[i]; i++)
3078 for (var i = 0, node; node = nodes[i]; i++)
3033 - node._counted = true;
3079 + node._countedByPrototype = _true;
3034 return nodes;
3080 return nodes;
3035 },
3081 },
3036
3082
3037 unmark: function(nodes) {
3083 unmark: function(nodes) {
3038 for (var i = 0, node; node = nodes[i]; i++)
3084 for (var i = 0, node; node = nodes[i]; i++)
3039 - node._counted = undefined;
3085 + node._countedByPrototype = undefined;
3040 return nodes;
3086 return nodes;
3041 },
3087 },
3042
3088
3043 // mark each child node with its position (for nth calls)
3089 // mark each child node with its position (for nth calls)
3044 // "ofType" flag indicates whether we're indexing for nth-of-type
3090 // "ofType" flag indicates whether we're indexing for nth-of-type
3045 // rather than nth-child
3091 // rather than nth-child
3046 index: function(parentNode, reverse, ofType) {
3092 index: function(parentNode, reverse, ofType) {
3047 - parentNode._counted = true;
3093 + parentNode._countedByPrototype = Prototype.emptyFunction;
3048 if (reverse) {
3094 if (reverse) {
3049 for (var nodes = parentNode.childNodes, i = nodes.length - 1, j = 1; i >= 0; i--) {
3095 for (var nodes = parentNode.childNodes, i = nodes.length - 1, j = 1; i >= 0; i--) {
3050 var node = nodes[i];
3096 var node = nodes[i];
3051 - if (node.nodeType == 1 && (!ofType || node._counted)) node.nodeIndex = j++;
3097 + if (node.nodeType == 1 && (!ofType || node._countedByPrototype)) node.nodeIndex = j++;
3052 }
3098 }
3053 } else {
3099 } else {
3054 for (var i = 0, j = 1, nodes = parentNode.childNodes; node = nodes[i]; i++)
3100 for (var i = 0, j = 1, nodes = parentNode.childNodes; node = nodes[i]; i++)
3055 - if (node.nodeType == 1 && (!ofType || node._counted)) node.nodeIndex = j++;
3101 + if (node.nodeType == 1 && (!ofType || node._countedByPrototype)) node.nodeIndex = j++;
3056 }
3102 }
3057 },
3103 },
3058
3104
3059 // filters out duplicates and extends all nodes
3105 // filters out duplicates and extends all nodes
3060 unique: function(nodes) {
3106 unique: function(nodes) {
3061 if (nodes.length == 0) return nodes;
3107 if (nodes.length == 0) return nodes;
3062 var results = [], n;
3108 var results = [], n;
3063 for (var i = 0, l = nodes.length; i < l; i++)
3109 for (var i = 0, l = nodes.length; i < l; i++)
3064 - if (!(n = nodes[i])._counted) {
3110 + if (!(n = nodes[i])._countedByPrototype) {
3065 - n._counted = true;
3111 + n._countedByPrototype = Prototype.emptyFunction;
3066 results.push(Element.extend(n));
3112 results.push(Element.extend(n));
3067 }
3113 }
3068 return Selector.handlers.unmark(results);
3114 return Selector.handlers.unmark(results);
3069 },
3115 },
3070
3116
3071 // COMBINATOR FUNCTIONS
3117 // COMBINATOR FUNCTIONS
3072 descendant: function(nodes) {
3118 descendant: function(nodes) {
3073 var h = Selector.handlers;
3119 var h = Selector.handlers;
3074 for (var i = 0, results = [], node; node = nodes[i]; i++)
3120 for (var i = 0, results = [], node; node = nodes[i]; i++)
3075 h.concat(results, node.getElementsByTagName('*'));
3121 h.concat(results, node.getElementsByTagName('*'));
3076 return results;
3122 return results;
3077 },
3123 },
3078
3124
3079 child: function(nodes) {
3125 child: function(nodes) {
3080 var h = Selector.handlers;
3126 var h = Selector.handlers;
3081 for (var i = 0, results = [], node; node = nodes[i]; i++) {
3127 for (var i = 0, results = [], node; node = nodes[i]; i++) {
3082 for (var j = 0, child; child = node.childNodes[j]; j++)
3128 for (var j = 0, child; child = node.childNodes[j]; j++)
3083 if (child.nodeType == 1 && child.tagName != '!') results.push(child);
3129 if (child.nodeType == 1 && child.tagName != '!') results.push(child);
3084 }
3130 }
3085 return results;
3131 return results;
3086 },
3132 },
3087
3133
3088 adjacent: function(nodes) {
3134 adjacent: function(nodes) {
3089 for (var i = 0, results = [], node; node = nodes[i]; i++) {
3135 for (var i = 0, results = [], node; node = nodes[i]; i++) {
3090 var next = this.nextElementSibling(node);
3136 var next = this.nextElementSibling(node);
3091 if (next) results.push(next);
3137 if (next) results.push(next);
3092 }
3138 }
3093 return results;
3139 return results;
3094 },
3140 },
3095
3141
3096 laterSibling: function(nodes) {
3142 laterSibling: function(nodes) {
3097 var h = Selector.handlers;
3143 var h = Selector.handlers;
3098 for (var i = 0, results = [], node; node = nodes[i]; i++)
3144 for (var i = 0, results = [], node; node = nodes[i]; i++)
3099 h.concat(results, Element.nextSiblings(node));
3145 h.concat(results, Element.nextSiblings(node));
3100 return results;
3146 return results;
3101 },
3147 },
3102
3148
3103 nextElementSibling: function(node) {
3149 nextElementSibling: function(node) {
3104 while (node = node.nextSibling)
3150 while (node = node.nextSibling)
3105 if (node.nodeType == 1) return node;
3151 if (node.nodeType == 1) return node;
3106 return null;
3152 return null;
3107 },
3153 },
3108
3154
3109 previousElementSibling: function(node) {
3155 previousElementSibling: function(node) {
3110 while (node = node.previousSibling)
3156 while (node = node.previousSibling)
3111 if (node.nodeType == 1) return node;
3157 if (node.nodeType == 1) return node;
3112 return null;
3158 return null;
3113 },
3159 },
3114
3160
3115 // TOKEN FUNCTIONS
3161 // TOKEN FUNCTIONS
3116 tagName: function(nodes, root, tagName, combinator) {
3162 tagName: function(nodes, root, tagName, combinator) {
3117 - tagName = tagName.toUpperCase();
3163 + var uTagName = tagName.toUpperCase();
3118 var results = [], h = Selector.handlers;
3164 var results = [], h = Selector.handlers;
3119 if (nodes) {
3165 if (nodes) {
3120 if (combinator) {
3166 if (combinator) {
3121 // fastlane for ordinary descendant combinators
3167 // fastlane for ordinary descendant combinators
3122 if (combinator == "descendant") {
3168 if (combinator == "descendant") {
3123 for (var i = 0, node; node = nodes[i]; i++)
3169 for (var i = 0, node; node = nodes[i]; i++)
3124 h.concat(results, node.getElementsByTagName(tagName));
3170 h.concat(results, node.getElementsByTagName(tagName));
3125 return results;
3171 return results;
3126 } else nodes = this[combinator](nodes);
3172 } else nodes = this[combinator](nodes);
3127 if (tagName == "*") return nodes;
3173 if (tagName == "*") return nodes;
3128 }
3174 }
3129 for (var i = 0, node; node = nodes[i]; i++)
3175 for (var i = 0, node; node = nodes[i]; i++)
3130 - if (node.tagName.toUpperCase() == tagName) results.push(node);
3176 + if (node.tagName.toUpperCase() === uTagName) results.push(node);
3131 return results;
3177 return results;
3132 } else return root.getElementsByTagName(tagName);
3178 } else return root.getElementsByTagName(tagName);
3133 },
3179 },
3134
3180
3135 id: function(nodes, root, id, combinator) {
3181 id: function(nodes, root, id, combinator) {
3136 var targetNode = $(id), h = Selector.handlers;
3182 var targetNode = $(id), h = Selector.handlers;
3137 if (!targetNode) return [];
3183 if (!targetNode) return [];
3138 if (!nodes && root == document) return [targetNode];
3184 if (!nodes && root == document) return [targetNode];
3139 if (nodes) {
3185 if (nodes) {
3140 if (combinator) {
3186 if (combinator) {
3141 if (combinator == 'child') {
3187 if (combinator == 'child') {
3142 for (var i = 0, node; node = nodes[i]; i++)
3188 for (var i = 0, node; node = nodes[i]; i++)
3143 if (targetNode.parentNode == node) return [targetNode];
3189 if (targetNode.parentNode == node) return [targetNode];
3144 } else if (combinator == 'descendant') {
3190 } else if (combinator == 'descendant') {
3145 for (var i = 0, node; node = nodes[i]; i++)
3191 for (var i = 0, node; node = nodes[i]; i++)
3146 if (Element.descendantOf(targetNode, node)) return [targetNode];
3192 if (Element.descendantOf(targetNode, node)) return [targetNode];
3147 } else if (combinator == 'adjacent') {
3193 } else if (combinator == 'adjacent') {
3148 for (var i = 0, node; node = nodes[i]; i++)
3194 for (var i = 0, node; node = nodes[i]; i++)
3149 if (Selector.handlers.previousElementSibling(targetNode) == node)
3195 if (Selector.handlers.previousElementSibling(targetNode) == node)
3150 return [targetNode];
3196 return [targetNode];
3151 } else nodes = h[combinator](nodes);
3197 } else nodes = h[combinator](nodes);
3152 }
3198 }
3153 for (var i = 0, node; node = nodes[i]; i++)
3199 for (var i = 0, node; node = nodes[i]; i++)
3154 if (node == targetNode) return [targetNode];
3200 if (node == targetNode) return [targetNode];
3155 return [];
3201 return [];
3156 }
3202 }
3157 return (targetNode && Element.descendantOf(targetNode, root)) ? [targetNode] : [];
3203 return (targetNode && Element.descendantOf(targetNode, root)) ? [targetNode] : [];
3158 },
3204 },
3159
3205
3160 className: function(nodes, root, className, combinator) {
3206 className: function(nodes, root, className, combinator) {
3161 if (nodes && combinator) nodes = this[combinator](nodes);
3207 if (nodes && combinator) nodes = this[combinator](nodes);
3162 return Selector.handlers.byClassName(nodes, root, className);
3208 return Selector.handlers.byClassName(nodes, root, className);
3163 },
3209 },
3164
3210
3165 byClassName: function(nodes, root, className) {
3211 byClassName: function(nodes, root, className) {
3166 if (!nodes) nodes = Selector.handlers.descendant([root]);
3212 if (!nodes) nodes = Selector.handlers.descendant([root]);
3167 var needle = ' ' + className + ' ';
3213 var needle = ' ' + className + ' ';
3168 for (var i = 0, results = [], node, nodeClassName; node = nodes[i]; i++) {
3214 for (var i = 0, results = [], node, nodeClassName; node = nodes[i]; i++) {
3169 nodeClassName = node.className;
3215 nodeClassName = node.className;
3170 if (nodeClassName.length == 0) continue;
3216 if (nodeClassName.length == 0) continue;
3171 if (nodeClassName == className || (' ' + nodeClassName + ' ').include(needle))
3217 if (nodeClassName == className || (' ' + nodeClassName + ' ').include(needle))
3172 results.push(node);
3218 results.push(node);
3173 }
3219 }
3174 return results;
3220 return results;
3175 },
3221 },
3176
3222
3177 - attrPresence: function(nodes, root, attr) {
3223 + attrPresence: function(nodes, root, attr, combinator) {
3178 if (!nodes) nodes = root.getElementsByTagName("*");
3224 if (!nodes) nodes = root.getElementsByTagName("*");
3225 + if (nodes && combinator) nodes = this[combinator](nodes);
3179 var results = [];
3226 var results = [];
3180 for (var i = 0, node; node = nodes[i]; i++)
3227 for (var i = 0, node; node = nodes[i]; i++)
3181 if (Element.hasAttribute(node, attr)) results.push(node);
3228 if (Element.hasAttribute(node, attr)) results.push(node);
3182 return results;
3229 return results;
3183 },
3230 },
3184
3231
3185 - attr: function(nodes, root, attr, value, operator) {
3232 + attr: function(nodes, root, attr, value, operator, combinator) {
3186 if (!nodes) nodes = root.getElementsByTagName("*");
3233 if (!nodes) nodes = root.getElementsByTagName("*");
3234 + if (nodes && combinator) nodes = this[combinator](nodes);
3187 var handler = Selector.operators[operator], results = [];
3235 var handler = Selector.operators[operator], results = [];
3188 for (var i = 0, node; node = nodes[i]; i++) {
3236 for (var i = 0, node; node = nodes[i]; i++) {
3189 var nodeValue = Element.readAttribute(node, attr);
3237 var nodeValue = Element.readAttribute(node, attr);
3190 if (nodeValue === null) continue;
3238 if (nodeValue === null) continue;
3191 if (handler(nodeValue, value)) results.push(node);
3239 if (handler(nodeValue, value)) results.push(node);
3192 }
3240 }
3193 return results;
3241 return results;
3194 },
3242 },
3195
3243
3196 pseudo: function(nodes, name, value, root, combinator) {
3244 pseudo: function(nodes, name, value, root, combinator) {
3197 if (nodes && combinator) nodes = this[combinator](nodes);
3245 if (nodes && combinator) nodes = this[combinator](nodes);
3198 if (!nodes) nodes = root.getElementsByTagName("*");
3246 if (!nodes) nodes = root.getElementsByTagName("*");
3199 return Selector.pseudos[name](nodes, value, root);
3247 return Selector.pseudos[name](nodes, value, root);
3200 }
3248 }
3201 },
3249 },
3202
3250
3203 pseudos: {
3251 pseudos: {
3204 'first-child': function(nodes, value, root) {
3252 'first-child': function(nodes, value, root) {
3205 for (var i = 0, results = [], node; node = nodes[i]; i++) {
3253 for (var i = 0, results = [], node; node = nodes[i]; i++) {
3206 if (Selector.handlers.previousElementSibling(node)) continue;
3254 if (Selector.handlers.previousElementSibling(node)) continue;
3207 results.push(node);
3255 results.push(node);
3208 }
3256 }
3209 return results;
3257 return results;
3210 },
3258 },
3211 'last-child': function(nodes, value, root) {
3259 'last-child': function(nodes, value, root) {
3212 for (var i = 0, results = [], node; node = nodes[i]; i++) {
3260 for (var i = 0, results = [], node; node = nodes[i]; i++) {
3213 if (Selector.handlers.nextElementSibling(node)) continue;
3261 if (Selector.handlers.nextElementSibling(node)) continue;
3214 results.push(node);
3262 results.push(node);
3215 }
3263 }
3216 return results;
3264 return results;
3217 },
3265 },
3218 'only-child': function(nodes, value, root) {
3266 'only-child': function(nodes, value, root) {
3219 var h = Selector.handlers;
3267 var h = Selector.handlers;
3220 for (var i = 0, results = [], node; node = nodes[i]; i++)
3268 for (var i = 0, results = [], node; node = nodes[i]; i++)
3221 if (!h.previousElementSibling(node) && !h.nextElementSibling(node))
3269 if (!h.previousElementSibling(node) && !h.nextElementSibling(node))
3222 results.push(node);
3270 results.push(node);
3223 return results;
3271 return results;
3224 },
3272 },
3225 'nth-child': function(nodes, formula, root) {
3273 'nth-child': function(nodes, formula, root) {
3226 return Selector.pseudos.nth(nodes, formula, root);
3274 return Selector.pseudos.nth(nodes, formula, root);
3227 },
3275 },
3228 'nth-last-child': function(nodes, formula, root) {
3276 'nth-last-child': function(nodes, formula, root) {
3229 return Selector.pseudos.nth(nodes, formula, root, true);
3277 return Selector.pseudos.nth(nodes, formula, root, true);
3230 },
3278 },
3231 'nth-of-type': function(nodes, formula, root) {
3279 'nth-of-type': function(nodes, formula, root) {
3232 return Selector.pseudos.nth(nodes, formula, root, false, true);
3280 return Selector.pseudos.nth(nodes, formula, root, false, true);
3233 },
3281 },
3234 'nth-last-of-type': function(nodes, formula, root) {
3282 'nth-last-of-type': function(nodes, formula, root) {
3235 return Selector.pseudos.nth(nodes, formula, root, true, true);
3283 return Selector.pseudos.nth(nodes, formula, root, true, true);
3236 },
3284 },
3237 'first-of-type': function(nodes, formula, root) {
3285 'first-of-type': function(nodes, formula, root) {
3238 return Selector.pseudos.nth(nodes, "1", root, false, true);
3286 return Selector.pseudos.nth(nodes, "1", root, false, true);
3239 },
3287 },
3240 'last-of-type': function(nodes, formula, root) {
3288 'last-of-type': function(nodes, formula, root) {
3241 return Selector.pseudos.nth(nodes, "1", root, true, true);
3289 return Selector.pseudos.nth(nodes, "1", root, true, true);
3242 },
3290 },
3243 'only-of-type': function(nodes, formula, root) {
3291 'only-of-type': function(nodes, formula, root) {
3244 var p = Selector.pseudos;
3292 var p = Selector.pseudos;
3245 return p['last-of-type'](p['first-of-type'](nodes, formula, root), formula, root);
3293 return p['last-of-type'](p['first-of-type'](nodes, formula, root), formula, root);
3246 },
3294 },
3247
3295
3248 // handles the an+b logic
3296 // handles the an+b logic
3249 getIndices: function(a, b, total) {
3297 getIndices: function(a, b, total) {
3250 if (a == 0) return b > 0 ? [b] : [];
3298 if (a == 0) return b > 0 ? [b] : [];
3251 return $R(1, total).inject([], function(memo, i) {
3299 return $R(1, total).inject([], function(memo, i) {
3252 if (0 == (i - b) % a && (i - b) / a >= 0) memo.push(i);
3300 if (0 == (i - b) % a && (i - b) / a >= 0) memo.push(i);
3253 return memo;
3301 return memo;
3254 });
3302 });
3255 },
3303 },
3256
3304
3257 // handles nth(-last)-child, nth(-last)-of-type, and (first|last)-of-type
3305 // handles nth(-last)-child, nth(-last)-of-type, and (first|last)-of-type
3258 nth: function(nodes, formula, root, reverse, ofType) {
3306 nth: function(nodes, formula, root, reverse, ofType) {
3259 if (nodes.length == 0) return [];
3307 if (nodes.length == 0) return [];
3260 if (formula == 'even') formula = '2n+0';
3308 if (formula == 'even') formula = '2n+0';
3261 if (formula == 'odd') formula = '2n+1';
3309 if (formula == 'odd') formula = '2n+1';
3262 var h = Selector.handlers, results = [], indexed = [], m;
3310 var h = Selector.handlers, results = [], indexed = [], m;
3263 h.mark(nodes);
3311 h.mark(nodes);
3264 for (var i = 0, node; node = nodes[i]; i++) {
3312 for (var i = 0, node; node = nodes[i]; i++) {
3265 - if (!node.parentNode._counted) {
3313 + if (!node.parentNode._countedByPrototype) {
3266 h.index(node.parentNode, reverse, ofType);
3314 h.index(node.parentNode, reverse, ofType);
3267 indexed.push(node.parentNode);
3315 indexed.push(node.parentNode);
3268 }
3316 }
3269 }
3317 }
3270 if (formula.match(/^\d+$/)) { // just a number
3318 if (formula.match(/^\d+$/)) { // just a number
3271 formula = Number(formula);
3319 formula = Number(formula);
3272 for (var i = 0, node; node = nodes[i]; i++)
3320 for (var i = 0, node; node = nodes[i]; i++)
3273 if (node.nodeIndex == formula) results.push(node);
3321 if (node.nodeIndex == formula) results.push(node);
3274 } else if (m = formula.match(/^(-?\d*)?n(([+-])(\d+))?/)) { // an+b
3322 } else if (m = formula.match(/^(-?\d*)?n(([+-])(\d+))?/)) { // an+b
3275 if (m[1] == "-") m[1] = -1;
3323 if (m[1] == "-") m[1] = -1;
3276 var a = m[1] ? Number(m[1]) : 1;
3324 var a = m[1] ? Number(m[1]) : 1;
3277 var b = m[2] ? Number(m[2]) : 0;
3325 var b = m[2] ? Number(m[2]) : 0;
3278 var indices = Selector.pseudos.getIndices(a, b, nodes.length);
3326 var indices = Selector.pseudos.getIndices(a, b, nodes.length);
3279 for (var i = 0, node, l = indices.length; node = nodes[i]; i++) {
3327 for (var i = 0, node, l = indices.length; node = nodes[i]; i++) {
3280 for (var j = 0; j < l; j++)
3328 for (var j = 0; j < l; j++)
3281 if (node.nodeIndex == indices[j]) results.push(node);
3329 if (node.nodeIndex == indices[j]) results.push(node);
3282 }
3330 }
3283 }
3331 }
3284 h.unmark(nodes);
3332 h.unmark(nodes);
3285 h.unmark(indexed);
3333 h.unmark(indexed);
3286 return results;
3334 return results;
3287 },
3335 },
3288
3336
3289 'empty': function(nodes, value, root) {
3337 'empty': function(nodes, value, root) {
3290 for (var i = 0, results = [], node; node = nodes[i]; i++) {
3338 for (var i = 0, results = [], node; node = nodes[i]; i++) {
3291 // IE treats comments as element nodes
3339 // IE treats comments as element nodes
3292 - if (node.tagName == '!' || (node.firstChild && !node.innerHTML.match(/^\s*$/))) continue;
3340 + if (node.tagName == '!' || node.firstChild) continue;
3293 results.push(node);
3341 results.push(node);
3294 }
3342 }
3295 return results;
3343 return results;
3296 },
3344 },
3297
3345
3298 'not': function(nodes, selector, root) {
3346 'not': function(nodes, selector, root) {
3299 var h = Selector.handlers, selectorType, m;
3347 var h = Selector.handlers, selectorType, m;
3300 var exclusions = new Selector(selector).findElements(root);
3348 var exclusions = new Selector(selector).findElements(root);
3301 h.mark(exclusions);
3349 h.mark(exclusions);
3302 for (var i = 0, results = [], node; node = nodes[i]; i++)
3350 for (var i = 0, results = [], node; node = nodes[i]; i++)
3303 - if (!node._counted) results.push(node);
3351 + if (!node._countedByPrototype) results.push(node);
3304 h.unmark(exclusions);
3352 h.unmark(exclusions);
3305 return results;
3353 return results;
3306 },
3354 },
3307
3355
3308 'enabled': function(nodes, value, root) {
3356 'enabled': function(nodes, value, root) {
3309 for (var i = 0, results = [], node; node = nodes[i]; i++)
3357 for (var i = 0, results = [], node; node = nodes[i]; i++)
3310 - if (!node.disabled) results.push(node);
3358 + if (!node.disabled && (!node.type || node.type !== 'hidden'))
3359 + results.push(node);
3311 return results;
3360 return results;
3312 },
3361 },
3313
3362
3314 'disabled': function(nodes, value, root) {
3363 'disabled': function(nodes, value, root) {
3315 for (var i = 0, results = [], node; node = nodes[i]; i++)
3364 for (var i = 0, results = [], node; node = nodes[i]; i++)
3316 if (node.disabled) results.push(node);
3365 if (node.disabled) results.push(node);
3317 return results;
3366 return results;
3318 },
3367 },
3319
3368
3320 'checked': function(nodes, value, root) {
3369 'checked': function(nodes, value, root) {
3321 for (var i = 0, results = [], node; node = nodes[i]; i++)
3370 for (var i = 0, results = [], node; node = nodes[i]; i++)
3322 if (node.checked) results.push(node);
3371 if (node.checked) results.push(node);
3323 return results;
3372 return results;
3324 }
3373 }
3325 },
3374 },
3326
3375
3327 operators: {
3376 operators: {
3328 '=': function(nv, v) { return nv == v; },
3377 '=': function(nv, v) { return nv == v; },
3329 '!=': function(nv, v) { return nv != v; },
3378 '!=': function(nv, v) { return nv != v; },
3330 - '^=': function(nv, v) { return nv.startsWith(v); },
3379 + '^=': function(nv, v) { return nv == v || nv && nv.startsWith(v); },
3380 + '$=': function(nv, v) { return nv == v || nv && nv.endsWith(v); },
3381 + '*=': function(nv, v) { return nv == v || nv && nv.include(v); },
3331 '$=': function(nv, v) { return nv.endsWith(v); },
3382 '$=': function(nv, v) { return nv.endsWith(v); },
3332 '*=': function(nv, v) { return nv.include(v); },
3383 '*=': function(nv, v) { return nv.include(v); },
3333 '~=': function(nv, v) { return (' ' + nv + ' ').include(' ' + v + ' '); },
3384 '~=': function(nv, v) { return (' ' + nv + ' ').include(' ' + v + ' '); },
3334 - '|=': function(nv, v) { return ('-' + nv.toUpperCase() + '-').include('-' + v.toUpperCase() + '-'); }
3385 + '|=': function(nv, v) { return ('-' + (nv || "").toUpperCase() +
3386 + '-').include('-' + (v || "").toUpperCase() + '-'); }
3387 + },
3388 +
3389 + split: function(expression) {
3390 + var expressions = [];
3391 + expression.scan(/(([\w#:.~>+()\s-]+|\*|\[.*?\])+)\s*(,|$)/, function(m) {
3392 + expressions.push(m[1].strip());
3393 + });
3394 + return expressions;
3335 },
3395 },
3336
3396
3337 matchElements: function(elements, expression) {
3397 matchElements: function(elements, expression) {
3338 - var matches = new Selector(expression).findElements(), h = Selector.handlers;
3398 + var matches = $$(expression), h = Selector.handlers;
3339 h.mark(matches);
3399 h.mark(matches);
3340 for (var i = 0, results = [], element; element = elements[i]; i++)
3400 for (var i = 0, results = [], element; element = elements[i]; i++)
3341 - if (element._counted) results.push(element);
3401 + if (element._countedByPrototype) results.push(element);
3342 h.unmark(matches);
3402 h.unmark(matches);
3343 return results;
3403 return results;
3344 },
3404 },
3345
3405
3346 findElement: function(elements, expression, index) {
3406 findElement: function(elements, expression, index) {
3347 if (Object.isNumber(expression)) {
3407 if (Object.isNumber(expression)) {
3348 index = expression; expression = false;
3408 index = expression; expression = false;
3349 }
3409 }
3350 return Selector.matchElements(elements, expression || '*')[index || 0];
3410 return Selector.matchElements(elements, expression || '*')[index || 0];
3351 },
3411 },
3352
3412
3353 findChildElements: function(element, expressions) {
3413 findChildElements: function(element, expressions) {
3354 - var exprs = expressions.join(',');
3414 + expressions = Selector.split(expressions.join(','));
3355 - expressions = [];
3356 - exprs.scan(/(([\w#:.~>+()\s-]+|\*|\[.*?\])+)\s*(,|$)/, function(m) {
3357 - expressions.push(m[1].strip());
3358 - });
3359 var results = [], h = Selector.handlers;
3415 var results = [], h = Selector.handlers;
3360 for (var i = 0, l = expressions.length, selector; i < l; i++) {
3416 for (var i = 0, l = expressions.length, selector; i < l; i++) {
3361 selector = new Selector(expressions[i].strip());
3417 selector = new Selector(expressions[i].strip());
3362 h.concat(results, selector.findElements(element));
3418 h.concat(results, selector.findElements(element));
3363 }
3419 }
3364 return (l > 1) ? h.unique(results) : results;
3420 return (l > 1) ? h.unique(results) : results;
3365 }
3421 }
3366 });
3422 });
3367
3423
3368 if (Prototype.Browser.IE) {
3424 if (Prototype.Browser.IE) {
3425 + Object.extend(Selector.handlers, {
3369 // IE returns comment nodes on getElementsByTagName("*").
3426 // IE returns comment nodes on getElementsByTagName("*").
3370 // Filter them out.
3427 // Filter them out.
3371 - Selector.handlers.concat = function(a, b) {
3428 + concat: function(a, b) {
3372 for (var i = 0, node; node = b[i]; i++)
3429 for (var i = 0, node; node = b[i]; i++)
3373 if (node.tagName !== "!") a.push(node);
3430 if (node.tagName !== "!") a.push(node);
3374 return a;
3431 return a;
3375 - };
3432 + },
3433 +
3434 + // IE improperly serializes _countedByPrototype in (inner|outer)HTML.
3435 + unmark: function(nodes) {
3436 + for (var i = 0, node; node = nodes[i]; i++)
3437 + node.removeAttribute('_countedByPrototype');
3438 + return nodes;
3439 + }
3440 + });
3376 }
3441 }
3377
3442
3378 function $$() {
3443 function $$() {
3379 return Selector.findChildElements(document, $A(arguments));
3444 return Selector.findChildElements(document, $A(arguments));
3380 }
3445 }
3381 var Form = {
3446 var Form = {
3382 reset: function(form) {
3447 reset: function(form) {
3383 $(form).reset();
3448 $(form).reset();
3384 return form;
3449 return form;
3385 },
3450 },
3386
3451
3387 serializeElements: function(elements, options) {
3452 serializeElements: function(elements, options) {
3388 if (typeof options != 'object') options = { hash: !!options };
3453 if (typeof options != 'object') options = { hash: !!options };
3389 else if (Object.isUndefined(options.hash)) options.hash = true;
3454 else if (Object.isUndefined(options.hash)) options.hash = true;
3390 var key, value, submitted = false, submit = options.submit;
3455 var key, value, submitted = false, submit = options.submit;
3391
3456
3392 var data = elements.inject({ }, function(result, element) {
3457 var data = elements.inject({ }, function(result, element) {
3393 if (!element.disabled && element.name) {
3458 if (!element.disabled && element.name) {
3394 key = element.name; value = $(element).getValue();
3459 key = element.name; value = $(element).getValue();
3395 - if (value != null && (element.type != 'submit' || (!submitted &&
3460 + if (value != null && element.type != 'file' && (element.type != 'submit' || (!submitted &&
3396 submit !== false && (!submit || key == submit) && (submitted = true)))) {
3461 submit !== false && (!submit || key == submit) && (submitted = true)))) {
3397 if (key in result) {
3462 if (key in result) {
3398 // a key is already present; construct an array of values
3463 // a key is already present; construct an array of values
3399 if (!Object.isArray(result[key])) result[key] = [result[key]];
3464 if (!Object.isArray(result[key])) result[key] = [result[key]];
3400 result[key].push(value);
3465 result[key].push(value);
3401 }
3466 }
3402 else result[key] = value;
3467 else result[key] = value;
3403 }
3468 }
3404 }
3469 }
3405 return result;
3470 return result;
3406 });
3471 });
3407
3472
3408 return options.hash ? data : Object.toQueryString(data);
3473 return options.hash ? data : Object.toQueryString(data);
3409 }
3474 }
3410 };
3475 };
3411
3476
3412 Form.Methods = {
3477 Form.Methods = {
3413 serialize: function(form, options) {
3478 serialize: function(form, options) {
3414 return Form.serializeElements(Form.getElements(form), options);
3479 return Form.serializeElements(Form.getElements(form), options);
3415 },
3480 },
3416
3481
3417 getElements: function(form) {
3482 getElements: function(form) {
3418 return $A($(form).getElementsByTagName('*')).inject([],
3483 return $A($(form).getElementsByTagName('*')).inject([],
3419 function(elements, child) {
3484 function(elements, child) {
3420 if (Form.Element.Serializers[child.tagName.toLowerCase()])
3485 if (Form.Element.Serializers[child.tagName.toLowerCase()])
3421 elements.push(Element.extend(child));
3486 elements.push(Element.extend(child));
3422 return elements;
3487 return elements;
3423 }
3488 }
3424 );
3489 );
3425 },
3490 },
3426
3491
3427 getInputs: function(form, typeName, name) {
3492 getInputs: function(form, typeName, name) {
3428 form = $(form);
3493 form = $(form);
3429 var inputs = form.getElementsByTagName('input');
3494 var inputs = form.getElementsByTagName('input');
3430
3495
3431 if (!typeName && !name) return $A(inputs).map(Element.extend);
3496 if (!typeName && !name) return $A(inputs).map(Element.extend);
3432
3497
3433 for (var i = 0, matchingInputs = [], length = inputs.length; i < length; i++) {
3498 for (var i = 0, matchingInputs = [], length = inputs.length; i < length; i++) {
3434 var input = inputs[i];
3499 var input = inputs[i];
3435 if ((typeName && input.type != typeName) || (name && input.name != name))
3500 if ((typeName && input.type != typeName) || (name && input.name != name))
3436 continue;
3501 continue;
3437 matchingInputs.push(Element.extend(input));
3502 matchingInputs.push(Element.extend(input));
3438 }
3503 }
3439
3504
3440 return matchingInputs;
3505 return matchingInputs;
3441 },
3506 },
3442
3507
3443 disable: function(form) {
3508 disable: function(form) {
@@ -3508,152 +3573,151
3508 serialize: function(element) {
3573 serialize: function(element) {
3509 element = $(element);
3574 element = $(element);
3510 if (!element.disabled && element.name) {
3575 if (!element.disabled && element.name) {
3511 var value = element.getValue();
3576 var value = element.getValue();
3512 if (value != undefined) {
3577 if (value != undefined) {
3513 var pair = { };
3578 var pair = { };
3514 pair[element.name] = value;
3579 pair[element.name] = value;
3515 return Object.toQueryString(pair);
3580 return Object.toQueryString(pair);
3516 }
3581 }
3517 }
3582 }
3518 return '';
3583 return '';
3519 },
3584 },
3520
3585
3521 getValue: function(element) {
3586 getValue: function(element) {
3522 element = $(element);
3587 element = $(element);
3523 var method = element.tagName.toLowerCase();
3588 var method = element.tagName.toLowerCase();
3524 return Form.Element.Serializers[method](element);
3589 return Form.Element.Serializers[method](element);
3525 },
3590 },
3526
3591
3527 setValue: function(element, value) {
3592 setValue: function(element, value) {
3528 element = $(element);
3593 element = $(element);
3529 var method = element.tagName.toLowerCase();
3594 var method = element.tagName.toLowerCase();
3530 Form.Element.Serializers[method](element, value);
3595 Form.Element.Serializers[method](element, value);
3531 return element;
3596 return element;
3532 },
3597 },
3533
3598
3534 clear: function(element) {
3599 clear: function(element) {
3535 $(element).value = '';
3600 $(element).value = '';
3536 return element;
3601 return element;
3537 },
3602 },
3538
3603
3539 present: function(element) {
3604 present: function(element) {
3540 return $(element).value != '';
3605 return $(element).value != '';
3541 },
3606 },
3542
3607
3543 activate: function(element) {
3608 activate: function(element) {
3544 element = $(element);
3609 element = $(element);
3545 try {
3610 try {
3546 element.focus();
3611 element.focus();
3547 if (element.select && (element.tagName.toLowerCase() != 'input' ||
3612 if (element.select && (element.tagName.toLowerCase() != 'input' ||
3548 !['button', 'reset', 'submit'].include(element.type)))
3613 !['button', 'reset', 'submit'].include(element.type)))
3549 element.select();
3614 element.select();
3550 } catch (e) { }
3615 } catch (e) { }
3551 return element;
3616 return element;
3552 },
3617 },
3553
3618
3554 disable: function(element) {
3619 disable: function(element) {
3555 element = $(element);
3620 element = $(element);
3556 - element.blur();
3557 element.disabled = true;
3621 element.disabled = true;
3558 return element;
3622 return element;
3559 },
3623 },
3560
3624
3561 enable: function(element) {
3625 enable: function(element) {
3562 element = $(element);
3626 element = $(element);
3563 element.disabled = false;
3627 element.disabled = false;
3564 return element;
3628 return element;
3565 }
3629 }
3566 };
3630 };
3567
3631
3568 /*--------------------------------------------------------------------------*/
3632 /*--------------------------------------------------------------------------*/
3569
3633
3570 var Field = Form.Element;
3634 var Field = Form.Element;
3571 var $F = Form.Element.Methods.getValue;
3635 var $F = Form.Element.Methods.getValue;
3572
3636
3573 /*--------------------------------------------------------------------------*/
3637 /*--------------------------------------------------------------------------*/
3574
3638
3575 Form.Element.Serializers = {
3639 Form.Element.Serializers = {
3576 input: function(element, value) {
3640 input: function(element, value) {
3577 switch (element.type.toLowerCase()) {
3641 switch (element.type.toLowerCase()) {
3578 case 'checkbox':
3642 case 'checkbox':
3579 case 'radio':
3643 case 'radio':
3580 return Form.Element.Serializers.inputSelector(element, value);
3644 return Form.Element.Serializers.inputSelector(element, value);
3581 default:
3645 default:
3582 return Form.Element.Serializers.textarea(element, value);
3646 return Form.Element.Serializers.textarea(element, value);
3583 }
3647 }
3584 },
3648 },
3585
3649
3586 inputSelector: function(element, value) {
3650 inputSelector: function(element, value) {
3587 if (Object.isUndefined(value)) return element.checked ? element.value : null;
3651 if (Object.isUndefined(value)) return element.checked ? element.value : null;
3588 else element.checked = !!value;
3652 else element.checked = !!value;
3589 },
3653 },
3590
3654
3591 textarea: function(element, value) {
3655 textarea: function(element, value) {
3592 if (Object.isUndefined(value)) return element.value;
3656 if (Object.isUndefined(value)) return element.value;
3593 else element.value = value;
3657 else element.value = value;
3594 },
3658 },
3595
3659
3596 - select: function(element, index) {
3660 + select: function(element, value) {
3597 - if (Object.isUndefined(index))
3661 + if (Object.isUndefined(value))
3598 return this[element.type == 'select-one' ?
3662 return this[element.type == 'select-one' ?
3599 'selectOne' : 'selectMany'](element);
3663 'selectOne' : 'selectMany'](element);
3600 else {
3664 else {
3601 - var opt, value, single = !Object.isArray(index);
3665 + var opt, currentValue, single = !Object.isArray(value);
3602 for (var i = 0, length = element.length; i < length; i++) {
3666 for (var i = 0, length = element.length; i < length; i++) {
3603 opt = element.options[i];
3667 opt = element.options[i];
3604 - value = this.optionValue(opt);
3668 + currentValue = this.optionValue(opt);
3605 if (single) {
3669 if (single) {
3606 - if (value == index) {
3670 + if (currentValue == value) {
3607 opt.selected = true;
3671 opt.selected = true;
3608 return;
3672 return;
3609 }
3673 }
3610 }
3674 }
3611 - else opt.selected = index.include(value);
3675 + else opt.selected = value.include(currentValue);
3612 }
3676 }
3613 }
3677 }
3614 },
3678 },
3615
3679
3616 selectOne: function(element) {
3680 selectOne: function(element) {
3617 var index = element.selectedIndex;
3681 var index = element.selectedIndex;
3618 return index >= 0 ? this.optionValue(element.options[index]) : null;
3682 return index >= 0 ? this.optionValue(element.options[index]) : null;
3619 },
3683 },
3620
3684
3621 selectMany: function(element) {
3685 selectMany: function(element) {
3622 var values, length = element.length;
3686 var values, length = element.length;
3623 if (!length) return null;
3687 if (!length) return null;
3624
3688
3625 for (var i = 0, values = []; i < length; i++) {
3689 for (var i = 0, values = []; i < length; i++) {
3626 var opt = element.options[i];
3690 var opt = element.options[i];
3627 if (opt.selected) values.push(this.optionValue(opt));
3691 if (opt.selected) values.push(this.optionValue(opt));
3628 }
3692 }
3629 return values;
3693 return values;
3630 },
3694 },
3631
3695
3632 optionValue: function(opt) {
3696 optionValue: function(opt) {
3633 // extend element because hasAttribute may not be native
3697 // extend element because hasAttribute may not be native
3634 return Element.extend(opt).hasAttribute('value') ? opt.value : opt.text;
3698 return Element.extend(opt).hasAttribute('value') ? opt.value : opt.text;
3635 }
3699 }
3636 };
3700 };
3637
3701
3638 /*--------------------------------------------------------------------------*/
3702 /*--------------------------------------------------------------------------*/
3639
3703
3640 Abstract.TimedObserver = Class.create(PeriodicalExecuter, {
3704 Abstract.TimedObserver = Class.create(PeriodicalExecuter, {
3641 initialize: function($super, element, frequency, callback) {
3705 initialize: function($super, element, frequency, callback) {
3642 $super(callback, frequency);
3706 $super(callback, frequency);
3643 this.element = $(element);
3707 this.element = $(element);
3644 this.lastValue = this.getValue();
3708 this.lastValue = this.getValue();
3645 },
3709 },
3646
3710
3647 execute: function() {
3711 execute: function() {
3648 var value = this.getValue();
3712 var value = this.getValue();
3649 if (Object.isString(this.lastValue) && Object.isString(value) ?
3713 if (Object.isString(this.lastValue) && Object.isString(value) ?
3650 this.lastValue != value : String(this.lastValue) != String(value)) {
3714 this.lastValue != value : String(this.lastValue) != String(value)) {
3651 this.callback(this.element, value);
3715 this.callback(this.element, value);
3652 this.lastValue = value;
3716 this.lastValue = value;
3653 }
3717 }
3654 }
3718 }
3655 });
3719 });
3656
3720
3657 Form.Element.Observer = Class.create(Abstract.TimedObserver, {
3721 Form.Element.Observer = Class.create(Abstract.TimedObserver, {
3658 getValue: function() {
3722 getValue: function() {
3659 return Form.Element.getValue(this.element);
3723 return Form.Element.getValue(this.element);
@@ -3734,326 +3798,357
3734 KEY_END: 35,
3798 KEY_END: 35,
3735 KEY_PAGEUP: 33,
3799 KEY_PAGEUP: 33,
3736 KEY_PAGEDOWN: 34,
3800 KEY_PAGEDOWN: 34,
3737 KEY_INSERT: 45,
3801 KEY_INSERT: 45,
3738
3802
3739 cache: { },
3803 cache: { },
3740
3804
3741 relatedTarget: function(event) {
3805 relatedTarget: function(event) {
3742 var element;
3806 var element;
3743 switch(event.type) {
3807 switch(event.type) {
3744 case 'mouseover': element = event.fromElement; break;
3808 case 'mouseover': element = event.fromElement; break;
3745 case 'mouseout': element = event.toElement; break;
3809 case 'mouseout': element = event.toElement; break;
3746 default: return null;
3810 default: return null;
3747 }
3811 }
3748 return Element.extend(element);
3812 return Element.extend(element);
3749 }
3813 }
3750 });
3814 });
3751
3815
3752 Event.Methods = (function() {
3816 Event.Methods = (function() {
3753 var isButton;
3817 var isButton;
3754
3818
3755 if (Prototype.Browser.IE) {
3819 if (Prototype.Browser.IE) {
3756 var buttonMap = { 0: 1, 1: 4, 2: 2 };
3820 var buttonMap = { 0: 1, 1: 4, 2: 2 };
3757 isButton = function(event, code) {
3821 isButton = function(event, code) {
3758 return event.button == buttonMap[code];
3822 return event.button == buttonMap[code];
3759 };
3823 };
3760
3824
3761 } else if (Prototype.Browser.WebKit) {
3825 } else if (Prototype.Browser.WebKit) {
3762 isButton = function(event, code) {
3826 isButton = function(event, code) {
3763 switch (code) {
3827 switch (code) {
3764 case 0: return event.which == 1 && !event.metaKey;
3828 case 0: return event.which == 1 && !event.metaKey;
3765 case 1: return event.which == 1 && event.metaKey;
3829 case 1: return event.which == 1 && event.metaKey;
3766 default: return false;
3830 default: return false;
3767 }
3831 }
3768 };
3832 };
3769
3833
3770 } else {
3834 } else {
3771 isButton = function(event, code) {
3835 isButton = function(event, code) {
3772 return event.which ? (event.which === code + 1) : (event.button === code);
3836 return event.which ? (event.which === code + 1) : (event.button === code);
3773 };
3837 };
3774 }
3838 }
3775
3839
3776 return {
3840 return {
3777 isLeftClick: function(event) { return isButton(event, 0) },
3841 isLeftClick: function(event) { return isButton(event, 0) },
3778 isMiddleClick: function(event) { return isButton(event, 1) },
3842 isMiddleClick: function(event) { return isButton(event, 1) },
3779 isRightClick: function(event) { return isButton(event, 2) },
3843 isRightClick: function(event) { return isButton(event, 2) },
3780
3844
3781 element: function(event) {
3845 element: function(event) {
3782 - var node = Event.extend(event).target;
3846 + event = Event.extend(event);
3783 - return Element.extend(node.nodeType == Node.TEXT_NODE ? node.parentNode : node);
3847 +
3848 + var node = event.target,
3849 + type = event.type,
3850 + currentTarget = event.currentTarget;
3851 +
3852 + if (currentTarget && currentTarget.tagName) {
3853 + // Firefox screws up the "click" event when moving between radio buttons
3854 + // via arrow keys. It also screws up the "load" and "error" events on images,
3855 + // reporting the document as the target instead of the original image.
3856 + if (type === 'load' || type === 'error' ||
3857 + (type === 'click' && currentTarget.tagName.toLowerCase() === 'input'
3858 + && currentTarget.type === 'radio'))
3859 + node = currentTarget;
3860 + }
3861 + if (node.nodeType == Node.TEXT_NODE) node = node.parentNode;
3862 + return Element.extend(node);
3784 },
3863 },
3785
3864
3786 findElement: function(event, expression) {
3865 findElement: function(event, expression) {
3787 var element = Event.element(event);
3866 var element = Event.element(event);
3788 if (!expression) return element;
3867 if (!expression) return element;
3789 var elements = [element].concat(element.ancestors());
3868 var elements = [element].concat(element.ancestors());
3790 return Selector.findElement(elements, expression, 0);
3869 return Selector.findElement(elements, expression, 0);
3791 },
3870 },
3792
3871
3793 pointer: function(event) {
3872 pointer: function(event) {
3873 + var docElement = document.documentElement,
3874 + body = document.body || { scrollLeft: 0, scrollTop: 0 };
3794 return {
3875 return {
3795 x: event.pageX || (event.clientX +
3876 x: event.pageX || (event.clientX +
3796 - (document.documentElement.scrollLeft || document.body.scrollLeft)),
3877 + (docElement.scrollLeft || body.scrollLeft) -
3878 + (docElement.clientLeft || 0)),
3797 y: event.pageY || (event.clientY +
3879 y: event.pageY || (event.clientY +
3798 - (document.documentElement.scrollTop || document.body.scrollTop))
3880 + (docElement.scrollTop || body.scrollTop) -
3881 + (docElement.clientTop || 0))
3799 };
3882 };
3800 },
3883 },
3801
3884
3802 pointerX: function(event) { return Event.pointer(event).x },
3885 pointerX: function(event) { return Event.pointer(event).x },
3803 pointerY: function(event) { return Event.pointer(event).y },
3886 pointerY: function(event) { return Event.pointer(event).y },
3804
3887
3805 stop: function(event) {
3888 stop: function(event) {
3806 Event.extend(event);
3889 Event.extend(event);
3807 event.preventDefault();
3890 event.preventDefault();
3808 event.stopPropagation();
3891 event.stopPropagation();
3809 event.stopped = true;
3892 event.stopped = true;
3810 }
3893 }
3811 };
3894 };
3812 })();
3895 })();
3813
3896
3814 Event.extend = (function() {
3897 Event.extend = (function() {
3815 var methods = Object.keys(Event.Methods).inject({ }, function(m, name) {
3898 var methods = Object.keys(Event.Methods).inject({ }, function(m, name) {
3816 m[name] = Event.Methods[name].methodize();
3899 m[name] = Event.Methods[name].methodize();
3817 return m;
3900 return m;
3818 });
3901 });
3819
3902
3820 if (Prototype.Browser.IE) {
3903 if (Prototype.Browser.IE) {
3821 Object.extend(methods, {
3904 Object.extend(methods, {
3822 stopPropagation: function() { this.cancelBubble = true },
3905 stopPropagation: function() { this.cancelBubble = true },
3823 preventDefault: function() { this.returnValue = false },
3906 preventDefault: function() { this.returnValue = false },
3824 inspect: function() { return "[object Event]" }
3907 inspect: function() { return "[object Event]" }
3825 });
3908 });
3826
3909
3827 return function(event) {
3910 return function(event) {
3828 if (!event) return false;
3911 if (!event) return false;
3829 if (event._extendedByPrototype) return event;
3912 if (event._extendedByPrototype) return event;
3830
3913
3831 event._extendedByPrototype = Prototype.emptyFunction;
3914 event._extendedByPrototype = Prototype.emptyFunction;
3832 var pointer = Event.pointer(event);
3915 var pointer = Event.pointer(event);
3833 Object.extend(event, {
3916 Object.extend(event, {
3834 target: event.srcElement,
3917 target: event.srcElement,
3835 relatedTarget: Event.relatedTarget(event),
3918 relatedTarget: Event.relatedTarget(event),
3836 pageX: pointer.x,
3919 pageX: pointer.x,
3837 pageY: pointer.y
3920 pageY: pointer.y
3838 });
3921 });
3839 return Object.extend(event, methods);
3922 return Object.extend(event, methods);
3840 };
3923 };
3841
3924
3842 } else {
3925 } else {
3843 - Event.prototype = Event.prototype || document.createEvent("HTMLEvents").__proto__;
3926 + Event.prototype = Event.prototype || document.createEvent("HTMLEvents")['__proto__'];
3844 Object.extend(Event.prototype, methods);
3927 Object.extend(Event.prototype, methods);
3845 return Prototype.K;
3928 return Prototype.K;
3846 }
3929 }
3847 })();
3930 })();
3848
3931
3849 Object.extend(Event, (function() {
3932 Object.extend(Event, (function() {
3850 var cache = Event.cache;
3933 var cache = Event.cache;
3851
3934
3852 function getEventID(element) {
3935 function getEventID(element) {
3853 - if (element._eventID) return element._eventID;
3936 + if (element._prototypeEventID) return element._prototypeEventID[0];
3854 arguments.callee.id = arguments.callee.id || 1;
3937 arguments.callee.id = arguments.callee.id || 1;
3855 - return element._eventID = ++arguments.callee.id;
3938 + return element._prototypeEventID = [++arguments.callee.id];
3856 }
3939 }
3857
3940
3858 function getDOMEventName(eventName) {
3941 function getDOMEventName(eventName) {
3859 if (eventName && eventName.include(':')) return "dataavailable";
3942 if (eventName && eventName.include(':')) return "dataavailable";
3860 return eventName;
3943 return eventName;
3861 }
3944 }
3862
3945
3863 function getCacheForID(id) {
3946 function getCacheForID(id) {
3864 return cache[id] = cache[id] || { };
3947 return cache[id] = cache[id] || { };
3865 }
3948 }
3866
3949
3867 function getWrappersForEventName(id, eventName) {
3950 function getWrappersForEventName(id, eventName) {
3868 var c = getCacheForID(id);
3951 var c = getCacheForID(id);
3869 return c[eventName] = c[eventName] || [];
3952 return c[eventName] = c[eventName] || [];
3870 }
3953 }
3871
3954
3872 function createWrapper(element, eventName, handler) {
3955 function createWrapper(element, eventName, handler) {
3873 var id = getEventID(element);
3956 var id = getEventID(element);
3874 var c = getWrappersForEventName(id, eventName);
3957 var c = getWrappersForEventName(id, eventName);
3875 if (c.pluck("handler").include(handler)) return false;
3958 if (c.pluck("handler").include(handler)) return false;
3876
3959
3877 var wrapper = function(event) {
3960 var wrapper = function(event) {
3878 if (!Event || !Event.extend ||
3961 if (!Event || !Event.extend ||
3879 (event.eventName && event.eventName != eventName))
3962 (event.eventName && event.eventName != eventName))
3880 return false;
3963 return false;
3881
3964
3882 Event.extend(event);
3965 Event.extend(event);
3883 - handler.call(element, event)
3966 + handler.call(element, event);
3884 };
3967 };
3885
3968
3886 wrapper.handler = handler;
3969 wrapper.handler = handler;
3887 c.push(wrapper);
3970 c.push(wrapper);
3888 return wrapper;
3971 return wrapper;
3889 }
3972 }
3890
3973
3891 function findWrapper(id, eventName, handler) {
3974 function findWrapper(id, eventName, handler) {
3892 var c = getWrappersForEventName(id, eventName);
3975 var c = getWrappersForEventName(id, eventName);
3893 return c.find(function(wrapper) { return wrapper.handler == handler });
3976 return c.find(function(wrapper) { return wrapper.handler == handler });
3894 }
3977 }
3895
3978
3896 function destroyWrapper(id, eventName, handler) {
3979 function destroyWrapper(id, eventName, handler) {
3897 var c = getCacheForID(id);
3980 var c = getCacheForID(id);
3898 if (!c[eventName]) return false;
3981 if (!c[eventName]) return false;
3899 c[eventName] = c[eventName].without(findWrapper(id, eventName, handler));
3982 c[eventName] = c[eventName].without(findWrapper(id, eventName, handler));
3900 }
3983 }
3901
3984
3902 function destroyCache() {
3985 function destroyCache() {
3903 for (var id in cache)
3986 for (var id in cache)
3904 for (var eventName in cache[id])
3987 for (var eventName in cache[id])
3905 cache[id][eventName] = null;
3988 cache[id][eventName] = null;
3906 }
3989 }
3907
3990
3991 +
3992 + // Internet Explorer needs to remove event handlers on page unload
3993 + // in order to avoid memory leaks.
3908 if (window.attachEvent) {
3994 if (window.attachEvent) {
3909 window.attachEvent("onunload", destroyCache);
3995 window.attachEvent("onunload", destroyCache);
3910 }
3996 }
3911
3997
3998 + // Safari has a dummy event handler on page unload so that it won't
3999 + // use its bfcache. Safari <= 3.1 has an issue with restoring the "document"
4000 + // object when page is returned to via the back button using its bfcache.
4001 + if (Prototype.Browser.WebKit) {
4002 + window.addEventListener('unload', Prototype.emptyFunction, false);
4003 + }
4004 +
3912 return {
4005 return {
3913 observe: function(element, eventName, handler) {
4006 observe: function(element, eventName, handler) {
3914 element = $(element);
4007 element = $(element);
3915 var name = getDOMEventName(eventName);
4008 var name = getDOMEventName(eventName);
3916
4009
3917 var wrapper = createWrapper(element, eventName, handler);
4010 var wrapper = createWrapper(element, eventName, handler);
3918 if (!wrapper) return element;
4011 if (!wrapper) return element;
3919
4012
3920 if (element.addEventListener) {
4013 if (element.addEventListener) {
3921 element.addEventListener(name, wrapper, false);
4014 element.addEventListener(name, wrapper, false);
3922 } else {
4015 } else {
3923 element.attachEvent("on" + name, wrapper);
4016 element.attachEvent("on" + name, wrapper);
3924 }
4017 }
3925
4018
3926 return element;
4019 return element;
3927 },
4020 },
3928
4021
3929 stopObserving: function(element, eventName, handler) {
4022 stopObserving: function(element, eventName, handler) {
3930 element = $(element);
4023 element = $(element);
3931 var id = getEventID(element), name = getDOMEventName(eventName);
4024 var id = getEventID(element), name = getDOMEventName(eventName);
3932
4025
3933 if (!handler && eventName) {
4026 if (!handler && eventName) {
3934 getWrappersForEventName(id, eventName).each(function(wrapper) {
4027 getWrappersForEventName(id, eventName).each(function(wrapper) {
3935 element.stopObserving(eventName, wrapper.handler);
4028 element.stopObserving(eventName, wrapper.handler);
3936 });
4029 });
3937 return element;
4030 return element;
3938
4031
3939 } else if (!eventName) {
4032 } else if (!eventName) {
3940 Object.keys(getCacheForID(id)).each(function(eventName) {
4033 Object.keys(getCacheForID(id)).each(function(eventName) {
3941 element.stopObserving(eventName);
4034 element.stopObserving(eventName);
3942 });
4035 });
3943 return element;
4036 return element;
3944 }
4037 }
3945
4038
3946 var wrapper = findWrapper(id, eventName, handler);
4039 var wrapper = findWrapper(id, eventName, handler);
3947 if (!wrapper) return element;
4040 if (!wrapper) return element;
3948
4041
3949 if (element.removeEventListener) {
4042 if (element.removeEventListener) {
3950 element.removeEventListener(name, wrapper, false);
4043 element.removeEventListener(name, wrapper, false);
3951 } else {
4044 } else {
3952 element.detachEvent("on" + name, wrapper);
4045 element.detachEvent("on" + name, wrapper);
3953 }
4046 }
3954
4047
3955 destroyWrapper(id, eventName, handler);
4048 destroyWrapper(id, eventName, handler);
3956
4049
3957 return element;
4050 return element;
3958 },
4051 },
3959
4052
3960 fire: function(element, eventName, memo) {
4053 fire: function(element, eventName, memo) {
3961 element = $(element);
4054 element = $(element);
3962 if (element == document && document.createEvent && !element.dispatchEvent)
4055 if (element == document && document.createEvent && !element.dispatchEvent)
3963 element = document.documentElement;
4056 element = document.documentElement;
3964
4057
4058 + var event;
3965 if (document.createEvent) {
4059 if (document.createEvent) {
3966 - var event = document.createEvent("HTMLEvents");
4060 + event = document.createEvent("HTMLEvents");
3967 event.initEvent("dataavailable", true, true);
4061 event.initEvent("dataavailable", true, true);
3968 } else {
4062 } else {
3969 - var event = document.createEventObject();
4063 + event = document.createEventObject();
3970 event.eventType = "ondataavailable";
4064 event.eventType = "ondataavailable";
3971 }
4065 }
3972
4066
3973 event.eventName = eventName;
4067 event.eventName = eventName;
3974 event.memo = memo || { };
4068 event.memo = memo || { };
3975
4069
3976 if (document.createEvent) {
4070 if (document.createEvent) {
3977 element.dispatchEvent(event);
4071 element.dispatchEvent(event);
3978 } else {
4072 } else {
3979 element.fireEvent(event.eventType, event);
4073 element.fireEvent(event.eventType, event);
3980 }
4074 }
3981
4075
3982 return Event.extend(event);
4076 return Event.extend(event);
3983 }
4077 }
3984 };
4078 };
3985 })());
4079 })());
3986
4080
3987 Object.extend(Event, Event.Methods);
4081 Object.extend(Event, Event.Methods);
3988
4082
3989 Element.addMethods({
4083 Element.addMethods({
3990 fire: Event.fire,
4084 fire: Event.fire,
3991 observe: Event.observe,
4085 observe: Event.observe,
3992 stopObserving: Event.stopObserving
4086 stopObserving: Event.stopObserving
3993 });
4087 });
3994
4088
3995 Object.extend(document, {
4089 Object.extend(document, {
3996 fire: Element.Methods.fire.methodize(),
4090 fire: Element.Methods.fire.methodize(),
3997 observe: Element.Methods.observe.methodize(),
4091 observe: Element.Methods.observe.methodize(),
3998 - stopObserving: Element.Methods.stopObserving.methodize()
4092 + stopObserving: Element.Methods.stopObserving.methodize(),
4093 + loaded: false
3999 });
4094 });
4000
4095
4001 (function() {
4096 (function() {
4002 /* Support for the DOMContentLoaded event is based on work by Dan Webb,
4097 /* Support for the DOMContentLoaded event is based on work by Dan Webb,
4003 Matthias Miller, Dean Edwards and John Resig. */
4098 Matthias Miller, Dean Edwards and John Resig. */
4004
4099
4005 - var timer, fired = false;
4100 + var timer;
4006
4101
4007 function fireContentLoadedEvent() {
4102 function fireContentLoadedEvent() {
4008 - if (fired) return;
4103 + if (document.loaded) return;
4009 if (timer) window.clearInterval(timer);
4104 if (timer) window.clearInterval(timer);
4010 document.fire("dom:loaded");
4105 document.fire("dom:loaded");
4011 - fired = true;
4106 + document.loaded = true;
4012 }
4107 }
4013
4108
4014 if (document.addEventListener) {
4109 if (document.addEventListener) {
4015 if (Prototype.Browser.WebKit) {
4110 if (Prototype.Browser.WebKit) {
4016 timer = window.setInterval(function() {
4111 timer = window.setInterval(function() {
4017 if (/loaded|complete/.test(document.readyState))
4112 if (/loaded|complete/.test(document.readyState))
4018 fireContentLoadedEvent();
4113 fireContentLoadedEvent();
4019 }, 0);
4114 }, 0);
4020
4115
4021 Event.observe(window, "load", fireContentLoadedEvent);
4116 Event.observe(window, "load", fireContentLoadedEvent);
4022
4117
4023 } else {
4118 } else {
4024 document.addEventListener("DOMContentLoaded",
4119 document.addEventListener("DOMContentLoaded",
4025 fireContentLoadedEvent, false);
4120 fireContentLoadedEvent, false);
4026 }
4121 }
4027
4122
4028 } else {
4123 } else {
4029 document.write("<script id=__onDOMContentLoaded defer src=//:><\/script>");
4124 document.write("<script id=__onDOMContentLoaded defer src=//:><\/script>");
4030 $("__onDOMContentLoaded").onreadystatechange = function() {
4125 $("__onDOMContentLoaded").onreadystatechange = function() {
4031 if (this.readyState == "complete") {
4126 if (this.readyState == "complete") {
4032 this.onreadystatechange = null;
4127 this.onreadystatechange = null;
4033 fireContentLoadedEvent();
4128 fireContentLoadedEvent();
4034 }
4129 }
4035 };
4130 };
4036 }
4131 }
4037 })();
4132 })();
4038 /*------------------------------- DEPRECATED -------------------------------*/
4133 /*------------------------------- DEPRECATED -------------------------------*/
4039
4134
4040 Hash.toQueryString = Object.toQueryString;
4135 Hash.toQueryString = Object.toQueryString;
4041
4136
4042 var Toggle = { display: Element.toggle };
4137 var Toggle = { display: Element.toggle };
4043
4138
4044 Element.Methods.childOf = Element.Methods.descendantOf;
4139 Element.Methods.childOf = Element.Methods.descendantOf;
4045
4140
4046 var Insertion = {
4141 var Insertion = {
4047 Before: function(element, content) {
4142 Before: function(element, content) {
4048 return Element.insert(element, {before:content});
4143 return Element.insert(element, {before:content});
4049 },
4144 },
4050
4145
4051 Top: function(element, content) {
4146 Top: function(element, content) {
4052 return Element.insert(element, {top:content});
4147 return Element.insert(element, {top:content});
4053 },
4148 },
4054
4149
4055 Bottom: function(element, content) {
4150 Bottom: function(element, content) {
4056 return Element.insert(element, {bottom:content});
4151 return Element.insert(element, {bottom:content});
4057 },
4152 },
4058
4153
4059 After: function(element, content) {
4154 After: function(element, content) {
You need to be logged in to leave comments. Login now