Description:
initial commit git-svn-id: http://theory.cpe.ku.ac.th/grader/web/trunk@1 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

r0:adb458d2f524 - - 114 files changed: 7811 inserted, 0 deleted

@@ -0,0 +1,182
1 + == Welcome to Rails
2 +
3 + Rails is a web-application and persistence framework that includes everything
4 + needed to create database-backed web-applications according to the
5 + Model-View-Control pattern of separation. This pattern splits the view (also
6 + called the presentation) into "dumb" templates that are primarily responsible
7 + for inserting pre-built data in between HTML tags. The model contains the
8 + "smart" domain objects (such as Account, Product, Person, Post) that holds all
9 + the business logic and knows how to persist themselves to a database. The
10 + controller handles the incoming requests (such as Save New Account, Update
11 + Product, Show Post) by manipulating the model and directing data to the view.
12 +
13 + In Rails, the model is handled by what's called an object-relational mapping
14 + layer entitled Active Record. This layer allows you to present the data from
15 + database rows as objects and embellish these data objects with business logic
16 + methods. You can read more about Active Record in
17 + link:files/vendor/rails/activerecord/README.html.
18 +
19 + The controller and view are handled by the Action Pack, which handles both
20 + layers by its two parts: Action View and Action Controller. These two layers
21 + are bundled in a single package due to their heavy interdependence. This is
22 + unlike the relationship between the Active Record and Action Pack that is much
23 + more separate. Each of these packages can be used independently outside of
24 + Rails. You can read more about Action Pack in
25 + link:files/vendor/rails/actionpack/README.html.
26 +
27 +
28 + == Getting started
29 +
30 + 1. At the command prompt, start a new rails application using the rails command
31 + and your application name. Ex: rails myapp
32 + (If you've downloaded rails in a complete tgz or zip, this step is already done)
33 + 2. Change directory into myapp and start the web server: <tt>script/server</tt> (run with --help for options)
34 + 3. Go to http://localhost:3000/ and get "Welcome aboard: You’re riding the Rails!"
35 + 4. Follow the guidelines to start developing your application
36 +
37 +
38 + == Web Servers
39 +
40 + By default, Rails will try to use Mongrel and lighttpd if they are installed, otherwise
41 + Rails will use the WEBrick, the webserver that ships with Ruby. When you run script/server,
42 + Rails will check if Mongrel exists, then lighttpd and finally fall back to WEBrick. This ensures
43 + that you can always get up and running quickly.
44 +
45 + Mongrel is a Ruby-based webserver with a C-component (which requires compilation) that is
46 + suitable for development and deployment of Rails applications. If you have Ruby Gems installed,
47 + getting up and running with mongrel is as easy as: <tt>gem install mongrel</tt>.
48 + More info at: http://mongrel.rubyforge.org
49 +
50 + If Mongrel is not installed, Rails will look for lighttpd. It's considerably faster than
51 + Mongrel and WEBrick and also suited for production use, but requires additional
52 + installation and currently only works well on OS X/Unix (Windows users are encouraged
53 + to start with Mongrel). We recommend version 1.4.11 and higher. You can download it from
54 + http://www.lighttpd.net.
55 +
56 + And finally, if neither Mongrel or lighttpd are installed, Rails will use the built-in Ruby
57 + web server, WEBrick. WEBrick is a small Ruby web server suitable for development, but not
58 + for production.
59 +
60 + But of course its also possible to run Rails on any platform that supports FCGI.
61 + Apache, LiteSpeed, IIS are just a few. For more information on FCGI,
62 + please visit: http://wiki.rubyonrails.com/rails/pages/FastCGI
63 +
64 +
65 + == Debugging Rails
66 +
67 + Have "tail -f" commands running on the server.log and development.log. Rails will
68 + automatically display debugging and runtime information to these files. Debugging
69 + info will also be shown in the browser on requests from 127.0.0.1.
70 +
71 +
72 + == Breakpoints
73 +
74 + Breakpoint support is available through the script/breakpointer client. This
75 + means that you can break out of execution at any point in the code, investigate
76 + and change the model, AND then resume execution! Example:
77 +
78 + class WeblogController < ActionController::Base
79 + def index
80 + @posts = Post.find(:all)
81 + breakpoint "Breaking out from the list"
82 + end
83 + end
84 +
85 + So the controller will accept the action, run the first line, then present you
86 + with a IRB prompt in the breakpointer window. Here you can do things like:
87 +
88 + Executing breakpoint "Breaking out from the list" at .../webrick_server.rb:16 in 'breakpoint'
89 +
90 + >> @posts.inspect
91 + => "[#<Post:0x14a6be8 @attributes={\"title\"=>nil, \"body\"=>nil, \"id\"=>\"1\"}>,
92 + #<Post:0x14a6620 @attributes={\"title\"=>\"Rails you know!\", \"body\"=>\"Only ten..\", \"id\"=>\"2\"}>]"
93 + >> @posts.first.title = "hello from a breakpoint"
94 + => "hello from a breakpoint"
95 +
96 + ...and even better is that you can examine how your runtime objects actually work:
97 +
98 + >> f = @posts.first
99 + => #<Post:0x13630c4 @attributes={"title"=>nil, "body"=>nil, "id"=>"1"}>
100 + >> f.
101 + Display all 152 possibilities? (y or n)
102 +
103 + Finally, when you're ready to resume execution, you press CTRL-D
104 +
105 +
106 + == Console
107 +
108 + You can interact with the domain model by starting the console through <tt>script/console</tt>.
109 + Here you'll have all parts of the application configured, just like it is when the
110 + application is running. You can inspect domain models, change values, and save to the
111 + database. Starting the script without arguments will launch it in the development environment.
112 + Passing an argument will specify a different environment, like <tt>script/console production</tt>.
113 +
114 + To reload your controllers and models after launching the console run <tt>reload!</tt>
115 +
116 + To reload your controllers and models after launching the console run <tt>reload!</tt>
117 +
118 +
119 +
120 + == Description of contents
121 +
122 + app
123 + Holds all the code that's specific to this particular application.
124 +
125 + app/controllers
126 + Holds controllers that should be named like weblogs_controller.rb for
127 + automated URL mapping. All controllers should descend from ApplicationController
128 + which itself descends from ActionController::Base.
129 +
130 + app/models
131 + Holds models that should be named like post.rb.
132 + Most models will descend from ActiveRecord::Base.
133 +
134 + app/views
135 + Holds the template files for the view that should be named like
136 + weblogs/index.rhtml for the WeblogsController#index action. All views use eRuby
137 + syntax.
138 +
139 + app/views/layouts
140 + Holds the template files for layouts to be used with views. This models the common
141 + header/footer method of wrapping views. In your views, define a layout using the
142 + <tt>layout :default</tt> and create a file named default.rhtml. Inside default.rhtml,
143 + call <% yield %> to render the view using this layout.
144 +
145 + app/helpers
146 + Holds view helpers that should be named like weblogs_helper.rb. These are generated
147 + for you automatically when using script/generate for controllers. Helpers can be used to
148 + wrap functionality for your views into methods.
149 +
150 + config
151 + Configuration files for the Rails environment, the routing map, the database, and other dependencies.
152 +
153 + components
154 + Self-contained mini-applications that can bundle together controllers, models, and views.
155 +
156 + db
157 + Contains the database schema in schema.rb. db/migrate contains all
158 + the sequence of Migrations for your schema.
159 +
160 + doc
161 + This directory is where your application documentation will be stored when generated
162 + using <tt>rake doc:app</tt>
163 +
164 + lib
165 + Application specific libraries. Basically, any kind of custom code that doesn't
166 + belong under controllers, models, or helpers. This directory is in the load path.
167 +
168 + public
169 + The directory available for the web server. Contains subdirectories for images, stylesheets,
170 + and javascripts. Also contains the dispatchers and the default HTML files. This should be
171 + set as the DOCUMENT_ROOT of your web server.
172 +
173 + script
174 + Helper scripts for automation and generation.
175 +
176 + test
177 + Unit and functional tests along with fixtures. When using the script/generate scripts, template
178 + test files will be generated for you and placed in this directory.
179 +
180 + vendor
181 + External libraries that the application depends on. Also includes the plugins subdirectory.
182 + This directory is in the load path.
@@ -0,0 +1,10
1 + # Add your own tasks in files placed in lib/tasks ending in .rake,
2 + # for example lib/tasks/capistrano.rake, and they will automatically be available to Rake.
3 +
4 + require(File.join(File.dirname(__FILE__), 'config', 'boot'))
5 +
6 + require 'rake'
7 + require 'rake/testtask'
8 + require 'rake/rdoctask'
9 +
10 + require 'tasks/rails'
@@ -0,0 +1,34
1 + # Filters added to this controller apply to all controllers in the application.
2 + # Likewise, all the methods added will be available for all controllers.
3 +
4 + class ApplicationController < ActionController::Base
5 + # Pick a unique cookie name to distinguish our session data from others'
6 + session :session_key => '_grader_session_id'
7 +
8 + protected
9 + def authenticate
10 + unless session[:user_id]
11 + redirect_to :controller => 'main', :action => 'login'
12 + return false
13 + end
14 + return true
15 + end
16 +
17 + def authorization
18 + return false unless authenticate
19 + user = User.find(session[:user_id])
20 + unless user.roles.detect { |role|
21 + role.rights.detect{ |right|
22 + right.controller == self.class.controller_name and
23 + (right.action == 'all' or right.action == action_name)
24 + }
25 + }
26 + flash[:notice] = 'You are not authorized to view the page you requested'
27 + #request.env['HTTP_REFERER'] ? (redirect_to :back) : (redirect_to :controller => 'login')
28 + redirect_to :controller => 'login'
29 + return false
30 + end
31 + end
32 +
33 + end
34 +
@@ -0,0 +1,19
1 + class LoginController < ApplicationController
2 +
3 + def index
4 + # show login screen
5 + reset_session
6 + redirect_to :controller => 'main', :action => 'login'
7 + end
8 +
9 + def login
10 + if user = User.authenticate(params[:login], params[:password])
11 + session[:user_id] = user.id
12 + redirect_to :controller => 'main', :action => 'list'
13 + else
14 + flash[:notice] = 'Wrong password'
15 + redirect_to :controller => 'main', :action => 'login'
16 + end
17 + end
18 +
19 + end
@@ -0,0 +1,65
1 + class MainController < ApplicationController
2 +
3 + before_filter :authenticate, :except => [:index, :login]
4 +
5 + verify :method => :post, :only => [:submit],
6 + :redirect_to => { :action => :index }
7 +
8 + def index
9 + end
10 +
11 + def login
12 + reset_session
13 + end
14 +
15 + def list
16 + @problems = Problem.find_available_problems
17 + @prob_submissions = Array.new
18 + @user = User.find(session[:user_id])
19 + @problems.each do |p|
20 + c, sub = Submission.find_by_user_and_problem(@user.id,p.id)
21 + @prob_submissions << [c,sub]
22 + end
23 + end
24 +
25 + def submit
26 + submission = Submission.new(params[:submission])
27 + submission.user_id = session[:user_id]
28 + submission.language_id = 0
29 + source = params['file'].read
30 + if source.length > 100_000
31 + flash[:notice] = 'Error: file too long'
32 + elsif (lang = Submission.find_language_in_source(source))==nil
33 + flash[:notice] = 'Error: cannot determine language used'
34 + elsif ((submission.problem_id==-1) and
35 + !(problem=Submission.find_problem_in_source(source)))
36 + flash[:notice] = 'Error: cannot determine problem submitted'
37 + elsif ((submission.problem_id==-1) and
38 + (problem.available == false))
39 + flash[:notice] = 'Error: problem is not available'
40 + else
41 + submission.problem_id = problem.id if submission.problem_id == -1
42 + submission.source = source
43 + submission.language_id = lang.id
44 + submission.submitted_at = Time.new
45 + if submission.save == false
46 + flash[:notice] = 'Error saving your submission'
47 + elsif Task.create(:submission_id => submission.id) == false
48 + flash[:notice] = 'Error adding your submission to task queue'
49 + end
50 + end
51 + redirect_to :action => 'list'
52 + end
53 +
54 + def get_source
55 + submission = Submission.find(params[:id])
56 + if submission.user_id == session[:user_id]
57 + fname = submission.problem.name + '.' + submission.language.ext
58 + send_data(submission.source,
59 + {:filename => fname,
60 + :type => 'text/plain'})
61 + else
62 + flash[:notice] = 'Error viewing source'
63 + end
64 + end
65 + end
@@ -0,0 +1,68
1 + class ProblemsController < ApplicationController
2 +
3 + before_filter :authenticate, :authorization
4 +
5 + def index
6 + list
7 + render :action => 'list'
8 + end
9 +
10 + # GETs should be safe (see http://www.w3.org/2001/tag/doc/whenToUseGet.html)
11 + verify :method => :post, :only => [ :destroy, :create, :update ],
12 + :redirect_to => { :action => :list }
13 +
14 + def list
15 + @problem_pages, @problems = paginate(:problems,
16 + :per_page => 10,
17 + :order => 'date_added DESC')
18 + end
19 +
20 + def show
21 + @problem = Problem.find(params[:id])
22 + end
23 +
24 + def new
25 + @problem = Problem.new
26 + end
27 +
28 + def create
29 + @problem = Problem.new(params[:problem])
30 + if @problem.save
31 + flash[:notice] = 'Problem was successfully created.'
32 + redirect_to :action => 'list'
33 + else
34 + render :action => 'new'
35 + end
36 + end
37 +
38 + def edit
39 + @problem = Problem.find(params[:id])
40 + end
41 +
42 + def update
43 + @problem = Problem.find(params[:id])
44 + if @problem.update_attributes(params[:problem])
45 + flash[:notice] = 'Problem was successfully updated.'
46 + redirect_to :action => 'show', :id => @problem
47 + else
48 + render :action => 'edit'
49 + end
50 + end
51 +
52 + def destroy
53 + Problem.find(params[:id]).destroy
54 + redirect_to :action => 'list'
55 + end
56 +
57 + def toggle_avail
58 + problem = Problem.find(params[:id])
59 + problem.available = !(problem.available)
60 + problem.save
61 + redirect_to :action => 'list'
62 + end
63 +
64 + def stat
65 + @problem = Problem.find(params[:id])
66 + @submissions = Submission.find_last_by_problem(params[:id])
67 + end
68 + end
@@ -0,0 +1,73
1 + class UserAdminController < ApplicationController
2 +
3 + before_filter :authenticate, :authorization
4 +
5 + def index
6 + list
7 + render :action => 'list'
8 + end
9 +
10 + # GETs should be safe (see http://www.w3.org/2001/tag/doc/whenToUseGet.html)
11 + verify :method => :post, :only => [ :destroy, :create, :update ],
12 + :redirect_to => { :action => :list }
13 +
14 + def list
15 + @user_pages, @users = paginate :users, :per_page => 50
16 + end
17 +
18 + def show
19 + @user = User.find(params[:id])
20 + end
21 +
22 + def new
23 + @user = User.new
24 + end
25 +
26 + def create
27 + @user = User.new(params[:user])
28 + if @user.save
29 + flash[:notice] = 'User was successfully created.'
30 + redirect_to :action => 'list'
31 + else
32 + render :action => 'new'
33 + end
34 + end
35 +
36 + def edit
37 + @user = User.find(params[:id])
38 + end
39 +
40 + def update
41 + @user = User.find(params[:id])
42 + if @user.update_attributes(params[:user])
43 + flash[:notice] = 'User was successfully updated.'
44 + redirect_to :action => 'show', :id => @user
45 + else
46 + render :action => 'edit'
47 + end
48 + end
49 +
50 + def destroy
51 + User.find(params[:id]).destroy
52 + redirect_to :action => 'list'
53 + end
54 +
55 + def user_stat
56 + @problems = Problem.find_available_problems
57 + @users = User.find(:all)
58 + @scorearray = Array.new
59 + @users.each do |u|
60 + ustat = Array.new
61 + ustat[0] = u.login
62 + @problems.each do |p|
63 + c, sub = Submission.find_by_user_and_problem(u.id,p.id)
64 + if c!=0
65 + ustat << sub.points
66 + else
67 + ustat << 0
68 + end
69 + end
70 + @scorearray << ustat
71 + end
72 + end
73 + end
@@ -0,0 +1,2
1 + class UsersController < ApplicationController
2 + end
@@ -0,0 +1,3
1 + # Methods added to this helper will be available to all templates in the application.
2 + module ApplicationHelper
3 + end
@@ -0,0 +1,2
1 + module LoginHelper
2 + end
@@ -0,0 +1,61
1 + module MainHelper
2 +
3 + def user_options
4 + options = ''
5 + user = User.find(session[:user_id])
6 + if user.admin?
7 + options = options + ' ' +
8 + link_to('[Problem admin]',
9 + {:controller => 'problems', :action => 'index'})
10 + options = options + ' ' +
11 + link_to('[User admin]',
12 + {:controller => 'user_admin', :action => 'index'})
13 + end
14 + options = options + ' ' +
15 + link_to('[Log out]', {:controller => 'main', :action => 'login'})
16 + options
17 + end
18 +
19 + def format_short_time(time)
20 + now = Time.now
21 + st = ''
22 + if (time.yday != now.yday) or
23 + (time.year != now.year)
24 + st = time.strftime("%x")
25 + end
26 + st + time.strftime("%X")
27 + end
28 +
29 + def format_compiler_msg(sub)
30 + <<cmpmsg
31 + <div>
32 + <div><a href="#" onClick="n = this.parentNode.parentNode.lastChild;
33 + if(n.style.display == 'none') { n.style.display = 'block'; }
34 + else {n.style.display ='none'; } return false;">
35 + Compiler message</a> (click to see)</div>
36 + <div style="display: none">
37 + <div class="compilermsgbody" style="border: thin solid grey; margin: 2px">
38 + #{h(sub.compiler_message).gsub(/\n/,'<br/>')}
39 + </div>
40 + </div></div>
41 + cmpmsg
42 + end
43 +
44 + def format_submission(sub, count)
45 + msg = "#{count} submission(s)<br />"
46 + if count>0
47 + msg = msg + "Last on " +
48 + format_short_time(sub.submitted_at) + ' ' +
49 + link_to('[source]',{:action => 'get_source', :id => sub.id}) +
50 + "<br />"
51 + end
52 + if sub!=nil and sub.graded_at!=nil
53 + msg = msg + 'Graded at ' + format_short_time(sub.graded_at) + ', score: '+
54 + sub.points.to_s +
55 + ' [' + sub.grader_comment + "]<br />" +
56 + format_compiler_msg(sub)
57 + end
58 + msg
59 + end
60 +
61 + end
@@ -0,0 +1,2
1 + module ProblemsHelper
2 + end
@@ -0,0 +1,2
1 + module UserAdminHelper
2 + end
@@ -0,0 +1,2
1 + module UsersHelper
2 + end
@@ -0,0 +1,2
1 + class Language < ActiveRecord::Base
2 + end
@@ -0,0 +1,7
1 + class Problem < ActiveRecord::Base
2 +
3 + def self.find_available_problems
4 + find(:all, :conditions => {:available => true})
5 + end
6 +
7 + end
@@ -0,0 +1,3
1 + class Right < ActiveRecord::Base
2 + has_and_belongs_to_many :roles
3 + end
@@ -0,0 +1,4
1 + class Role < ActiveRecord::Base
2 + has_and_belongs_to_many :users
3 + has_and_belongs_to_many :rights
4 + end
@@ -0,0 +1,64
1 + class Submission < ActiveRecord::Base
2 +
3 + belongs_to :language
4 + belongs_to :problem
5 +
6 + def self.find_by_user_and_problem(user_id, problem_id)
7 + subcount = count(:conditions => "user_id = #{user_id} AND problem_id = #{problem_id}")
8 + if subcount != 0
9 + last_sub = find(:first,
10 + :conditions => {:user_id => user_id,
11 + :problem_id => problem_id},
12 + :order => 'submitted_at DESC')
13 + else
14 + last_sub = nil
15 + end
16 + return subcount, last_sub
17 + end
18 +
19 + def self.find_last_by_problem(problem_id)
20 + # need to put in SQL command, maybe there's a better way
21 + Submission.find_by_sql("SELECT * FROM submissions " +
22 + "WHERE id = " +
23 + "(SELECT MAX(id) FROM submissions AS subs " +
24 + "WHERE subs.user_id = submissions.user_id AND " +
25 + "problem_id = " + problem_id.to_s + " " +
26 + "GROUP BY user_id)")
27 + end
28 +
29 + def self.find_option_in_source(option, source)
30 + i = 0
31 + source.each_line do |s|
32 + if s =~ option
33 + words = s.split
34 + return words[1]
35 + end
36 + i = i + 1
37 + if i==10
38 + return nil
39 + end
40 + end
41 + return nil
42 + end
43 +
44 + def self.find_language_in_source(source)
45 + langopt = find_option_in_source(/^LANG:/,source)
46 + if language = Language.find_by_name(langopt)
47 + return language
48 + elsif language = Language.find_by_pretty_name(langopt)
49 + return language
50 + else
51 + return nil
52 + end
53 + end
54 +
55 + def self.find_problem_in_source(source)
56 + prob_opt = find_option_in_source(/^TASK:/,source)
57 + if problem = Problem.find_by_name(prob_opt)
58 + return problem
59 + else
60 + return nil
61 + end
62 + end
63 +
64 + end
@@ -0,0 +1,2
1 + class Task < ActiveRecord::Base
2 + end
@@ -0,0 +1,45
1 + require 'digest/sha1'
2 +
3 + class User < ActiveRecord::Base
4 +
5 + has_and_belongs_to_many :roles
6 +
7 + validates_presence_of :login
8 + validates_presence_of :full_name
9 +
10 + validates_presence_of :password, :if => :password_required?
11 + validates_length_of :password, :within => 4..20, :if => :password_required?
12 + validates_confirmation_of :password, :if => :password_required?
13 +
14 + attr_accessor :password
15 +
16 + before_save :encrypt_new_password
17 +
18 + def self.authenticate(login, password)
19 + user = find_by_login(login)
20 + return user if user && user.authenticated?(password)
21 + end
22 +
23 + def authenticated?(password)
24 + hashed_password == encrypt(password,salt)
25 + end
26 +
27 + def admin?
28 + self.roles.detect {|r| r.name == 'admin' }
29 + end
30 +
31 + # protected
32 + def encrypt_new_password
33 + return if password.blank?
34 + self.salt = (10+rand(90)).to_s
35 + self.hashed_password = encrypt(password,salt)
36 + end
37 +
38 + def password_required?
39 + hashed_password.blank? || !password.blank?
40 + end
41 +
42 + def encrypt(string,salt)
43 + Digest::SHA1.hexdigest(salt + string)
44 + end
45 + end
@@ -0,0 +1,15
1 + <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
2 + "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
3 +
4 + <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
5 + <head>
6 + <meta http-equiv="content-type" content="text/html;charset=UTF-8" />
7 + <title>Grader!</title>
8 + <%= stylesheet_link_tag 'application' %>
9 + </head>
10 + <body>
11 +
12 + <%= yield %>
13 +
14 + </body>
15 + </html>
@@ -0,0 +1,17
1 + <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
2 + "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
3 +
4 + <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
5 + <head>
6 + <meta http-equiv="content-type" content="text/html;charset=UTF-8" />
7 + <title>Problems: <%= controller.action_name %></title>
8 + <%= stylesheet_link_tag 'scaffold' %>
9 + </head>
10 + <body>
11 +
12 + <p style="color: green"><%= flash[:notice] %></p>
13 +
14 + <%= yield %>
15 +
16 + </body>
17 + </html>
@@ -0,0 +1,17
1 + <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
2 + "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
3 +
4 + <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
5 + <head>
6 + <meta http-equiv="content-type" content="text/html;charset=UTF-8" />
7 + <title>UserAdmin: <%= controller.action_name %></title>
8 + <%= stylesheet_link_tag 'scaffold' %>
9 + </head>
10 + <body>
11 +
12 + <p style="color: green"><%= flash[:notice] %></p>
13 +
14 + <%= yield %>
15 +
16 + </body>
17 + </html>
@@ -0,0 +1,17
1 + <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
2 + "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
3 +
4 + <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
5 + <head>
6 + <meta http-equiv="content-type" content="text/html;charset=UTF-8" />
7 + <title>Users: <%= controller.action_name %></title>
8 + <%= stylesheet_link_tag 'scaffold' %>
9 + </head>
10 + <body>
11 +
12 + <p style="color: green"><%= flash[:notice] %></p>
13 +
14 + <%= yield %>
15 +
16 + </body>
17 + </html>
@@ -0,0 +1,5
1 + <h1>Grader</h1>
2 +
3 + Welcome... first you need to
4 + <%= link_to 'login', :controller => 'main', :action => 'login' %>
5 + to see problem list.
@@ -0,0 +1,38
1 + <h1>Hello <%=h @user.full_name %></h1>
2 +
3 + <div class="usermenu">
4 + <%= user_options %>
5 + </div>
6 +
7 + <hr>
8 +
9 + <p style="color: red"><%= flash[:notice] %></p>
10 +
11 + <div class="problist">
12 + <% i = 0 %>
13 + <% @problems.each do |p| %>
14 + <div class="problist-each">
15 + <div class="probname">
16 + <%= "#{i+1}: #{p.full_name} (#{p.name})" %>
17 + </div>
18 + <div class="subinfo">
19 + <%= format_submission(@prob_submissions[i][1],
20 + @prob_submissions[i][0]) %>
21 + </div>
22 + </div>
23 + <% i = i+1 %>
24 + <% end %>
25 + </div>
26 +
27 + <br />
28 + <hr />
29 + <br />
30 +
31 + <% form_tag({:action => 'submit'}, :multipart => true) do %>
32 + Problem: <%= select 'submission', 'problem_id',
33 + [['Specified in header','-1']] +
34 + @problems.collect {|p| [p.full_name, p.id]},
35 + :selected => '-1' %>
36 + File: <%= file_field_tag 'file' %>
37 + <%= submit_tag 'Submit' %>
38 + <% end %>
@@ -0,0 +1,19
1 + <h1>Login</h1>
2 +
3 + <% if flash[:notice] %>
4 + <hr>
5 + <b><%= flash[:notice] %></b>
6 + <hr>
7 + <% end %>
8 +
9 + <% form_tag :controller => 'login', :action => 'login' do %>
10 + <table>
11 + <tr>
12 + <td align="right">User name:</td><td><%= text_field_tag 'login' %></td>
13 + </tr>
14 + <tr>
15 + <td align="right">Password:</td><td><%= password_field_tag %></td>
16 + </tr>
17 + </table>
18 + <%= submit_tag 'Login' %>
19 + <% end %>
@@ -0,0 +1,19
1 + <%= error_messages_for 'problem' %>
2 +
3 + <!--[form:problem]-->
4 + <p><label for="problem_name">Name</label><br/>
5 + <%= text_field 'problem', 'name' %></p>
6 +
7 + <p><label for="problem_full_name">Full name</label><br/>
8 + <%= text_field 'problem', 'full_name' %></p>
9 +
10 + <p><label for="problem_full_score">Full score</label><br/>
11 + <%= text_field 'problem', 'full_score' %></p>
12 +
13 + <p><label for="problem_date_added">Date added</label><br/>
14 + <%= date_select 'problem', 'date_added' %></p>
15 +
16 + <p><label for="problem_available">Available</label><br/>
17 + <select id="problem_available" name="problem[available]"><option value="false">False</option><option value="true">True</option></select></p>
18 + <!--[eoform:problem]-->
19 +
@@ -0,0 +1,9
1 + <h1>Editing problem</h1>
2 +
3 + <% form_tag :action => 'update', :id => @problem do %>
4 + <%= render :partial => 'form' %>
5 + <%= submit_tag 'Edit' %>
6 + <% end %>
7 +
8 + <%= link_to 'Show', :action => 'show', :id => @problem %> |
9 + <%= link_to 'Back', :action => 'list' %>
@@ -0,0 +1,33
1 + <h1>Listing problems</h1>
2 +
3 + <div class="usermenu">
4 + <%= link_to 'Main', :controller => 'main', :action => 'list' %>
5 + </div>
6 +
7 + <table>
8 + <tr>
9 + <% for column in Problem.content_columns %>
10 + <th><%= column.human_name %></th>
11 + <% end %>
12 + </tr>
13 +
14 + <% for problem in @problems %>
15 + <tr>
16 + <% for column in Problem.content_columns %>
17 + <td><%=h problem.send(column.name) %></td>
18 + <% end %>
19 + <td><%= link_to '[Toggle]', :action => 'toggle_avail', :id => problem.id %></td>
20 + <td><%= link_to '[Stat]', :action => 'stat', :id => problem.id %></td>
21 + <td><%= link_to '[Show]', :action => 'show', :id => problem %></td>
22 + <td><%= link_to '[Edit]', :action => 'edit', :id => problem %></td>
23 + <td><%= link_to '[Destroy]', { :action => 'destroy', :id => problem }, :confirm => 'Are you sure?', :method => :post %></td>
24 + </tr>
25 + <% end %>
26 + </table>
27 +
28 + <%= link_to 'Previous page', { :page => @problem_pages.current.previous } if @problem_pages.current.previous %>
29 + <%= link_to 'Next page', { :page => @problem_pages.current.next } if @problem_pages.current.next %>
30 +
31 + <br />
32 +
33 + <%= link_to 'New problem', :action => 'new' %>
@@ -0,0 +1,8
1 + <h1>New problem</h1>
2 +
3 + <% form_tag :action => 'create' do %>
4 + <%= render :partial => 'form' %>
5 + <%= submit_tag "Create" %>
6 + <% end %>
7 +
8 + <%= link_to 'Back', :action => 'list' %>
@@ -0,0 +1,8
1 + <% for column in Problem.content_columns %>
2 + <p>
3 + <b><%= column.human_name %>:</b> <%=h @problem.send(column.name) %>
4 + </p>
5 + <% end %>
6 +
7 + <%= link_to 'Edit', :action => 'edit', :id => @problem %> |
8 + <%= link_to 'Back', :action => 'list' %>
@@ -0,0 +1,23
1 + <h1>Problem stat: <%= @problem.name %></h1>
2 +
3 + <div class="usermenu">
4 + <%= link_to 'Main', :controller => 'main', :action => 'list' %>
5 + </div>
6 +
7 + <i>This is just a hack. Really not efficient.</i><br/><br/>
8 +
9 + <% if @submissions!=nil %>
10 + <table border="1">
11 + <tr><td>user_id</td><td>submitted_at</td><td>points</td><td>comment</td></tr>
12 + <% @submissions.each do |sub| %>
13 + <tr>
14 + <td><%= sub.user_id %></td>
15 + <td><%= sub.submitted_at.to_s %></td>
16 + <td><%= sub.points %></td>
17 + <td><div style="font-family: monospace"><%= sub.grader_comment %></div></td>
18 + </tr>
19 + <% end %>
20 + </table>
21 + <% else %>
22 + No submission
23 + <% end %>
@@ -0,0 +1,19
1 + <%= error_messages_for 'user' %>
2 +
3 + <!--[form:user]-->
4 + <p><label for="user_name">Login</label><br/>
5 + <%= text_field 'user', 'login' %></p>
6 +
7 + <p><label for="user_name">Full name</label><br/>
8 + <%= text_field 'user', 'full_name' %></p>
9 +
10 + <p><label for="password">Password</label><br/>
11 + <%= password_field 'user', 'password' %></p>
12 +
13 + <p><label for="password_confirmation">Password (confirm)</label><br/>
14 + <%= password_field 'user', 'password_confirmation' %></p>
15 +
16 + <p><label for="user_alias">Alias</label><br/>
17 + <%= text_field 'user', 'alias' %></p>
18 + <!--[eoform:user]-->
19 +
@@ -0,0 +1,9
1 + <h1>Editing user</h1>
2 +
3 + <% form_tag :action => 'update', :id => @user do %>
4 + <%= render :partial => 'form' %>
5 + <%= submit_tag 'Edit' %>
6 + <% end %>
7 +
8 + <%= link_to 'Show', :action => 'show', :id => @user %> |
9 + <%= link_to 'Back', :action => 'list' %>
@@ -0,0 +1,55
1 + <h1>Listing users</h1>
2 +
3 + <div class="usermenu">
4 + <%= link_to 'Stat', :action => 'user_stat' %>
5 + <%= link_to 'Main', :controller => 'main', :action => 'list' %>
6 + </div>
7 +
8 + <div style="border: solid 1px; margin: 2px">
9 + <b>Quick add</b>
10 + <% form_tag :action => 'create' do %>
11 + <table border="0">
12 + <tr>
13 + <td><label for="user_name">Login</label></td>
14 + <td><label for="user_name">Full name</label></td>
15 + <td><label for="user_alias">Alias</label></td>
16 + <td><label for="password">Password</label></td>
17 + <td><label for="password_confirmation">confirm</label></td>
18 + </tr>
19 + <tr>
20 + <td><%= text_field 'user', 'login', :size => 10 %></td>
21 + <td><%= text_field 'user', 'full_name', :size => 30 %></td>
22 + <td><%= text_field 'user', 'alias', :size => 10 %></td>
23 + <td><%= password_field 'user', 'password', :size => 10 %></td>
24 + <td><%= password_field 'user', 'password_confirmation', :size => 10 %></td>
25 + <td><%= submit_tag "Create" %></td>
26 + </tr></table>
27 + <% end %>
28 +
29 + </div>
30 +
31 + <table>
32 + <tr>
33 + <% for column in User.content_columns %>
34 + <th><%= column.human_name %></th>
35 + <% end %>
36 + </tr>
37 +
38 + <% for user in @users %>
39 + <tr>
40 + <% for column in User.content_columns %>
41 + <td><%=h user.send(column.name) %></td>
42 + <% end %>
43 + <td><%= link_to 'Show', :action => 'show', :id => user %></td>
44 + <td><%= link_to 'Edit', :action => 'edit', :id => user %></td>
45 + <td><%= link_to 'Destroy', { :action => 'destroy', :id => user }, :confirm => 'Are you sure?', :method => :post %></td>
46 + </tr>
47 + <% end %>
48 + </table>
49 +
50 + <%= link_to 'Previous page', { :page => @user_pages.current.previous } if @user_pages.current.previous %>
51 + <%= link_to 'Next page', { :page => @user_pages.current.next } if @user_pages.current.next %>
52 +
53 + <br />
54 +
55 + <%= link_to 'New user', :action => 'new' %>
@@ -0,0 +1,8
1 + <h1>New user</h1>
2 +
3 + <% form_tag :action => 'create' do %>
4 + <%= render :partial => 'form' %>
5 + <%= submit_tag "Create" %>
6 + <% end %>
7 +
8 + <%= link_to 'Back', :action => 'list' %>
@@ -0,0 +1,8
1 + <% for column in User.content_columns %>
2 + <p>
3 + <b><%= column.human_name %>:</b> <%=h @user.send(column.name) %>
4 + </p>
5 + <% end %>
6 +
7 + <%= link_to 'Edit', :action => 'edit', :id => @user %> |
8 + <%= link_to 'Back', :action => 'list' %>
@@ -0,0 +1,26
1 + <h1>User stat</h1>
2 +
3 + <div class="usermenu">
4 + <%= link_to 'List', :action => 'list' %>
5 + <%= link_to 'Main', :controller => 'main', :action => 'list' %>
6 + </div>
7 +
8 +
9 + <table border="1">
10 + <tr><td>User</td>
11 + <% @problems.each do |p| %>
12 + <td><%= p.name %></td>
13 + <% end %>
14 + <td>Total</td>
15 + </tr>
16 + <% @scorearray.each do |sc| %>
17 + <tr>
18 + <% total = 0 %>
19 + <% sc.each do |i| %>
20 + <td><%= i %></td>
21 + <% total += i.to_i %>
22 + <% end %>
23 + <td><%= total %></td>
24 + </tr>
25 + <% end %>
26 + </table>
@@ -0,0 +1,19
1 + <%= error_messages_for 'user' %>
2 +
3 + <!--[form:user]-->
4 + <p><label for="user_name">Login</label><br/>
5 + <%= text_field 'user', 'login' %></p>
6 +
7 + <p><label for="user_name">Full name</label><br/>
8 + <%= text_field 'user', 'full_name' %></p>
9 +
10 + <p><label for="password">Password</label><br/>
11 + <%= password_field 'user', 'password' %></p>
12 +
13 + <p><label for="password_confirmation">Password (confirm)</label><br/>
14 + <%= password_field 'user', 'password_confirmation' %></p>
15 +
16 + <p><label for="user_alias">Alias</label><br/>
17 + <%= text_field 'user', 'alias' %></p>
18 + <!--[eoform:user]-->
19 +
@@ -0,0 +1,9
1 + <h1>Editing user</h1>
2 +
3 + <% form_tag :action => 'update', :id => @user do %>
4 + <%= render :partial => 'form' %>
5 + <%= submit_tag 'Edit' %>
6 + <% end %>
7 +
8 + <%= link_to 'Show', :action => 'show', :id => @user %> |
9 + <%= link_to 'Back', :action => 'list' %>
@@ -0,0 +1,27
1 + <h1>Listing users</h1>
2 +
3 + <table>
4 + <tr>
5 + <% for column in User.content_columns %>
6 + <th><%= column.human_name %></th>
7 + <% end %>
8 + </tr>
9 +
10 + <% for user in @users %>
11 + <tr>
12 + <% for column in User.content_columns %>
13 + <td><%=h user.send(column.name) %></td>
14 + <% end %>
15 + <td><%= link_to 'Show', :action => 'show', :id => user %></td>
16 + <td><%= link_to 'Edit', :action => 'edit', :id => user %></td>
17 + <td><%= link_to 'Destroy', { :action => 'destroy', :id => user }, :confirm => 'Are you sure?', :method => :post %></td>
18 + </tr>
19 + <% end %>
20 + </table>
21 +
22 + <%= link_to 'Previous page', { :page => @user_pages.current.previous } if @user_pages.current.previous %>
23 + <%= link_to 'Next page', { :page => @user_pages.current.next } if @user_pages.current.next %>
24 +
25 + <br />
26 +
27 + <%= link_to 'New user', :action => 'new' %>
@@ -0,0 +1,8
1 + <h1>New user</h1>
2 +
3 + <% form_tag :action => 'create' do %>
4 + <%= render :partial => 'form' %>
5 + <%= submit_tag "Create" %>
6 + <% end %>
7 +
8 + <%= link_to 'Back', :action => 'list' %>
@@ -0,0 +1,8
1 + <% for column in User.content_columns %>
2 + <p>
3 + <b><%= column.human_name %>:</b> <%=h @user.send(column.name) %>
4 + </p>
5 + <% end %>
6 +
7 + <%= link_to 'Edit', :action => 'edit', :id => @user %> |
8 + <%= link_to 'Back', :action => 'list' %>
@@ -0,0 +1,45
1 + # Don't change this file. Configuration is done in config/environment.rb and config/environments/*.rb
2 +
3 + unless defined?(RAILS_ROOT)
4 + root_path = File.join(File.dirname(__FILE__), '..')
5 +
6 + unless RUBY_PLATFORM =~ /(:?mswin|mingw)/
7 + require 'pathname'
8 + root_path = Pathname.new(root_path).cleanpath(true).to_s
9 + end
10 +
11 + RAILS_ROOT = root_path
12 + end
13 +
14 + unless defined?(Rails::Initializer)
15 + if File.directory?("#{RAILS_ROOT}/vendor/rails")
16 + require "#{RAILS_ROOT}/vendor/rails/railties/lib/initializer"
17 + else
18 + require 'rubygems'
19 +
20 + environment_without_comments = IO.readlines(File.dirname(__FILE__) + '/environment.rb').reject { |l| l =~ /^#/ }.join
21 + environment_without_comments =~ /[^#]RAILS_GEM_VERSION = '([\d.]+)'/
22 + rails_gem_version = $1
23 +
24 + if version = defined?(RAILS_GEM_VERSION) ? RAILS_GEM_VERSION : rails_gem_version
25 + # Asking for 1.1.6 will give you 1.1.6.5206, if available -- makes it easier to use beta gems
26 + rails_gem = Gem.cache.search('rails', "~>#{version}.0").sort_by { |g| g.version.version }.last
27 +
28 + if rails_gem
29 + gem "rails", "=#{rails_gem.version.version}"
30 + require rails_gem.full_gem_path + '/lib/initializer'
31 + else
32 + STDERR.puts %(Cannot find gem for Rails ~>#{version}.0:
33 + Install the missing gem with 'gem install -v=#{version} rails', or
34 + change environment.rb to define RAILS_GEM_VERSION with your desired version.
35 + )
36 + exit 1
37 + end
38 + else
39 + gem "rails"
40 + require 'initializer'
41 + end
42 + end
43 +
44 + Rails::Initializer.run(:set_load_path)
45 + end
@@ -0,0 +1,36
1 + # MySQL (default setup). Versions 4.1 and 5.0 are recommended.
2 + #
3 + # Install the MySQL driver:
4 + # gem install mysql
5 + # On MacOS X:
6 + # gem install mysql -- --include=/usr/local/lib
7 + # On Windows:
8 + # gem install mysql
9 + # Choose the win32 build.
10 + # Install MySQL and put its /bin directory on your path.
11 + #
12 + # And be sure to use new-style password hashing:
13 + # http://dev.mysql.com/doc/refman/5.0/en/old-client.html
14 + development:
15 + adapter: mysql
16 + database: ioi
17 + username: ioi
18 + password: ioi
19 + host: localhost
20 +
21 + # Warning: The database defined as 'test' will be erased and
22 + # re-generated from your development database when you run 'rake'.
23 + # Do not set this db to the same as development or production.
24 + test:
25 + adapter: mysql
26 + database: grader_test
27 + username: root
28 + password:
29 + host: localhost
30 +
31 + production:
32 + adapter: mysql
33 + database: ioi
34 + username: ioi
35 + password: mioisql
36 + host: localhost
@@ -0,0 +1,60
1 + # Be sure to restart your web server when you modify this file.
2 +
3 + # Uncomment below to force Rails into production mode when
4 + # you don't control web/app server and can't set it the proper way
5 + # ENV['RAILS_ENV'] ||= 'production'
6 +
7 + # Specifies gem version of Rails to use when vendor/rails is not present
8 + RAILS_GEM_VERSION = '1.2.4' unless defined? RAILS_GEM_VERSION
9 +
10 + # Bootstrap the Rails environment, frameworks, and default configuration
11 + require File.join(File.dirname(__FILE__), 'boot')
12 +
13 + Rails::Initializer.run do |config|
14 + # Settings in config/environments/* take precedence over those specified here
15 +
16 + # Skip frameworks you're not going to use (only works if using vendor/rails)
17 + # config.frameworks -= [ :action_web_service, :action_mailer ]
18 +
19 + # Only load the plugins named here, by default all plugins in vendor/plugins are loaded
20 + # config.plugins = %W( exception_notification ssl_requirement )
21 +
22 + # Add additional load paths for your own custom dirs
23 + # config.load_paths += %W( #{RAILS_ROOT}/extras )
24 +
25 + # Force all environments to use the same logger level
26 + # (by default production uses :info, the others :debug)
27 + # config.log_level = :debug
28 +
29 + # Use the database for sessions instead of the file system
30 + # (create the session table with 'rake db:sessions:create')
31 + config.action_controller.session_store = :active_record_store
32 +
33 + # Use SQL instead of Active Record's schema dumper when creating the test database.
34 + # This is necessary if your schema can't be completely dumped by the schema dumper,
35 + # like if you have constraints or database-specific column types
36 + # config.active_record.schema_format = :sql
37 +
38 + # Activate observers that should always be running
39 + # config.active_record.observers = :cacher, :garbage_collector
40 +
41 + # Make Active Record use UTC-base instead of local time
42 + config.active_record.default_timezone = :utc
43 +
44 + # See Rails::Configuration for more options
45 + end
46 +
47 + # Add new inflection rules using the following format
48 + # (all these examples are active by default):
49 + # Inflector.inflections do |inflect|
50 + # inflect.plural /^(ox)$/i, '\1en'
51 + # inflect.singular /^(ox)en/i, '\1'
52 + # inflect.irregular 'person', 'people'
53 + # inflect.uncountable %w( fish sheep )
54 + # end
55 +
56 + # Add new mime types for use in respond_to blocks:
57 + # Mime::Type.register "text/richtext", :rtf
58 + # Mime::Type.register "application/x-mobile", :mobile
59 +
60 + # Include your application configuration below
@@ -0,0 +1,21
1 + # Settings specified here will take precedence over those in config/environment.rb
2 +
3 + # In the development environment your application's code is reloaded on
4 + # every request. This slows down response time but is perfect for development
5 + # since you don't have to restart the webserver when you make code changes.
6 + config.cache_classes = false
7 +
8 + # Log error messages when you accidentally call methods on nil.
9 + config.whiny_nils = true
10 +
11 + # Enable the breakpoint server that script/breakpointer connects to
12 + config.breakpoint_server = true
13 +
14 + # Show full error reports and disable caching
15 + config.action_controller.consider_all_requests_local = true
16 + config.action_controller.perform_caching = false
17 + config.action_view.cache_template_extensions = false
18 + config.action_view.debug_rjs = true
19 +
20 + # Don't care if the mailer can't send
21 + config.action_mailer.raise_delivery_errors = false
@@ -0,0 +1,18
1 + # Settings specified here will take precedence over those in config/environment.rb
2 +
3 + # The production environment is meant for finished, "live" apps.
4 + # Code is not reloaded between requests
5 + config.cache_classes = true
6 +
7 + # Use a different logger for distributed setups
8 + # config.logger = SyslogLogger.new
9 +
10 + # Full error reports are disabled and caching is turned on
11 + config.action_controller.consider_all_requests_local = false
12 + config.action_controller.perform_caching = true
13 +
14 + # Enable serving of images, stylesheets, and javascripts from an asset server
15 + # config.action_controller.asset_host = "http://assets.example.com"
16 +
17 + # Disable delivery errors, bad email addresses will be ignored
18 + # config.action_mailer.raise_delivery_errors = false
@@ -0,0 +1,19
1 + # Settings specified here will take precedence over those in config/environment.rb
2 +
3 + # The test environment is used exclusively to run your application's
4 + # test suite. You never need to work with it otherwise. Remember that
5 + # your test database is "scratch space" for the test suite and is wiped
6 + # and recreated between test runs. Don't rely on the data there!
7 + config.cache_classes = true
8 +
9 + # Log error messages when you accidentally call methods on nil.
10 + config.whiny_nils = true
11 +
12 + # Show full error reports and disable caching
13 + config.action_controller.consider_all_requests_local = true
14 + config.action_controller.perform_caching = false
15 +
16 + # Tell ActionMailer not to deliver emails to the real world.
17 + # The :test delivery method accumulates sent emails in the
18 + # ActionMailer::Base.deliveries array.
19 + config.action_mailer.delivery_method = :test No newline at end of file
@@ -0,0 +1,23
1 + ActionController::Routing::Routes.draw do |map|
2 + # The priority is based upon order of creation: first created -> highest priority.
3 +
4 + # Sample of regular route:
5 + # map.connect 'products/:id', :controller => 'catalog', :action => 'view'
6 + # Keep in mind you can assign values other than :controller and :action
7 +
8 + # Sample of named route:
9 + # map.purchase 'products/:id/purchase', :controller => 'catalog', :action => 'purchase'
10 + # This route can be invoked with purchase_url(:id => product.id)
11 +
12 + # You can have the root of your site routed by hooking up ''
13 + # -- just remember to delete public/index.html.
14 + # map.connect '', :controller => "welcome"
15 +
16 + # Allow downloading Web Service WSDL as a file with an extension
17 + # instead of a file named 'wsdl'
18 + map.connect ':controller/service.wsdl', :action => 'wsdl'
19 +
20 + # Install the default route as the lowest priority.
21 + map.connect ':controller/:action/:id.:format'
22 + map.connect ':controller/:action/:id'
23 + end
@@ -0,0 +1,17
1 + class CreateUsers < ActiveRecord::Migration
2 + def self.up
3 + create_table :users do |t|
4 + t.column :login, :string, :limit => 10
5 + t.column :full_name, :string
6 + t.column :hashed_password, :string
7 + t.column :salt, :string, :limit => 5
8 + t.column :alias, :string
9 + end
10 + # force unique name
11 + add_index :users, :login, :unique => true
12 + end
13 +
14 + def self.down
15 + drop_table :users
16 + end
17 + end
@@ -0,0 +1,15
1 + class CreateProblems < ActiveRecord::Migration
2 + def self.up
3 + create_table :problems do |t|
4 + t.column :name, :string, :limit => 30
5 + t.column :full_name, :string
6 + t.column :full_score, :integer
7 + t.column :date_added, :date
8 + t.column :available, :boolean
9 + end
10 + end
11 +
12 + def self.down
13 + drop_table :problems
14 + end
15 + end
@@ -0,0 +1,21
1 + class CreateSubmissions < ActiveRecord::Migration
2 + def self.up
3 + create_table :submissions do |t|
4 + t.column :user_id, :integer
5 + t.column :problem_id, :integer
6 + t.column :language_id, :integer
7 + t.column :source, :text
8 + t.column :binary, :binary
9 + t.column :submitted_at, :datetime
10 + t.column :compiled_at, :datetime
11 + t.column :compiler_message, :text
12 + t.column :graded_at, :datetime
13 + t.column :points, :integer
14 + t.column :grader_comment, :text
15 + end
16 + end
17 +
18 + def self.down
19 + drop_table :submissions
20 + end
21 + end
@@ -0,0 +1,16
1 + class CreateLanguages < ActiveRecord::Migration
2 + def self.up
3 + create_table :languages do |t|
4 + t.column :name, :string, :limit => 10
5 + t.column :pretty_name, :string
6 + end
7 +
8 + Language.create(:name => "c", :pretty_name => "C")
9 + Language.create(:name => "cpp", :pretty_name => "C++")
10 + Language.create(:name => "pas", :pretty_name => "Pascal")
11 + end
12 +
13 + def self.down
14 + drop_table :languages
15 + end
16 + end
@@ -0,0 +1,9
1 + class AddIndexToSubmissions < ActiveRecord::Migration
2 + def self.up
3 + add_index :submissions, [:user_id, :problem_id]
4 + end
5 +
6 + def self.down
7 + remove_index :submissions, :column => [:user_id, :problem_id]
8 + end
9 + end
@@ -0,0 +1,19
1 + class CreateRoles < ActiveRecord::Migration
2 + def self.up
3 + create_table :roles do |t|
4 + t.column 'name', :string
5 + end
6 +
7 + create_table :roles_users, :id => false do |t|
8 + t.column 'role_id', :integer
9 + t.column 'user_id', :integer
10 + end
11 +
12 + add_index :roles_users, :user_id
13 + end
14 +
15 + def self.down
16 + drop_table :roles_users
17 + drop_table :roles
18 + end
19 + end
@@ -0,0 +1,21
1 + class CreateRights < ActiveRecord::Migration
2 + def self.up
3 + create_table :rights do |t|
4 + t.column 'name', :string
5 + t.column 'controller', :string
6 + t.column 'action', :string
7 + end
8 +
9 + create_table :rights_roles, :id => false do |t|
10 + t.column 'right_id', :integer
11 + t.column 'role_id', :integer
12 + end
13 +
14 + add_index :rights_roles, :role_id
15 + end
16 +
17 + def self.down
18 + drop_table :rights_roles
19 + drop_table :rights
20 + end
21 + end
@@ -0,0 +1,12
1 + class CreateTasks < ActiveRecord::Migration
2 + def self.up
3 + create_table :tasks do |t|
4 + t.column 'submission_id', :integer
5 + t.column 'created_at', :datetime
6 + end
7 + end
8 +
9 + def self.down
10 + drop_table :tasks
11 + end
12 + end
@@ -0,0 +1,16
1 + class AddSessions < ActiveRecord::Migration
2 + def self.up
3 + create_table :sessions do |t|
4 + t.column :session_id, :string
5 + t.column :data, :text
6 + t.column :updated_at, :datetime
7 + end
8 +
9 + add_index :sessions, :session_id
10 + add_index :sessions, :updated_at
11 + end
12 +
13 + def self.down
14 + drop_table :sessions
15 + end
16 + end
@@ -0,0 +1,38
1 + class AddAdminAndRoles < ActiveRecord::Migration
2 + def self.up
3 + root = User.new(:login => 'root',
4 + :full_name => 'Administrator',
5 + :alias => 'root')
6 + root.password = 'ioionrails';
7 + root.encrypt_new_password
8 +
9 + role = Role.create(:name => 'admin')
10 + root.roles << role;
11 + root.save
12 +
13 + user_admin_right = Right.create(:name => 'user_admin',
14 + :controller => 'user_admin',
15 + :action => 'all')
16 + problem_admin_right = Right.create(:name=> 'problem_admin',
17 + :controller => 'problems',
18 + :action => 'all')
19 +
20 + role.rights << user_admin_right;
21 + role.rights << problem_admin_right;
22 + role.save
23 + end
24 +
25 + def self.down
26 + admin_role = Role.find_by_name('admin')
27 + admin_role.destroy unless admin_role==nil
28 +
29 + admin_right = Right.find_by_name('user_admin')
30 + admin_right.destroy unless admin_right==nil
31 +
32 + admin_right = Right.find_by_name('problem_admin')
33 + admin_right.destroy unless admin_right==nil
34 +
35 + root = User.find_by_login('root')
36 + root.destroy unless root==nil
37 + end
38 + end
@@ -0,0 +1,15
1 + class AddLanguageExt < ActiveRecord::Migration
2 + def self.up
3 + add_column :languages, :ext, :string, :limit => 10
4 +
5 + langs = Language.find(:all)
6 + langs.each do |l|
7 + l.ext = l.name
8 + l.save
9 + end
10 + end
11 +
12 + def self.down
13 + remove_column :languages, :ext
14 + end
15 + end
@@ -0,0 +1,2
1 + Use this README file to introduce your application and point to useful places in the API for learning more.
2 + Run "rake appdoc" to generate API documentation for your models and controllers. No newline at end of file
@@ -0,0 +1,40
1 + # General Apache options
2 + AddHandler fastcgi-script .fcgi
3 + AddHandler cgi-script .cgi
4 + Options +FollowSymLinks +ExecCGI
5 +
6 + # If you don't want Rails to look in certain directories,
7 + # use the following rewrite rules so that Apache won't rewrite certain requests
8 + #
9 + # Example:
10 + # RewriteCond %{REQUEST_URI} ^/notrails.*
11 + # RewriteRule .* - [L]
12 +
13 + # Redirect all requests not available on the filesystem to Rails
14 + # By default the cgi dispatcher is used which is very slow
15 + #
16 + # For better performance replace the dispatcher with the fastcgi one
17 + #
18 + # Example:
19 + # RewriteRule ^(.*)$ dispatch.fcgi [QSA,L]
20 + RewriteEngine On
21 +
22 + # If your Rails application is accessed via an Alias directive,
23 + # then you MUST also set the RewriteBase in this htaccess file.
24 + #
25 + # Example:
26 + # Alias /myrailsapp /path/to/myrailsapp/public
27 + # RewriteBase /myrailsapp
28 +
29 + RewriteRule ^$ index.html [QSA]
30 + RewriteRule ^([^.]+)$ $1.html [QSA]
31 + RewriteCond %{REQUEST_FILENAME} !-f
32 + RewriteRule ^(.*)$ dispatch.cgi [QSA,L]
33 +
34 + # In case Rails experiences terminal errors
35 + # Instead of displaying this message you can supply a file here which will be rendered instead
36 + #
37 + # Example:
38 + # ErrorDocument 500 /500.html
39 +
40 + ErrorDocument 500 "<h2>Application error</h2>Rails application failed to start properly" No newline at end of file
@@ -0,0 +1,30
1 + <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
2 + "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
3 +
4 + <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
5 +
6 + <head>
7 + <meta http-equiv="content-type" content="text/html; charset=UTF-8" />
8 + <title>The page you were looking for doesn't exist (404)</title>
9 + <style type="text/css">
10 + body { background-color: #fff; color: #666; text-align: center; font-family: arial, sans-serif; }
11 + div.dialog {
12 + width: 25em;
13 + padding: 0 4em;
14 + margin: 4em auto 0 auto;
15 + border: 1px solid #ccc;
16 + border-right-color: #999;
17 + border-bottom-color: #999;
18 + }
19 + h1 { font-size: 100%; color: #f00; line-height: 1.5em; }
20 + </style>
21 + </head>
22 +
23 + <body>
24 + <!-- This file lives in public/404.html -->
25 + <div class="dialog">
26 + <h1>The page you were looking for doesn't exist.</h1>
27 + <p>You may have mistyped the address or the page may have moved.</p>
28 + </div>
29 + </body>
30 + </html> No newline at end of file
@@ -0,0 +1,30
1 + <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
2 + "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
3 +
4 + <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
5 +
6 + <head>
7 + <meta http-equiv="content-type" content="text/html; charset=UTF-8" />
8 + <title>We're sorry, but something went wrong</title>
9 + <style type="text/css">
10 + body { background-color: #fff; color: #666; text-align: center; font-family: arial, sans-serif; }
11 + div.dialog {
12 + width: 25em;
13 + padding: 0 4em;
14 + margin: 4em auto 0 auto;
15 + border: 1px solid #ccc;
16 + border-right-color: #999;
17 + border-bottom-color: #999;
18 + }
19 + h1 { font-size: 100%; color: #f00; line-height: 1.5em; }
20 + </style>
21 + </head>
22 +
23 + <body>
24 + <!-- This file lives in public/500.html -->
25 + <div class="dialog">
26 + <h1>We're sorry, but something went wrong.</h1>
27 + <p>We've been notified about this issue and we'll take a look at it shortly.</p>
28 + </div>
29 + </body>
30 + </html> No newline at end of file
@@ -0,0 +1,10
1 + #!c:/ruby/bin/ruby
2 +
3 + require File.dirname(__FILE__) + "/../config/environment" unless defined?(RAILS_ROOT)
4 +
5 + # If you're using RubyGems and mod_ruby, this require should be changed to an absolute path one, like:
6 + # "/usr/local/lib/ruby/gems/1.8/gems/rails-0.8.0/lib/dispatcher" -- otherwise performance is severely impaired
7 + require "dispatcher"
8 +
9 + ADDITIONAL_LOAD_PATHS.reverse.each { |dir| $:.unshift(dir) if File.directory?(dir) } if defined?(Apache::RubyRun)
10 + Dispatcher.dispatch No newline at end of file
@@ -0,0 +1,24
1 + #!c:/ruby/bin/ruby
2 + #
3 + # You may specify the path to the FastCGI crash log (a log of unhandled
4 + # exceptions which forced the FastCGI instance to exit, great for debugging)
5 + # and the number of requests to process before running garbage collection.
6 + #
7 + # By default, the FastCGI crash log is RAILS_ROOT/log/fastcgi.crash.log
8 + # and the GC period is nil (turned off). A reasonable number of requests
9 + # could range from 10-100 depending on the memory footprint of your app.
10 + #
11 + # Example:
12 + # # Default log path, normal GC behavior.
13 + # RailsFCGIHandler.process!
14 + #
15 + # # Default log path, 50 requests between GC.
16 + # RailsFCGIHandler.process! nil, 50
17 + #
18 + # # Custom log path, normal GC behavior.
19 + # RailsFCGIHandler.process! '/var/log/myapp_fcgi_crash.log'
20 + #
21 + require File.dirname(__FILE__) + "/../config/environment"
22 + require 'fcgi_handler'
23 +
24 + RailsFCGIHandler.process!
@@ -0,0 +1,10
1 + #!c:/ruby/bin/ruby
2 +
3 + require File.dirname(__FILE__) + "/../config/environment" unless defined?(RAILS_ROOT)
4 +
5 + # If you're using RubyGems and mod_ruby, this require should be changed to an absolute path one, like:
6 + # "/usr/local/lib/ruby/gems/1.8/gems/rails-0.8.0/lib/dispatcher" -- otherwise performance is severely impaired
7 + require "dispatcher"
8 +
9 + ADDITIONAL_LOAD_PATHS.reverse.each { |dir| $:.unshift(dir) if File.directory?(dir) } if defined?(Apache::RubyRun)
10 + Dispatcher.dispatch No newline at end of file
new file 100644
new file 100644
binary diff hidden
@@ -0,0 +1,277
1 + <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
2 + "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
3 + <html>
4 + <head>
5 + <meta http-equiv="Content-type" content="text/html; charset=utf-8" />
6 + <title>Ruby on Rails: Welcome aboard</title>
7 + <style type="text/css" media="screen">
8 + body {
9 + margin: 0;
10 + margin-bottom: 25px;
11 + padding: 0;
12 + background-color: #f0f0f0;
13 + font-family: "Lucida Grande", "Bitstream Vera Sans", "Verdana";
14 + font-size: 13px;
15 + color: #333;
16 + }
17 +
18 + h1 {
19 + font-size: 28px;
20 + color: #000;
21 + }
22 +
23 + a {color: #03c}
24 + a:hover {
25 + background-color: #03c;
26 + color: white;
27 + text-decoration: none;
28 + }
29 +
30 +
31 + #page {
32 + background-color: #f0f0f0;
33 + width: 750px;
34 + margin: 0;
35 + margin-left: auto;
36 + margin-right: auto;
37 + }
38 +
39 + #content {
40 + float: left;
41 + background-color: white;
42 + border: 3px solid #aaa;
43 + border-top: none;
44 + padding: 25px;
45 + width: 500px;
46 + }
47 +
48 + #sidebar {
49 + float: right;
50 + width: 175px;
51 + }
52 +
53 + #footer {
54 + clear: both;
55 + }
56 +
57 +
58 + #header, #about, #getting-started {
59 + padding-left: 75px;
60 + padding-right: 30px;
61 + }
62 +
63 +
64 + #header {
65 + background-image: url("images/rails.png");
66 + background-repeat: no-repeat;
67 + background-position: top left;
68 + height: 64px;
69 + }
70 + #header h1, #header h2 {margin: 0}
71 + #header h2 {
72 + color: #888;
73 + font-weight: normal;
74 + font-size: 16px;
75 + }
76 +
77 +
78 + #about h3 {
79 + margin: 0;
80 + margin-bottom: 10px;
81 + font-size: 14px;
82 + }
83 +
84 + #about-content {
85 + background-color: #ffd;
86 + border: 1px solid #fc0;
87 + margin-left: -11px;
88 + }
89 + #about-content table {
90 + margin-top: 10px;
91 + margin-bottom: 10px;
92 + font-size: 11px;
93 + border-collapse: collapse;
94 + }
95 + #about-content td {
96 + padding: 10px;
97 + padding-top: 3px;
98 + padding-bottom: 3px;
99 + }
100 + #about-content td.name {color: #555}
101 + #about-content td.value {color: #000}
102 +
103 + #about-content.failure {
104 + background-color: #fcc;
105 + border: 1px solid #f00;
106 + }
107 + #about-content.failure p {
108 + margin: 0;
109 + padding: 10px;
110 + }
111 +
112 +
113 + #getting-started {
114 + border-top: 1px solid #ccc;
115 + margin-top: 25px;
116 + padding-top: 15px;
117 + }
118 + #getting-started h1 {
119 + margin: 0;
120 + font-size: 20px;
121 + }
122 + #getting-started h2 {
123 + margin: 0;
124 + font-size: 14px;
125 + font-weight: normal;
126 + color: #333;
127 + margin-bottom: 25px;
128 + }
129 + #getting-started ol {
130 + margin-left: 0;
131 + padding-left: 0;
132 + }
133 + #getting-started li {
134 + font-size: 18px;
135 + color: #888;
136 + margin-bottom: 25px;
137 + }
138 + #getting-started li h2 {
139 + margin: 0;
140 + font-weight: normal;
141 + font-size: 18px;
142 + color: #333;
143 + }
144 + #getting-started li p {
145 + color: #555;
146 + font-size: 13px;
147 + }
148 +
149 +
150 + #search {
151 + margin: 0;
152 + padding-top: 10px;
153 + padding-bottom: 10px;
154 + font-size: 11px;
155 + }
156 + #search input {
157 + font-size: 11px;
158 + margin: 2px;
159 + }
160 + #search-text {width: 170px}
161 +
162 +
163 + #sidebar ul {
164 + margin-left: 0;
165 + padding-left: 0;
166 + }
167 + #sidebar ul h3 {
168 + margin-top: 25px;
169 + font-size: 16px;
170 + padding-bottom: 10px;
171 + border-bottom: 1px solid #ccc;
172 + }
173 + #sidebar li {
174 + list-style-type: none;
175 + }
176 + #sidebar ul.links li {
177 + margin-bottom: 5px;
178 + }
179 +
180 + </style>
181 + <script type="text/javascript" src="javascripts/prototype.js"></script>
182 + <script type="text/javascript" src="javascripts/effects.js"></script>
183 + <script type="text/javascript">
184 + function about() {
185 + if (Element.empty('about-content')) {
186 + new Ajax.Updater('about-content', 'rails/info/properties', {
187 + method: 'get',
188 + onFailure: function() {Element.classNames('about-content').add('failure')},
189 + onComplete: function() {new Effect.BlindDown('about-content', {duration: 0.25})}
190 + });
191 + } else {
192 + new Effect[Element.visible('about-content') ?
193 + 'BlindUp' : 'BlindDown']('about-content', {duration: 0.25});
194 + }
195 + }
196 +
197 + window.onload = function() {
198 + $('search-text').value = '';
199 + $('search').onsubmit = function() {
200 + $('search-text').value = 'site:rubyonrails.org ' + $F('search-text');
201 + }
202 + }
203 + </script>
204 + </head>
205 + <body>
206 + <div id="page">
207 + <div id="sidebar">
208 + <ul id="sidebar-items">
209 + <li>
210 + <form id="search" action="http://www.google.com/search" method="get">
211 + <input type="hidden" name="hl" value="en" />
212 + <input type="text" id="search-text" name="q" value="site:rubyonrails.org " />
213 + <input type="submit" value="Search" /> the Rails site
214 + </form>
215 + </li>
216 +
217 + <li>
218 + <h3>Join the community</h3>
219 + <ul class="links">
220 + <li><a href="http://www.rubyonrails.org/">Ruby on Rails</a></li>
221 + <li><a href="http://weblog.rubyonrails.org/">Official weblog</a></li>
222 + <li><a href="http://lists.rubyonrails.org/">Mailing lists</a></li>
223 + <li><a href="http://wiki.rubyonrails.org/rails/pages/IRC">IRC channel</a></li>
224 + <li><a href="http://wiki.rubyonrails.org/">Wiki</a></li>
225 + <li><a href="http://dev.rubyonrails.org/">Bug tracker</a></li>
226 + </ul>
227 + </li>
228 +
229 + <li>
230 + <h3>Browse the documentation</h3>
231 + <ul class="links">
232 + <li><a href="http://api.rubyonrails.org/">Rails API</a></li>
233 + <li><a href="http://stdlib.rubyonrails.org/">Ruby standard library</a></li>
234 + <li><a href="http://corelib.rubyonrails.org/">Ruby core</a></li>
235 + </ul>
236 + </li>
237 + </ul>
238 + </div>
239 +
240 + <div id="content">
241 + <div id="header">
242 + <h1>Welcome aboard</h1>
243 + <h2>You&rsquo;re riding the Rails!</h2>
244 + </div>
245 +
246 + <div id="about">
247 + <h3><a href="rails/info/properties" onclick="about(); return false">About your application&rsquo;s environment</a></h3>
248 + <div id="about-content" style="display: none"></div>
249 + </div>
250 +
251 + <div id="getting-started">
252 + <h1>Getting started</h1>
253 + <h2>Here&rsquo;s how to get rolling:</h2>
254 +
255 + <ol>
256 + <li>
257 + <h2>Create your databases and edit <tt>config/database.yml</tt></h2>
258 + <p>Rails needs to know your login and password.</p>
259 + </li>
260 +
261 + <li>
262 + <h2>Use <tt>script/generate</tt> to create your models and controllers</h2>
263 + <p>To see all available options, run it without parameters.</p>
264 + </li>
265 +
266 + <li>
267 + <h2>Set up a default route and remove or rename this file</h2>
268 + <p>Routes are setup in config/routes.rb.</p>
269 + </li>
270 + </ol>
271 + </div>
272 + </div>
273 +
274 + <div id="footer">&nbsp;</div>
275 + </div>
276 + </body>
277 + </html> No newline at end of file
@@ -0,0 +1,2
1 + // Place your application-specific JavaScript functions and classes here
2 + // This file is automatically included by javascript_include_tag :defaults
This diff has been collapsed as it changes many lines, (833 lines changed) Show them Hide them
@@ -0,0 +1,833
1 + // Copyright (c) 2005, 2006 Thomas Fuchs (http://script.aculo.us, http://mir.aculo.us)
2 + // (c) 2005, 2006 Ivan Krstic (http://blogs.law.harvard.edu/ivan)
3 + // (c) 2005, 2006 Jon Tirsen (http://www.tirsen.com)
4 + // Contributors:
5 + // Richard Livsey
6 + // Rahul Bhargava
7 + // Rob Wills
8 + //
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/
11 +
12 + // Autocompleter.Base handles all the autocompletion functionality
13 + // that's independent of the data source for autocompletion. This
14 + // includes drawing the autocompletion menu, observing keyboard
15 + // and mouse events, and similar.
16 + //
17 + // Specific autocompleters need to provide, at the very least,
18 + // a getUpdatedChoices function that will be invoked every time
19 + // the text inside the monitored textbox changes. This method
20 + // should get the text for which to provide autocompletion by
21 + // invoking this.getToken(), NOT by directly accessing
22 + // this.element.value. This is to allow incremental tokenized
23 + // autocompletion. Specific auto-completion logic (AJAX, etc)
24 + // belongs in getUpdatedChoices.
25 + //
26 + // Tokenized incremental autocompletion is enabled automatically
27 + // when an autocompleter is instantiated with the 'tokens' option
28 + // in the options parameter, e.g.:
29 + // new Ajax.Autocompleter('id','upd', '/url/', { tokens: ',' });
30 + // will incrementally autocomplete with a comma as the token.
31 + // Additionally, ',' in the above example can be replaced with
32 + // a token array, e.g. { tokens: [',', '\n'] } which
33 + // enables autocompletion on multiple tokens. This is most
34 + // useful when one of the tokens is \n (a newline), as it
35 + // allows smart autocompletion after linebreaks.
36 +
37 + if(typeof Effect == 'undefined')
38 + throw("controls.js requires including script.aculo.us' effects.js library");
39 +
40 + var Autocompleter = {}
41 + Autocompleter.Base = function() {};
42 + Autocompleter.Base.prototype = {
43 + baseInitialize: function(element, update, options) {
44 + this.element = $(element);
45 + this.update = $(update);
46 + this.hasFocus = false;
47 + this.changed = false;
48 + this.active = false;
49 + this.index = 0;
50 + this.entryCount = 0;
51 +
52 + if(this.setOptions)
53 + this.setOptions(options);
54 + else
55 + this.options = options || {};
56 +
57 + this.options.paramName = this.options.paramName || this.element.name;
58 + this.options.tokens = this.options.tokens || [];
59 + this.options.frequency = this.options.frequency || 0.4;
60 + this.options.minChars = this.options.minChars || 1;
61 + this.options.onShow = this.options.onShow ||
62 + function(element, update){
63 + if(!update.style.position || update.style.position=='absolute') {
64 + update.style.position = 'absolute';
65 + Position.clone(element, update, {
66 + setHeight: false,
67 + offsetTop: element.offsetHeight
68 + });
69 + }
70 + Effect.Appear(update,{duration:0.15});
71 + };
72 + this.options.onHide = this.options.onHide ||
73 + function(element, update){ new Effect.Fade(update,{duration:0.15}) };
74 +
75 + if(typeof(this.options.tokens) == 'string')
76 + this.options.tokens = new Array(this.options.tokens);
77 +
78 + this.observer = null;
79 +
80 + this.element.setAttribute('autocomplete','off');
81 +
82 + Element.hide(this.update);
83 +
84 + Event.observe(this.element, "blur", this.onBlur.bindAsEventListener(this));
85 + Event.observe(this.element, "keypress", this.onKeyPress.bindAsEventListener(this));
86 + },
87 +
88 + show: function() {
89 + if(Element.getStyle(this.update, 'display')=='none') this.options.onShow(this.element, this.update);
90 + if(!this.iefix &&
91 + (navigator.appVersion.indexOf('MSIE')>0) &&
92 + (navigator.userAgent.indexOf('Opera')<0) &&
93 + (Element.getStyle(this.update, 'position')=='absolute')) {
94 + new Insertion.After(this.update,
95 + '<iframe id="' + this.update.id + '_iefix" '+
96 + 'style="display:none;position:absolute;filter:progid:DXImageTransform.Microsoft.Alpha(opacity=0);" ' +
97 + 'src="javascript:false;" frameborder="0" scrolling="no"></iframe>');
98 + this.iefix = $(this.update.id+'_iefix');
99 + }
100 + if(this.iefix) setTimeout(this.fixIEOverlapping.bind(this), 50);
101 + },
102 +
103 + fixIEOverlapping: function() {
104 + Position.clone(this.update, this.iefix, {setTop:(!this.update.style.height)});
105 + this.iefix.style.zIndex = 1;
106 + this.update.style.zIndex = 2;
107 + Element.show(this.iefix);
108 + },
109 +
110 + hide: function() {
111 + this.stopIndicator();
112 + if(Element.getStyle(this.update, 'display')!='none') this.options.onHide(this.element, this.update);
113 + if(this.iefix) Element.hide(this.iefix);
114 + },
115 +
116 + startIndicator: function() {
117 + if(this.options.indicator) Element.show(this.options.indicator);
118 + },
119 +
120 + stopIndicator: function() {
121 + if(this.options.indicator) Element.hide(this.options.indicator);
122 + },
123 +
124 + onKeyPress: function(event) {
125 + if(this.active)
126 + switch(event.keyCode) {
127 + case Event.KEY_TAB:
128 + case Event.KEY_RETURN:
129 + this.selectEntry();
130 + Event.stop(event);
131 + case Event.KEY_ESC:
132 + this.hide();
133 + this.active = false;
134 + Event.stop(event);
135 + return;
136 + case Event.KEY_LEFT:
137 + case Event.KEY_RIGHT:
138 + return;
139 + case Event.KEY_UP:
140 + this.markPrevious();
141 + this.render();
142 + if(navigator.appVersion.indexOf('AppleWebKit')>0) Event.stop(event);
143 + return;
144 + case Event.KEY_DOWN:
145 + this.markNext();
146 + this.render();
147 + if(navigator.appVersion.indexOf('AppleWebKit')>0) Event.stop(event);
148 + return;
149 + }
150 + else
151 + if(event.keyCode==Event.KEY_TAB || event.keyCode==Event.KEY_RETURN ||
152 + (navigator.appVersion.indexOf('AppleWebKit') > 0 && event.keyCode == 0)) return;
153 +
154 + this.changed = true;
155 + this.hasFocus = true;
156 +
157 + if(this.observer) clearTimeout(this.observer);
158 + this.observer =
159 + setTimeout(this.onObserverEvent.bind(this), this.options.frequency*1000);
160 + },
161 +
162 + activate: function() {
163 + this.changed = false;
164 + this.hasFocus = true;
165 + this.getUpdatedChoices();
166 + },
167 +
168 + onHover: function(event) {
169 + var element = Event.findElement(event, 'LI');
170 + if(this.index != element.autocompleteIndex)
171 + {
172 + this.index = element.autocompleteIndex;
173 + this.render();
174 + }
175 + Event.stop(event);
176 + },
177 +
178 + onClick: function(event) {
179 + var element = Event.findElement(event, 'LI');
180 + this.index = element.autocompleteIndex;
181 + this.selectEntry();
182 + this.hide();
183 + },
184 +
185 + onBlur: function(event) {
186 + // needed to make click events working
187 + setTimeout(this.hide.bind(this), 250);
188 + this.hasFocus = false;
189 + this.active = false;
190 + },
191 +
192 + render: function() {
193 + if(this.entryCount > 0) {
194 + for (var i = 0; i < this.entryCount; i++)
195 + this.index==i ?
196 + Element.addClassName(this.getEntry(i),"selected") :
197 + Element.removeClassName(this.getEntry(i),"selected");
198 +
199 + if(this.hasFocus) {
200 + this.show();
201 + this.active = true;
202 + }
203 + } else {
204 + this.active = false;
205 + this.hide();
206 + }
207 + },
208 +
209 + markPrevious: function() {
210 + if(this.index > 0) this.index--
211 + else this.index = this.entryCount-1;
212 + this.getEntry(this.index).scrollIntoView(true);
213 + },
214 +
215 + markNext: function() {
216 + if(this.index < this.entryCount-1) this.index++
217 + else this.index = 0;
218 + this.getEntry(this.index).scrollIntoView(false);
219 + },
220 +
221 + getEntry: function(index) {
222 + return this.update.firstChild.childNodes[index];
223 + },
224 +
225 + getCurrentEntry: function() {
226 + return this.getEntry(this.index);
227 + },
228 +
229 + selectEntry: function() {
230 + this.active = false;
231 + this.updateElement(this.getCurrentEntry());
232 + },
233 +
234 + updateElement: function(selectedElement) {
235 + if (this.options.updateElement) {
236 + this.options.updateElement(selectedElement);
237 + return;
238 + }
239 + var value = '';
240 + if (this.options.select) {
241 + var nodes = document.getElementsByClassName(this.options.select, selectedElement) || [];
242 + if(nodes.length>0) value = Element.collectTextNodes(nodes[0], this.options.select);
243 + } else
244 + value = Element.collectTextNodesIgnoreClass(selectedElement, 'informal');
245 +
246 + var lastTokenPos = this.findLastToken();
247 + if (lastTokenPos != -1) {
248 + var newValue = this.element.value.substr(0, lastTokenPos + 1);
249 + var whitespace = this.element.value.substr(lastTokenPos + 1).match(/^\s+/);
250 + if (whitespace)
251 + newValue += whitespace[0];
252 + this.element.value = newValue + value;
253 + } else {
254 + this.element.value = value;
255 + }
256 + this.element.focus();
257 +
258 + if (this.options.afterUpdateElement)
259 + this.options.afterUpdateElement(this.element, selectedElement);
260 + },
261 +
262 + updateChoices: function(choices) {
263 + if(!this.changed && this.hasFocus) {
264 + this.update.innerHTML = choices;
265 + Element.cleanWhitespace(this.update);
266 + Element.cleanWhitespace(this.update.down());
267 +
268 + if(this.update.firstChild && this.update.down().childNodes) {
269 + this.entryCount =
270 + this.update.down().childNodes.length;
271 + for (var i = 0; i < this.entryCount; i++) {
272 + var entry = this.getEntry(i);
273 + entry.autocompleteIndex = i;
274 + this.addObservers(entry);
275 + }
276 + } else {
277 + this.entryCount = 0;
278 + }
279 +
280 + this.stopIndicator();
281 + this.index = 0;
282 +
283 + if(this.entryCount==1 && this.options.autoSelect) {
284 + this.selectEntry();
285 + this.hide();
286 + } else {
287 + this.render();
288 + }
289 + }
290 + },
291 +
292 + addObservers: function(element) {
293 + Event.observe(element, "mouseover", this.onHover.bindAsEventListener(this));
294 + Event.observe(element, "click", this.onClick.bindAsEventListener(this));
295 + },
296 +
297 + onObserverEvent: function() {
298 + this.changed = false;
299 + if(this.getToken().length>=this.options.minChars) {
300 + this.startIndicator();
301 + this.getUpdatedChoices();
302 + } else {
303 + this.active = false;
304 + this.hide();
305 + }
306 + },
307 +
308 + getToken: function() {
309 + var tokenPos = this.findLastToken();
310 + if (tokenPos != -1)
311 + var ret = this.element.value.substr(tokenPos + 1).replace(/^\s+/,'').replace(/\s+$/,'');
312 + else
313 + var ret = this.element.value;
314 +
315 + return /\n/.test(ret) ? '' : ret;
316 + },
317 +
318 + findLastToken: function() {
319 + var lastTokenPos = -1;
320 +
321 + for (var i=0; i<this.options.tokens.length; i++) {
322 + var thisTokenPos = this.element.value.lastIndexOf(this.options.tokens[i]);
323 + if (thisTokenPos > lastTokenPos)
324 + lastTokenPos = thisTokenPos;
325 + }
326 + return lastTokenPos;
327 + }
328 + }
329 +
330 + Ajax.Autocompleter = Class.create();
331 + Object.extend(Object.extend(Ajax.Autocompleter.prototype, Autocompleter.Base.prototype), {
332 + initialize: function(element, update, url, options) {
333 + this.baseInitialize(element, update, options);
334 + this.options.asynchronous = true;
335 + this.options.onComplete = this.onComplete.bind(this);
336 + this.options.defaultParams = this.options.parameters || null;
337 + this.url = url;
338 + },
339 +
340 + getUpdatedChoices: function() {
341 + entry = encodeURIComponent(this.options.paramName) + '=' +
342 + encodeURIComponent(this.getToken());
343 +
344 + this.options.parameters = this.options.callback ?
345 + this.options.callback(this.element, entry) : entry;
346 +
347 + if(this.options.defaultParams)
348 + this.options.parameters += '&' + this.options.defaultParams;
349 +
350 + new Ajax.Request(this.url, this.options);
351 + },
352 +
353 + onComplete: function(request) {
354 + this.updateChoices(request.responseText);
355 + }
356 +
357 + });
358 +
359 + // The local array autocompleter. Used when you'd prefer to
360 + // inject an array of autocompletion options into the page, rather
361 + // than sending out Ajax queries, which can be quite slow sometimes.
362 + //
363 + // The constructor takes four parameters. The first two are, as usual,
364 + // the id of the monitored textbox, and id of the autocompletion menu.
365 + // The third is the array you want to autocomplete from, and the fourth
366 + // is the options block.
367 + //
368 + // Extra local autocompletion options:
369 + // - choices - How many autocompletion choices to offer
370 + //
371 + // - partialSearch - If false, the autocompleter will match entered
372 + // text only at the beginning of strings in the
373 + // autocomplete array. Defaults to true, which will
374 + // match text at the beginning of any *word* in the
375 + // strings in the autocomplete array. If you want to
376 + // search anywhere in the string, additionally set
377 + // the option fullSearch to true (default: off).
378 + //
379 + // - fullSsearch - Search anywhere in autocomplete array strings.
380 + //
381 + // - partialChars - How many characters to enter before triggering
382 + // a partial match (unlike minChars, which defines
383 + // how many characters are required to do any match
384 + // at all). Defaults to 2.
385 + //
386 + // - ignoreCase - Whether to ignore case when autocompleting.
387 + // Defaults to true.
388 + //
389 + // It's possible to pass in a custom function as the 'selector'
390 + // option, if you prefer to write your own autocompletion logic.
391 + // In that case, the other options above will not apply unless
392 + // you support them.
393 +
394 + Autocompleter.Local = Class.create();
395 + Autocompleter.Local.prototype = Object.extend(new Autocompleter.Base(), {
396 + initialize: function(element, update, array, options) {
397 + this.baseInitialize(element, update, options);
398 + this.options.array = array;
399 + },
400 +
401 + getUpdatedChoices: function() {
402 + this.updateChoices(this.options.selector(this));
403 + },
404 +
405 + setOptions: function(options) {
406 + this.options = Object.extend({
407 + choices: 10,
408 + partialSearch: true,
409 + partialChars: 2,
410 + ignoreCase: true,
411 + fullSearch: false,
412 + selector: function(instance) {
413 + var ret = []; // Beginning matches
414 + var partial = []; // Inside matches
415 + var entry = instance.getToken();
416 + var count = 0;
417 +
418 + for (var i = 0; i < instance.options.array.length &&
419 + ret.length < instance.options.choices ; i++) {
420 +
421 + var elem = instance.options.array[i];
422 + var foundPos = instance.options.ignoreCase ?
423 + elem.toLowerCase().indexOf(entry.toLowerCase()) :
424 + elem.indexOf(entry);
425 +
426 + while (foundPos != -1) {
427 + if (foundPos == 0 && elem.length != entry.length) {
428 + ret.push("<li><strong>" + elem.substr(0, entry.length) + "</strong>" +
429 + elem.substr(entry.length) + "</li>");
430 + break;
431 + } else if (entry.length >= instance.options.partialChars &&
432 + instance.options.partialSearch && foundPos != -1) {
433 + if (instance.options.fullSearch || /\s/.test(elem.substr(foundPos-1,1))) {
434 + partial.push("<li>" + elem.substr(0, foundPos) + "<strong>" +
435 + elem.substr(foundPos, entry.length) + "</strong>" + elem.substr(
436 + foundPos + entry.length) + "</li>");
437 + break;
438 + }
439 + }
440 +
441 + foundPos = instance.options.ignoreCase ?
442 + elem.toLowerCase().indexOf(entry.toLowerCase(), foundPos + 1) :
443 + elem.indexOf(entry, foundPos + 1);
444 +
445 + }
446 + }
447 + if (partial.length)
448 + ret = ret.concat(partial.slice(0, instance.options.choices - ret.length))
449 + return "<ul>" + ret.join('') + "</ul>";
450 + }
451 + }, options || {});
452 + }
453 + });
454 +
455 + // AJAX in-place editor
456 + //
457 + // see documentation on http://wiki.script.aculo.us/scriptaculous/show/Ajax.InPlaceEditor
458 +
459 + // Use this if you notice weird scrolling problems on some browsers,
460 + // the DOM might be a bit confused when this gets called so do this
461 + // waits 1 ms (with setTimeout) until it does the activation
462 + Field.scrollFreeActivate = function(field) {
463 + setTimeout(function() {
464 + Field.activate(field);
465 + }, 1);
466 + }
467 +
468 + Ajax.InPlaceEditor = Class.create();
469 + Ajax.InPlaceEditor.defaultHighlightColor = "#FFFF99";
470 + Ajax.InPlaceEditor.prototype = {
471 + initialize: function(element, url, options) {
472 + this.url = url;
473 + this.element = $(element);
474 +
475 + this.options = Object.extend({
476 + paramName: "value",
477 + okButton: true,
478 + okText: "ok",
479 + cancelLink: true,
480 + cancelText: "cancel",
481 + savingText: "Saving...",
482 + clickToEditText: "Click to edit",
483 + okText: "ok",
484 + rows: 1,
485 + onComplete: function(transport, element) {
486 + new Effect.Highlight(element, {startcolor: this.options.highlightcolor});
487 + },
488 + onFailure: function(transport) {
489 + alert("Error communicating with the server: " + transport.responseText.stripTags());
490 + },
491 + callback: function(form) {
492 + return Form.serialize(form);
493 + },
494 + handleLineBreaks: true,
495 + loadingText: 'Loading...',
496 + savingClassName: 'inplaceeditor-saving',
497 + loadingClassName: 'inplaceeditor-loading',
498 + formClassName: 'inplaceeditor-form',
499 + highlightcolor: Ajax.InPlaceEditor.defaultHighlightColor,
500 + highlightendcolor: "#FFFFFF",
501 + externalControl: null,
502 + submitOnBlur: false,
503 + ajaxOptions: {},
504 + evalScripts: false
505 + }, options || {});
506 +
507 + if(!this.options.formId && this.element.id) {
508 + this.options.formId = this.element.id + "-inplaceeditor";
509 + if ($(this.options.formId)) {
510 + // there's already a form with that name, don't specify an id
511 + this.options.formId = null;
512 + }
513 + }
514 +
515 + if (this.options.externalControl) {
516 + this.options.externalControl = $(this.options.externalControl);
517 + }
518 +
519 + this.originalBackground = Element.getStyle(this.element, 'background-color');
520 + if (!this.originalBackground) {
521 + this.originalBackground = "transparent";
522 + }
523 +
524 + this.element.title = this.options.clickToEditText;
525 +
526 + this.onclickListener = this.enterEditMode.bindAsEventListener(this);
527 + this.mouseoverListener = this.enterHover.bindAsEventListener(this);
528 + this.mouseoutListener = this.leaveHover.bindAsEventListener(this);
529 + Event.observe(this.element, 'click', this.onclickListener);
530 + Event.observe(this.element, 'mouseover', this.mouseoverListener);
531 + Event.observe(this.element, 'mouseout', this.mouseoutListener);
532 + if (this.options.externalControl) {
533 + Event.observe(this.options.externalControl, 'click', this.onclickListener);
534 + Event.observe(this.options.externalControl, 'mouseover', this.mouseoverListener);
535 + Event.observe(this.options.externalControl, 'mouseout', this.mouseoutListener);
536 + }
537 + },
538 + enterEditMode: function(evt) {
539 + if (this.saving) return;
540 + if (this.editing) return;
541 + this.editing = true;
542 + this.onEnterEditMode();
543 + if (this.options.externalControl) {
544 + Element.hide(this.options.externalControl);
545 + }
546 + Element.hide(this.element);
547 + this.createForm();
548 + this.element.parentNode.insertBefore(this.form, this.element);
549 + if (!this.options.loadTextURL) Field.scrollFreeActivate(this.editField);
550 + // stop the event to avoid a page refresh in Safari
551 + if (evt) {
552 + Event.stop(evt);
553 + }
554 + return false;
555 + },
556 + createForm: function() {
557 + this.form = document.createElement("form");
558 + this.form.id = this.options.formId;
559 + Element.addClassName(this.form, this.options.formClassName)
560 + this.form.onsubmit = this.onSubmit.bind(this);
561 +
562 + this.createEditField();
563 +
564 + if (this.options.textarea) {
565 + var br = document.createElement("br");
566 + this.form.appendChild(br);
567 + }
568 +
569 + if (this.options.okButton) {
570 + okButton = document.createElement("input");
571 + okButton.type = "submit";
572 + okButton.value = this.options.okText;
573 + okButton.className = 'editor_ok_button';
574 + this.form.appendChild(okButton);
575 + }
576 +
577 + if (this.options.cancelLink) {
578 + cancelLink = document.createElement("a");
579 + cancelLink.href = "#";
580 + cancelLink.appendChild(document.createTextNode(this.options.cancelText));
581 + cancelLink.onclick = this.onclickCancel.bind(this);
582 + cancelLink.className = 'editor_cancel';
583 + this.form.appendChild(cancelLink);
584 + }
585 + },
586 + hasHTMLLineBreaks: function(string) {
587 + if (!this.options.handleLineBreaks) return false;
588 + return string.match(/<br/i) || string.match(/<p>/i);
589 + },
590 + convertHTMLLineBreaks: function(string) {
591 + return string.replace(/<br>/gi, "\n").replace(/<br\/>/gi, "\n").replace(/<\/p>/gi, "\n").replace(/<p>/gi, "");
592 + },
593 + createEditField: function() {
594 + var text;
595 + if(this.options.loadTextURL) {
596 + text = this.options.loadingText;
597 + } else {
598 + text = this.getText();
599 + }
600 +
601 + var obj = this;
602 +
603 + if (this.options.rows == 1 && !this.hasHTMLLineBreaks(text)) {
604 + this.options.textarea = false;
605 + var textField = document.createElement("input");
606 + textField.obj = this;
607 + textField.type = "text";
608 + textField.name = this.options.paramName;
609 + textField.value = text;
610 + textField.style.backgroundColor = this.options.highlightcolor;
611 + textField.className = 'editor_field';
612 + var size = this.options.size || this.options.cols || 0;
613 + if (size != 0) textField.size = size;
614 + if (this.options.submitOnBlur)
615 + textField.onblur = this.onSubmit.bind(this);
616 + this.editField = textField;
617 + } else {
618 + this.options.textarea = true;
619 + var textArea = document.createElement("textarea");
620 + textArea.obj = this;
621 + textArea.name = this.options.paramName;
622 + textArea.value = this.convertHTMLLineBreaks(text);
623 + textArea.rows = this.options.rows;
624 + textArea.cols = this.options.cols || 40;
625 + textArea.className = 'editor_field';
626 + if (this.options.submitOnBlur)
627 + textArea.onblur = this.onSubmit.bind(this);
628 + this.editField = textArea;
629 + }
630 +
631 + if(this.options.loadTextURL) {
632 + this.loadExternalText();
633 + }
634 + this.form.appendChild(this.editField);
635 + },
636 + getText: function() {
637 + return this.element.innerHTML;
638 + },
639 + loadExternalText: function() {
640 + Element.addClassName(this.form, this.options.loadingClassName);
641 + this.editField.disabled = true;
642 + new Ajax.Request(
643 + this.options.loadTextURL,
644 + Object.extend({
645 + asynchronous: true,
646 + onComplete: this.onLoadedExternalText.bind(this)
647 + }, this.options.ajaxOptions)
648 + );
649 + },
650 + onLoadedExternalText: function(transport) {
651 + Element.removeClassName(this.form, this.options.loadingClassName);
652 + this.editField.disabled = false;
653 + this.editField.value = transport.responseText.stripTags();
654 + Field.scrollFreeActivate(this.editField);
655 + },
656 + onclickCancel: function() {
657 + this.onComplete();
658 + this.leaveEditMode();
659 + return false;
660 + },
661 + onFailure: function(transport) {
662 + this.options.onFailure(transport);
663 + if (this.oldInnerHTML) {
664 + this.element.innerHTML = this.oldInnerHTML;
665 + this.oldInnerHTML = null;
666 + }
667 + return false;
668 + },
669 + onSubmit: function() {
670 + // onLoading resets these so we need to save them away for the Ajax call
671 + var form = this.form;
672 + var value = this.editField.value;
673 +
674 + // do this first, sometimes the ajax call returns before we get a chance to switch on Saving...
675 + // which means this will actually switch on Saving... *after* we've left edit mode causing Saving...
676 + // to be displayed indefinitely
677 + this.onLoading();
678 +
679 + if (this.options.evalScripts) {
680 + new Ajax.Request(
681 + this.url, Object.extend({
682 + parameters: this.options.callback(form, value),
683 + onComplete: this.onComplete.bind(this),
684 + onFailure: this.onFailure.bind(this),
685 + asynchronous:true,
686 + evalScripts:true
687 + }, this.options.ajaxOptions));
688 + } else {
689 + new Ajax.Updater(
690 + { success: this.element,
691 + // don't update on failure (this could be an option)
692 + failure: null },
693 + this.url, Object.extend({
694 + parameters: this.options.callback(form, value),
695 + onComplete: this.onComplete.bind(this),
696 + onFailure: this.onFailure.bind(this)
697 + }, this.options.ajaxOptions));
698 + }
699 + // stop the event to avoid a page refresh in Safari
700 + if (arguments.length > 1) {
701 + Event.stop(arguments[0]);
702 + }
703 + return false;
704 + },
705 + onLoading: function() {
706 + this.saving = true;
707 + this.removeForm();
708 + this.leaveHover();
709 + this.showSaving();
710 + },
711 + showSaving: function() {
712 + this.oldInnerHTML = this.element.innerHTML;
713 + this.element.innerHTML = this.options.savingText;
714 + Element.addClassName(this.element, this.options.savingClassName);
715 + this.element.style.backgroundColor = this.originalBackground;
716 + Element.show(this.element);
717 + },
718 + removeForm: function() {
719 + if(this.form) {
720 + if (this.form.parentNode) Element.remove(this.form);
721 + this.form = null;
722 + }
723 + },
724 + enterHover: function() {
725 + if (this.saving) return;
726 + this.element.style.backgroundColor = this.options.highlightcolor;
727 + if (this.effect) {
728 + this.effect.cancel();
729 + }
730 + Element.addClassName(this.element, this.options.hoverClassName)
731 + },
732 + leaveHover: function() {
733 + if (this.options.backgroundColor) {
734 + this.element.style.backgroundColor = this.oldBackground;
735 + }
736 + Element.removeClassName(this.element, this.options.hoverClassName)
737 + if (this.saving) return;
738 + this.effect = new Effect.Highlight(this.element, {
739 + startcolor: this.options.highlightcolor,
740 + endcolor: this.options.highlightendcolor,
741 + restorecolor: this.originalBackground
742 + });
743 + },
744 + leaveEditMode: function() {
745 + Element.removeClassName(this.element, this.options.savingClassName);
746 + this.removeForm();
747 + this.leaveHover();
748 + this.element.style.backgroundColor = this.originalBackground;
749 + Element.show(this.element);
750 + if (this.options.externalControl) {
751 + Element.show(this.options.externalControl);
752 + }
753 + this.editing = false;
754 + this.saving = false;
755 + this.oldInnerHTML = null;
756 + this.onLeaveEditMode();
757 + },
758 + onComplete: function(transport) {
759 + this.leaveEditMode();
760 + this.options.onComplete.bind(this)(transport, this.element);
761 + },
762 + onEnterEditMode: function() {},
763 + onLeaveEditMode: function() {},
764 + dispose: function() {
765 + if (this.oldInnerHTML) {
766 + this.element.innerHTML = this.oldInnerHTML;
767 + }
768 + this.leaveEditMode();
769 + Event.stopObserving(this.element, 'click', this.onclickListener);
770 + Event.stopObserving(this.element, 'mouseover', this.mouseoverListener);
771 + Event.stopObserving(this.element, 'mouseout', this.mouseoutListener);
772 + if (this.options.externalControl) {
773 + Event.stopObserving(this.options.externalControl, 'click', this.onclickListener);
774 + Event.stopObserving(this.options.externalControl, 'mouseover', this.mouseoverListener);
775 + Event.stopObserving(this.options.externalControl, 'mouseout', this.mouseoutListener);
776 + }
777 + }
778 + };
779 +
780 + Ajax.InPlaceCollectionEditor = Class.create();
781 + Object.extend(Ajax.InPlaceCollectionEditor.prototype, Ajax.InPlaceEditor.prototype);
782 + Object.extend(Ajax.InPlaceCollectionEditor.prototype, {
783 + createEditField: function() {
784 + if (!this.cached_selectTag) {
785 + var selectTag = document.createElement("select");
786 + var collection = this.options.collection || [];
787 + var optionTag;
788 + collection.each(function(e,i) {
789 + optionTag = document.createElement("option");
790 + optionTag.value = (e instanceof Array) ? e[0] : e;
791 + if((typeof this.options.value == 'undefined') &&
792 + ((e instanceof Array) ? this.element.innerHTML == e[1] : e == optionTag.value)) optionTag.selected = true;
793 + if(this.options.value==optionTag.value) optionTag.selected = true;
794 + optionTag.appendChild(document.createTextNode((e instanceof Array) ? e[1] : e));
795 + selectTag.appendChild(optionTag);
796 + }.bind(this));
797 + this.cached_selectTag = selectTag;
798 + }
799 +
800 + this.editField = this.cached_selectTag;
801 + if(this.options.loadTextURL) this.loadExternalText();
802 + this.form.appendChild(this.editField);
803 + this.options.callback = function(form, value) {
804 + return "value=" + encodeURIComponent(value);
805 + }
806 + }
807 + });
808 +
809 + // Delayed observer, like Form.Element.Observer,
810 + // but waits for delay after last key input
811 + // Ideal for live-search fields
812 +
813 + Form.Element.DelayedObserver = Class.create();
814 + Form.Element.DelayedObserver.prototype = {
815 + initialize: function(element, delay, callback) {
816 + this.delay = delay || 0.5;
817 + this.element = $(element);
818 + this.callback = callback;
819 + this.timer = null;
820 + this.lastValue = $F(this.element);
821 + Event.observe(this.element,'keyup',this.delayedListener.bindAsEventListener(this));
822 + },
823 + delayedListener: function(event) {
824 + if(this.lastValue == $F(this.element)) return;
825 + if(this.timer) clearTimeout(this.timer);
826 + this.timer = setTimeout(this.onTimerEvent.bind(this), this.delay * 1000);
827 + this.lastValue = $F(this.element);
828 + },
829 + onTimerEvent: function() {
830 + this.timer = null;
831 + this.callback(this.element, $F(this.element));
832 + }
833 + };
This diff has been collapsed as it changes many lines, (942 lines changed) Show them Hide them
@@ -0,0 +1,942
1 + // Copyright (c) 2005, 2006 Thomas Fuchs (http://script.aculo.us, http://mir.aculo.us)
2 + // (c) 2005, 2006 Sammi Williams (http://www.oriontransfer.co.nz, sammi@oriontransfer.co.nz)
3 + //
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/
6 +
7 + if(typeof Effect == 'undefined')
8 + throw("dragdrop.js requires including script.aculo.us' effects.js library");
9 +
10 + var Droppables = {
11 + drops: [],
12 +
13 + remove: function(element) {
14 + this.drops = this.drops.reject(function(d) { return d.element==$(element) });
15 + },
16 +
17 + add: function(element) {
18 + element = $(element);
19 + var options = Object.extend({
20 + greedy: true,
21 + hoverclass: null,
22 + tree: false
23 + }, arguments[1] || {});
24 +
25 + // cache containers
26 + if(options.containment) {
27 + options._containers = [];
28 + var containment = options.containment;
29 + if((typeof containment == 'object') &&
30 + (containment.constructor == Array)) {
31 + containment.each( function(c) { options._containers.push($(c)) });
32 + } else {
33 + options._containers.push($(containment));
34 + }
35 + }
36 +
37 + if(options.accept) options.accept = [options.accept].flatten();
38 +
39 + Element.makePositioned(element); // fix IE
40 + options.element = element;
41 +
42 + this.drops.push(options);
43 + },
44 +
45 + findDeepestChild: function(drops) {
46 + deepest = drops[0];
47 +
48 + for (i = 1; i < drops.length; ++i)
49 + if (Element.isParent(drops[i].element, deepest.element))
50 + deepest = drops[i];
51 +
52 + return deepest;
53 + },
54 +
55 + isContained: function(element, drop) {
56 + var containmentNode;
57 + if(drop.tree) {
58 + containmentNode = element.treeNode;
59 + } else {
60 + containmentNode = element.parentNode;
61 + }
62 + return drop._containers.detect(function(c) { return containmentNode == c });
63 + },
64 +
65 + isAffected: function(point, element, drop) {
66 + return (
67 + (drop.element!=element) &&
68 + ((!drop._containers) ||
69 + this.isContained(element, drop)) &&
70 + ((!drop.accept) ||
71 + (Element.classNames(element).detect(
72 + function(v) { return drop.accept.include(v) } ) )) &&
73 + Position.within(drop.element, point[0], point[1]) );
74 + },
75 +
76 + deactivate: function(drop) {
77 + if(drop.hoverclass)
78 + Element.removeClassName(drop.element, drop.hoverclass);
79 + this.last_active = null;
80 + },
81 +
82 + activate: function(drop) {
83 + if(drop.hoverclass)
84 + Element.addClassName(drop.element, drop.hoverclass);
85 + this.last_active = drop;
86 + },
87 +
88 + show: function(point, element) {
89 + if(!this.drops.length) return;
90 + var affected = [];
91 +
92 + if(this.last_active) this.deactivate(this.last_active);
93 + this.drops.each( function(drop) {
94 + if(Droppables.isAffected(point, element, drop))
95 + affected.push(drop);
96 + });
97 +
98 + if(affected.length>0) {
99 + drop = Droppables.findDeepestChild(affected);
100 + Position.within(drop.element, point[0], point[1]);
101 + if(drop.onHover)
102 + drop.onHover(element, drop.element, Position.overlap(drop.overlap, drop.element));
103 +
104 + Droppables.activate(drop);
105 + }
106 + },
107 +
108 + fire: function(event, element) {
109 + if(!this.last_active) return;
110 + Position.prepare();
111 +
112 + if (this.isAffected([Event.pointerX(event), Event.pointerY(event)], element, this.last_active))
113 + if (this.last_active.onDrop)
114 + this.last_active.onDrop(element, this.last_active.element, event);
115 + },
116 +
117 + reset: function() {
118 + if(this.last_active)
119 + this.deactivate(this.last_active);
120 + }
121 + }
122 +
123 + var Draggables = {
124 + drags: [],
125 + observers: [],
126 +
127 + register: function(draggable) {
128 + if(this.drags.length == 0) {
129 + this.eventMouseUp = this.endDrag.bindAsEventListener(this);
130 + this.eventMouseMove = this.updateDrag.bindAsEventListener(this);
131 + this.eventKeypress = this.keyPress.bindAsEventListener(this);
132 +
133 + Event.observe(document, "mouseup", this.eventMouseUp);
134 + Event.observe(document, "mousemove", this.eventMouseMove);
135 + Event.observe(document, "keypress", this.eventKeypress);
136 + }
137 + this.drags.push(draggable);
138 + },
139 +
140 + unregister: function(draggable) {
141 + this.drags = this.drags.reject(function(d) { return d==draggable });
142 + if(this.drags.length == 0) {
143 + Event.stopObserving(document, "mouseup", this.eventMouseUp);
144 + Event.stopObserving(document, "mousemove", this.eventMouseMove);
145 + Event.stopObserving(document, "keypress", this.eventKeypress);
146 + }
147 + },
148 +
149 + activate: function(draggable) {
150 + if(draggable.options.delay) {
151 + this._timeout = setTimeout(function() {
152 + Draggables._timeout = null;
153 + window.focus();
154 + Draggables.activeDraggable = draggable;
155 + }.bind(this), draggable.options.delay);
156 + } else {
157 + window.focus(); // allows keypress events if window isn't currently focused, fails for Safari
158 + this.activeDraggable = draggable;
159 + }
160 + },
161 +
162 + deactivate: function() {
163 + this.activeDraggable = null;
164 + },
165 +
166 + updateDrag: function(event) {
167 + if(!this.activeDraggable) return;
168 + var pointer = [Event.pointerX(event), Event.pointerY(event)];
169 + // Mozilla-based browsers fire successive mousemove events with
170 + // the same coordinates, prevent needless redrawing (moz bug?)
171 + if(this._lastPointer && (this._lastPointer.inspect() == pointer.inspect())) return;
172 + this._lastPointer = pointer;
173 +
174 + this.activeDraggable.updateDrag(event, pointer);
175 + },
176 +
177 + endDrag: function(event) {
178 + if(this._timeout) {
179 + clearTimeout(this._timeout);
180 + this._timeout = null;
181 + }
182 + if(!this.activeDraggable) return;
183 + this._lastPointer = null;
184 + this.activeDraggable.endDrag(event);
185 + this.activeDraggable = null;
186 + },
187 +
188 + keyPress: function(event) {
189 + if(this.activeDraggable)
190 + this.activeDraggable.keyPress(event);
191 + },
192 +
193 + addObserver: function(observer) {
194 + this.observers.push(observer);
195 + this._cacheObserverCallbacks();
196 + },
197 +
198 + removeObserver: function(element) { // element instead of observer fixes mem leaks
199 + this.observers = this.observers.reject( function(o) { return o.element==element });
200 + this._cacheObserverCallbacks();
201 + },
202 +
203 + notify: function(eventName, draggable, event) { // 'onStart', 'onEnd', 'onDrag'
204 + if(this[eventName+'Count'] > 0)
205 + this.observers.each( function(o) {
206 + if(o[eventName]) o[eventName](eventName, draggable, event);
207 + });
208 + if(draggable.options[eventName]) draggable.options[eventName](draggable, event);
209 + },
210 +
211 + _cacheObserverCallbacks: function() {
212 + ['onStart','onEnd','onDrag'].each( function(eventName) {
213 + Draggables[eventName+'Count'] = Draggables.observers.select(
214 + function(o) { return o[eventName]; }
215 + ).length;
216 + });
217 + }
218 + }
219 +
220 + /*--------------------------------------------------------------------------*/
221 +
222 + var Draggable = Class.create();
223 + Draggable._dragging = {};
224 +
225 + Draggable.prototype = {
226 + initialize: function(element) {
227 + var defaults = {
228 + handle: false,
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;
231 + new Effect.Move(element, { x: -left_offset, y: -top_offset, duration: dur,
232 + queue: {scope:'_draggable', position:'end'}
233 + });
234 + },
235 + endeffect: function(element) {
236 + var toOpacity = typeof element._opacity == 'number' ? element._opacity : 1.0;
237 + new Effect.Opacity(element, {duration:0.2, from:0.7, to:toOpacity,
238 + queue: {scope:'_draggable', position:'end'},
239 + afterFinish: function(){
240 + Draggable._dragging[element] = false
241 + }
242 + });
243 + },
244 + zindex: 1000,
245 + revert: false,
246 + scroll: false,
247 + scrollSensitivity: 20,
248 + scrollSpeed: 15,
249 + snap: false, // false, or xy or [x,y] or function(x,y){ return [x,y] }
250 + delay: 0
251 + };
252 +
253 + if(!arguments[1] || typeof arguments[1].endeffect == 'undefined')
254 + Object.extend(defaults, {
255 + starteffect: function(element) {
256 + element._opacity = Element.getOpacity(element);
257 + Draggable._dragging[element] = true;
258 + new Effect.Opacity(element, {duration:0.2, from:element._opacity, to:0.7});
259 + }
260 + });
261 +
262 + var options = Object.extend(defaults, arguments[1] || {});
263 +
264 + this.element = $(element);
265 +
266 + if(options.handle && (typeof options.handle == 'string'))
267 + this.handle = this.element.down('.'+options.handle, 0);
268 +
269 + if(!this.handle) this.handle = $(options.handle);
270 + if(!this.handle) this.handle = this.element;
271 +
272 + if(options.scroll && !options.scroll.scrollTo && !options.scroll.outerHTML) {
273 + options.scroll = $(options.scroll);
274 + this._isScrollChild = Element.childOf(this.element, options.scroll);
275 + }
276 +
277 + Element.makePositioned(this.element); // fix IE
278 +
279 + this.delta = this.currentDelta();
280 + this.options = options;
281 + this.dragging = false;
282 +
283 + this.eventMouseDown = this.initDrag.bindAsEventListener(this);
284 + Event.observe(this.handle, "mousedown", this.eventMouseDown);
285 +
286 + Draggables.register(this);
287 + },
288 +
289 + destroy: function() {
290 + Event.stopObserving(this.handle, "mousedown", this.eventMouseDown);
291 + Draggables.unregister(this);
292 + },
293 +
294 + currentDelta: function() {
295 + return([
296 + parseInt(Element.getStyle(this.element,'left') || '0'),
297 + parseInt(Element.getStyle(this.element,'top') || '0')]);
298 + },
299 +
300 + initDrag: function(event) {
301 + if(typeof Draggable._dragging[this.element] != 'undefined' &&
302 + Draggable._dragging[this.element]) return;
303 + if(Event.isLeftClick(event)) {
304 + // abort on form elements, fixes a Firefox issue
305 + var src = Event.element(event);
306 + if(src.tagName && (
307 + src.tagName=='INPUT' ||
308 + src.tagName=='SELECT' ||
309 + src.tagName=='OPTION' ||
310 + src.tagName=='BUTTON' ||
311 + src.tagName=='TEXTAREA')) return;
312 +
313 + var pointer = [Event.pointerX(event), Event.pointerY(event)];
314 + var pos = Position.cumulativeOffset(this.element);
315 + this.offset = [0,1].map( function(i) { return (pointer[i] - pos[i]) });
316 +
317 + Draggables.activate(this);
318 + Event.stop(event);
319 + }
320 + },
321 +
322 + startDrag: function(event) {
323 + this.dragging = true;
324 +
325 + if(this.options.zindex) {
326 + this.originalZ = parseInt(Element.getStyle(this.element,'z-index') || 0);
327 + this.element.style.zIndex = this.options.zindex;
328 + }
329 +
330 + if(this.options.ghosting) {
331 + this._clone = this.element.cloneNode(true);
332 + Position.absolutize(this.element);
333 + this.element.parentNode.insertBefore(this._clone, this.element);
334 + }
335 +
336 + if(this.options.scroll) {
337 + if (this.options.scroll == window) {
338 + var where = this._getWindowScroll(this.options.scroll);
339 + this.originalScrollLeft = where.left;
340 + this.originalScrollTop = where.top;
341 + } else {
342 + this.originalScrollLeft = this.options.scroll.scrollLeft;
343 + this.originalScrollTop = this.options.scroll.scrollTop;
344 + }
345 + }
346 +
347 + Draggables.notify('onStart', this, event);
348 +
349 + if(this.options.starteffect) this.options.starteffect(this.element);
350 + },
351 +
352 + updateDrag: function(event, pointer) {
353 + if(!this.dragging) this.startDrag(event);
354 + Position.prepare();
355 + Droppables.show(pointer, this.element);
356 + Draggables.notify('onDrag', this, event);
357 +
358 + this.draw(pointer);
359 + if(this.options.change) this.options.change(this);
360 +
361 + if(this.options.scroll) {
362 + this.stopScrolling();
363 +
364 + var p;
365 + if (this.options.scroll == window) {
366 + with(this._getWindowScroll(this.options.scroll)) { p = [ left, top, left+width, top+height ]; }
367 + } else {
368 + p = Position.page(this.options.scroll);
369 + p[0] += this.options.scroll.scrollLeft + Position.deltaX;
370 + p[1] += this.options.scroll.scrollTop + Position.deltaY;
371 + p.push(p[0]+this.options.scroll.offsetWidth);
372 + p.push(p[1]+this.options.scroll.offsetHeight);
373 + }
374 + var speed = [0,0];
375 + if(pointer[0] < (p[0]+this.options.scrollSensitivity)) speed[0] = pointer[0]-(p[0]+this.options.scrollSensitivity);
376 + if(pointer[1] < (p[1]+this.options.scrollSensitivity)) speed[1] = pointer[1]-(p[1]+this.options.scrollSensitivity);
377 + if(pointer[0] > (p[2]-this.options.scrollSensitivity)) speed[0] = pointer[0]-(p[2]-this.options.scrollSensitivity);
378 + if(pointer[1] > (p[3]-this.options.scrollSensitivity)) speed[1] = pointer[1]-(p[3]-this.options.scrollSensitivity);
379 + this.startScrolling(speed);
380 + }
381 +
382 + // fix AppleWebKit rendering
383 + if(navigator.appVersion.indexOf('AppleWebKit')>0) window.scrollBy(0,0);
384 +
385 + Event.stop(event);
386 + },
387 +
388 + finishDrag: function(event, success) {
389 + this.dragging = false;
390 +
391 + if(this.options.ghosting) {
392 + Position.relativize(this.element);
393 + Element.remove(this._clone);
394 + this._clone = null;
395 + }
396 +
397 + if(success) Droppables.fire(event, this.element);
398 + Draggables.notify('onEnd', this, event);
399 +
400 + var revert = this.options.revert;
401 + if(revert && typeof revert == 'function') revert = revert(this.element);
402 +
403 + var d = this.currentDelta();
404 + if(revert && this.options.reverteffect) {
405 + this.options.reverteffect(this.element,
406 + d[1]-this.delta[1], d[0]-this.delta[0]);
407 + } else {
408 + this.delta = d;
409 + }
410 +
411 + if(this.options.zindex)
412 + this.element.style.zIndex = this.originalZ;
413 +
414 + if(this.options.endeffect)
415 + this.options.endeffect(this.element);
416 +
417 + Draggables.deactivate(this);
418 + Droppables.reset();
419 + },
420 +
421 + keyPress: function(event) {
422 + if(event.keyCode!=Event.KEY_ESC) return;
423 + this.finishDrag(event, false);
424 + Event.stop(event);
425 + },
426 +
427 + endDrag: function(event) {
428 + if(!this.dragging) return;
429 + this.stopScrolling();
430 + this.finishDrag(event, true);
431 + Event.stop(event);
432 + },
433 +
434 + draw: function(point) {
435 + var pos = Position.cumulativeOffset(this.element);
436 + if(this.options.ghosting) {
437 + var r = Position.realOffset(this.element);
438 + pos[0] += r[0] - Position.deltaX; pos[1] += r[1] - Position.deltaY;
439 + }
440 +
441 + var d = this.currentDelta();
442 + pos[0] -= d[0]; pos[1] -= d[1];
443 +
444 + if(this.options.scroll && (this.options.scroll != window && this._isScrollChild)) {
445 + pos[0] -= this.options.scroll.scrollLeft-this.originalScrollLeft;
446 + pos[1] -= this.options.scroll.scrollTop-this.originalScrollTop;
447 + }
448 +
449 + var p = [0,1].map(function(i){
450 + return (point[i]-pos[i]-this.offset[i])
451 + }.bind(this));
452 +
453 + if(this.options.snap) {
454 + if(typeof this.options.snap == 'function') {
455 + p = this.options.snap(p[0],p[1],this);
456 + } else {
457 + if(this.options.snap instanceof Array) {
458 + p = p.map( function(v, i) {
459 + return Math.round(v/this.options.snap[i])*this.options.snap[i] }.bind(this))
460 + } else {
461 + p = p.map( function(v) {
462 + return Math.round(v/this.options.snap)*this.options.snap }.bind(this))
463 + }
464 + }}
465 +
466 + var style = this.element.style;
467 + if((!this.options.constraint) || (this.options.constraint=='horizontal'))
468 + style.left = p[0] + "px";
469 + if((!this.options.constraint) || (this.options.constraint=='vertical'))
470 + style.top = p[1] + "px";
471 +
472 + if(style.visibility=="hidden") style.visibility = ""; // fix gecko rendering
473 + },
474 +
475 + stopScrolling: function() {
476 + if(this.scrollInterval) {
477 + clearInterval(this.scrollInterval);
478 + this.scrollInterval = null;
479 + Draggables._lastScrollPointer = null;
480 + }
481 + },
482 +
483 + startScrolling: function(speed) {
484 + if(!(speed[0] || speed[1])) return;
485 + this.scrollSpeed = [speed[0]*this.options.scrollSpeed,speed[1]*this.options.scrollSpeed];
486 + this.lastScrolled = new Date();
487 + this.scrollInterval = setInterval(this.scroll.bind(this), 10);
488 + },
489 +
490 + scroll: function() {
491 + var current = new Date();
492 + var delta = current - this.lastScrolled;
493 + this.lastScrolled = current;
494 + if(this.options.scroll == window) {
495 + with (this._getWindowScroll(this.options.scroll)) {
496 + if (this.scrollSpeed[0] || this.scrollSpeed[1]) {
497 + var d = delta / 1000;
498 + this.options.scroll.scrollTo( left + d*this.scrollSpeed[0], top + d*this.scrollSpeed[1] );
499 + }
500 + }
501 + } else {
502 + this.options.scroll.scrollLeft += this.scrollSpeed[0] * delta / 1000;
503 + this.options.scroll.scrollTop += this.scrollSpeed[1] * delta / 1000;
504 + }
505 +
506 + Position.prepare();
507 + Droppables.show(Draggables._lastPointer, this.element);
508 + Draggables.notify('onDrag', this);
509 + if (this._isScrollChild) {
510 + Draggables._lastScrollPointer = Draggables._lastScrollPointer || $A(Draggables._lastPointer);
511 + Draggables._lastScrollPointer[0] += this.scrollSpeed[0] * delta / 1000;
512 + Draggables._lastScrollPointer[1] += this.scrollSpeed[1] * delta / 1000;
513 + if (Draggables._lastScrollPointer[0] < 0)
514 + Draggables._lastScrollPointer[0] = 0;
515 + if (Draggables._lastScrollPointer[1] < 0)
516 + Draggables._lastScrollPointer[1] = 0;
517 + this.draw(Draggables._lastScrollPointer);
518 + }
519 +
520 + if(this.options.change) this.options.change(this);
521 + },
522 +
523 + _getWindowScroll: function(w) {
524 + var T, L, W, H;
525 + with (w.document) {
526 + if (w.document.documentElement && documentElement.scrollTop) {
527 + T = documentElement.scrollTop;
528 + L = documentElement.scrollLeft;
529 + } else if (w.document.body) {
530 + T = body.scrollTop;
531 + L = body.scrollLeft;
532 + }
533 + if (w.innerWidth) {
534 + W = w.innerWidth;
535 + H = w.innerHeight;
536 + } else if (w.document.documentElement && documentElement.clientWidth) {
537 + W = documentElement.clientWidth;
538 + H = documentElement.clientHeight;
539 + } else {
540 + W = body.offsetWidth;
541 + H = body.offsetHeight
542 + }
543 + }
544 + return { top: T, left: L, width: W, height: H };
545 + }
546 + }
547 +
548 + /*--------------------------------------------------------------------------*/
549 +
550 + var SortableObserver = Class.create();
551 + SortableObserver.prototype = {
552 + initialize: function(element, observer) {
553 + this.element = $(element);
554 + this.observer = observer;
555 + this.lastValue = Sortable.serialize(this.element);
556 + },
557 +
558 + onStart: function() {
559 + this.lastValue = Sortable.serialize(this.element);
560 + },
561 +
562 + onEnd: function() {
563 + Sortable.unmark();
564 + if(this.lastValue != Sortable.serialize(this.element))
565 + this.observer(this.element)
566 + }
567 + }
568 +
569 + var Sortable = {
570 + SERIALIZE_RULE: /^[^_\-](?:[A-Za-z0-9\-\_]*)[_](.*)$/,
571 +
572 + sortables: {},
573 +
574 + _findRootElement: function(element) {
575 + while (element.tagName != "BODY") {
576 + if(element.id && Sortable.sortables[element.id]) return element;
577 + element = element.parentNode;
578 + }
579 + },
580 +
581 + options: function(element) {
582 + element = Sortable._findRootElement($(element));
583 + if(!element) return;
584 + return Sortable.sortables[element.id];
585 + },
586 +
587 + destroy: function(element){
588 + var s = Sortable.options(element);
589 +
590 + if(s) {
591 + Draggables.removeObserver(s.element);
592 + s.droppables.each(function(d){ Droppables.remove(d) });
593 + s.draggables.invoke('destroy');
594 +
595 + delete Sortable.sortables[s.element.id];
596 + }
597 + },
598 +
599 + create: function(element) {
600 + element = $(element);
601 + var options = Object.extend({
602 + element: element,
603 + tag: 'li', // assumes li children, override with tag: 'tagname'
604 + dropOnEmpty: false,
605 + tree: false,
606 + treeTag: 'ul',
607 + overlap: 'vertical', // one of 'vertical', 'horizontal'
608 + constraint: 'vertical', // one of 'vertical', 'horizontal', false
609 + containment: element, // also takes array of elements (or id's); or false
610 + handle: false, // or a CSS class
611 + only: false,
612 + delay: 0,
613 + hoverclass: null,
614 + ghosting: false,
615 + scroll: false,
616 + scrollSensitivity: 20,
617 + scrollSpeed: 15,
618 + format: this.SERIALIZE_RULE,
619 + onChange: Prototype.emptyFunction,
620 + onUpdate: Prototype.emptyFunction
621 + }, arguments[1] || {});
622 +
623 + // clear any old sortable with same element
624 + this.destroy(element);
625 +
626 + // build options for the draggables
627 + var options_for_draggable = {
628 + revert: true,
629 + scroll: options.scroll,
630 + scrollSpeed: options.scrollSpeed,
631 + scrollSensitivity: options.scrollSensitivity,
632 + delay: options.delay,
633 + ghosting: options.ghosting,
634 + constraint: options.constraint,
635 + handle: options.handle };
636 +
637 + if(options.starteffect)
638 + options_for_draggable.starteffect = options.starteffect;
639 +
640 + if(options.reverteffect)
641 + options_for_draggable.reverteffect = options.reverteffect;
642 + else
643 + if(options.ghosting) options_for_draggable.reverteffect = function(element) {
644 + element.style.top = 0;
645 + element.style.left = 0;
646 + };
647 +
648 + if(options.endeffect)
649 + options_for_draggable.endeffect = options.endeffect;
650 +
651 + if(options.zindex)
652 + options_for_draggable.zindex = options.zindex;
653 +
654 + // build options for the droppables
655 + var options_for_droppable = {
656 + overlap: options.overlap,
657 + containment: options.containment,
658 + tree: options.tree,
659 + hoverclass: options.hoverclass,
660 + onHover: Sortable.onHover
661 + }
662 +
663 + var options_for_tree = {
664 + onHover: Sortable.onEmptyHover,
665 + overlap: options.overlap,
666 + containment: options.containment,
667 + hoverclass: options.hoverclass
668 + }
669 +
670 + // fix for gecko engine
671 + Element.cleanWhitespace(element);
672 +
673 + options.draggables = [];
674 + options.droppables = [];
675 +
676 + // drop on empty handling
677 + if(options.dropOnEmpty || options.tree) {
678 + Droppables.add(element, options_for_tree);
679 + options.droppables.push(element);
680 + }
681 +
682 + (this.findElements(element, options) || []).each( function(e) {
683 + // handles are per-draggable
684 + var handle = options.handle ?
685 + $(e).down('.'+options.handle,0) : e;
686 + options.draggables.push(
687 + new Draggable(e, Object.extend(options_for_draggable, { handle: handle })));
688 + Droppables.add(e, options_for_droppable);
689 + if(options.tree) e.treeNode = element;
690 + options.droppables.push(e);
691 + });
692 +
693 + if(options.tree) {
694 + (Sortable.findTreeElements(element, options) || []).each( function(e) {
695 + Droppables.add(e, options_for_tree);
696 + e.treeNode = element;
697 + options.droppables.push(e);
698 + });
699 + }
700 +
701 + // keep reference
702 + this.sortables[element.id] = options;
703 +
704 + // for onupdate
705 + Draggables.addObserver(new SortableObserver(element, options.onUpdate));
706 +
707 + },
708 +
709 + // return all suitable-for-sortable elements in a guaranteed order
710 + findElements: function(element, options) {
711 + return Element.findChildren(
712 + element, options.only, options.tree ? true : false, options.tag);
713 + },
714 +
715 + findTreeElements: function(element, options) {
716 + return Element.findChildren(
717 + element, options.only, options.tree ? true : false, options.treeTag);
718 + },
719 +
720 + onHover: function(element, dropon, overlap) {
721 + if(Element.isParent(dropon, element)) return;
722 +
723 + if(overlap > .33 && overlap < .66 && Sortable.options(dropon).tree) {
724 + return;
725 + } else if(overlap>0.5) {
726 + Sortable.mark(dropon, 'before');
727 + if(dropon.previousSibling != element) {
728 + var oldParentNode = element.parentNode;
729 + element.style.visibility = "hidden"; // fix gecko rendering
730 + dropon.parentNode.insertBefore(element, dropon);
731 + if(dropon.parentNode!=oldParentNode)
732 + Sortable.options(oldParentNode).onChange(element);
733 + Sortable.options(dropon.parentNode).onChange(element);
734 + }
735 + } else {
736 + Sortable.mark(dropon, 'after');
737 + var nextElement = dropon.nextSibling || null;
738 + if(nextElement != element) {
739 + var oldParentNode = element.parentNode;
740 + element.style.visibility = "hidden"; // fix gecko rendering
741 + dropon.parentNode.insertBefore(element, nextElement);
742 + if(dropon.parentNode!=oldParentNode)
743 + Sortable.options(oldParentNode).onChange(element);
744 + Sortable.options(dropon.parentNode).onChange(element);
745 + }
746 + }
747 + },
748 +
749 + onEmptyHover: function(element, dropon, overlap) {
750 + var oldParentNode = element.parentNode;
751 + var droponOptions = Sortable.options(dropon);
752 +
753 + if(!Element.isParent(dropon, element)) {
754 + var index;
755 +
756 + var children = Sortable.findElements(dropon, {tag: droponOptions.tag, only: droponOptions.only});
757 + var child = null;
758 +
759 + if(children) {
760 + var offset = Element.offsetSize(dropon, droponOptions.overlap) * (1.0 - overlap);
761 +
762 + for (index = 0; index < children.length; index += 1) {
763 + if (offset - Element.offsetSize (children[index], droponOptions.overlap) >= 0) {
764 + offset -= Element.offsetSize (children[index], droponOptions.overlap);
765 + } else if (offset - (Element.offsetSize (children[index], droponOptions.overlap) / 2) >= 0) {
766 + child = index + 1 < children.length ? children[index + 1] : null;
767 + break;
768 + } else {
769 + child = children[index];
770 + break;
771 + }
772 + }
773 + }
774 +
775 + dropon.insertBefore(element, child);
776 +
777 + Sortable.options(oldParentNode).onChange(element);
778 + droponOptions.onChange(element);
779 + }
780 + },
781 +
782 + unmark: function() {
783 + if(Sortable._marker) Sortable._marker.hide();
784 + },
785 +
786 + mark: function(dropon, position) {
787 + // mark on ghosting only
788 + var sortable = Sortable.options(dropon.parentNode);
789 + if(sortable && !sortable.ghosting) return;
790 +
791 + if(!Sortable._marker) {
792 + Sortable._marker =
793 + ($('dropmarker') || Element.extend(document.createElement('DIV'))).
794 + hide().addClassName('dropmarker').setStyle({position:'absolute'});
795 + document.getElementsByTagName("body").item(0).appendChild(Sortable._marker);
796 + }
797 + var offsets = Position.cumulativeOffset(dropon);
798 + Sortable._marker.setStyle({left: offsets[0]+'px', top: offsets[1] + 'px'});
799 +
800 + if(position=='after')
801 + if(sortable.overlap == 'horizontal')
802 + Sortable._marker.setStyle({left: (offsets[0]+dropon.clientWidth) + 'px'});
803 + else
804 + Sortable._marker.setStyle({top: (offsets[1]+dropon.clientHeight) + 'px'});
805 +
806 + Sortable._marker.show();
807 + },
808 +
809 + _tree: function(element, options, parent) {
810 + var children = Sortable.findElements(element, options) || [];
811 +
812 + for (var i = 0; i < children.length; ++i) {
813 + var match = children[i].id.match(options.format);
814 +
815 + if (!match) continue;
816 +
817 + var child = {
818 + id: encodeURIComponent(match ? match[1] : null),
819 + element: element,
820 + parent: parent,
821 + children: [],
822 + position: parent.children.length,
823 + container: $(children[i]).down(options.treeTag)
824 + }
825 +
826 + /* Get the element containing the children and recurse over it */
827 + if (child.container)
828 + this._tree(child.container, options, child)
829 +
830 + parent.children.push (child);
831 + }
832 +
833 + return parent;
834 + },
835 +
836 + tree: function(element) {
837 + element = $(element);
838 + var sortableOptions = this.options(element);
839 + var options = Object.extend({
840 + tag: sortableOptions.tag,
841 + treeTag: sortableOptions.treeTag,
842 + only: sortableOptions.only,
843 + name: element.id,
844 + format: sortableOptions.format
845 + }, arguments[1] || {});
846 +
847 + var root = {
848 + id: null,
849 + parent: null,
850 + children: [],
851 + container: element,
852 + position: 0
853 + }
854 +
855 + return Sortable._tree(element, options, root);
856 + },
857 +
858 + /* Construct a [i] index for a particular node */
859 + _constructIndex: function(node) {
860 + var index = '';
861 + do {
862 + if (node.id) index = '[' + node.position + ']' + index;
863 + } while ((node = node.parent) != null);
864 + return index;
865 + },
866 +
867 + sequence: function(element) {
868 + element = $(element);
869 + var options = Object.extend(this.options(element), arguments[1] || {});
870 +
871 + return $(this.findElements(element, options) || []).map( function(item) {
872 + return item.id.match(options.format) ? item.id.match(options.format)[1] : '';
873 + });
874 + },
875 +
876 + setSequence: function(element, new_sequence) {
877 + element = $(element);
878 + var options = Object.extend(this.options(element), arguments[2] || {});
879 +
880 + var nodeMap = {};
881 + this.findElements(element, options).each( function(n) {
882 + if (n.id.match(options.format))
883 + nodeMap[n.id.match(options.format)[1]] = [n, n.parentNode];
884 + n.parentNode.removeChild(n);
885 + });
886 +
887 + new_sequence.each(function(ident) {
888 + var n = nodeMap[ident];
889 + if (n) {
890 + n[1].appendChild(n[0]);
891 + delete nodeMap[ident];
892 + }
893 + });
894 + },
895 +
896 + serialize: function(element) {
897 + element = $(element);
898 + var options = Object.extend(Sortable.options(element), arguments[1] || {});
899 + var name = encodeURIComponent(
900 + (arguments[1] && arguments[1].name) ? arguments[1].name : element.id);
901 +
902 + if (options.tree) {
903 + return Sortable.tree(element, arguments[1]).children.map( function (item) {
904 + return [name + Sortable._constructIndex(item) + "[id]=" +
905 + encodeURIComponent(item.id)].concat(item.children.map(arguments.callee));
906 + }).flatten().join('&');
907 + } else {
908 + return Sortable.sequence(element, arguments[1]).map( function(item) {
909 + return name + "[]=" + encodeURIComponent(item);
910 + }).join('&');
911 + }
912 + }
913 + }
914 +
915 + // Returns true if child is contained within element
916 + Element.isParent = function(child, element) {
917 + if (!child.parentNode || child == element) return false;
918 + if (child.parentNode == element) return true;
919 + return Element.isParent(child.parentNode, element);
920 + }
921 +
922 + Element.findChildren = function(element, only, recursive, tagName) {
923 + if(!element.hasChildNodes()) return null;
924 + tagName = tagName.toUpperCase();
925 + if(only) only = [only].flatten();
926 + var elements = [];
927 + $A(element.childNodes).each( function(e) {
928 + if(e.tagName && e.tagName.toUpperCase()==tagName &&
929 + (!only || (Element.classNames(e).detect(function(v) { return only.include(v) }))))
930 + elements.push(e);
931 + if(recursive) {
932 + var grandchildren = Element.findChildren(e, only, recursive, tagName);
933 + if(grandchildren) elements.push(grandchildren);
934 + }
935 + });
936 +
937 + return (elements.length>0 ? elements.flatten() : []);
938 + }
939 +
940 + Element.offsetSize = function (element, type) {
941 + return element['offset' + ((type=='vertical' || type=='height') ? 'Height' : 'Width')];
942 + }
This diff has been collapsed as it changes many lines, (1088 lines changed) Show them Hide them
@@ -0,0 +1,1088
1 + // Copyright (c) 2005, 2006 Thomas Fuchs (http://script.aculo.us, http://mir.aculo.us)
2 + // Contributors:
3 + // Justin Palmer (http://encytemedia.com/)
4 + // Mark Pilgrim (http://diveintomark.org/)
5 + // Martin Bialasinki
6 + //
7 + // script.aculo.us is freely distributable under the terms of an MIT-style license.
8 + // For details, see the script.aculo.us web site: http://script.aculo.us/
9 +
10 + // converts rgb() and #xxx to #xxxxxx format,
11 + // returns self (or first argument) if not convertable
12 + String.prototype.parseColor = function() {
13 + var color = '#';
14 + if(this.slice(0,4) == 'rgb(') {
15 + var cols = this.slice(4,this.length-1).split(',');
16 + var i=0; do { color += parseInt(cols[i]).toColorPart() } while (++i<3);
17 + } else {
18 + if(this.slice(0,1) == '#') {
19 + if(this.length==4) for(var i=1;i<4;i++) color += (this.charAt(i) + this.charAt(i)).toLowerCase();
20 + if(this.length==7) color = this.toLowerCase();
21 + }
22 + }
23 + return(color.length==7 ? color : (arguments[0] || this));
24 + }
25 +
26 + /*--------------------------------------------------------------------------*/
27 +
28 + Element.collectTextNodes = function(element) {
29 + return $A($(element).childNodes).collect( function(node) {
30 + return (node.nodeType==3 ? node.nodeValue :
31 + (node.hasChildNodes() ? Element.collectTextNodes(node) : ''));
32 + }).flatten().join('');
33 + }
34 +
35 + Element.collectTextNodesIgnoreClass = function(element, className) {
36 + return $A($(element).childNodes).collect( function(node) {
37 + return (node.nodeType==3 ? node.nodeValue :
38 + ((node.hasChildNodes() && !Element.hasClassName(node,className)) ?
39 + Element.collectTextNodesIgnoreClass(node, className) : ''));
40 + }).flatten().join('');
41 + }
42 +
43 + Element.setContentZoom = function(element, percent) {
44 + element = $(element);
45 + element.setStyle({fontSize: (percent/100) + 'em'});
46 + if(navigator.appVersion.indexOf('AppleWebKit')>0) window.scrollBy(0,0);
47 + return element;
48 + }
49 +
50 + Element.getOpacity = function(element){
51 + element = $(element);
52 + var opacity;
53 + if (opacity = element.getStyle('opacity'))
54 + return parseFloat(opacity);
55 + if (opacity = (element.getStyle('filter') || '').match(/alpha\(opacity=(.*)\)/))
56 + if(opacity[1]) return parseFloat(opacity[1]) / 100;
57 + return 1.0;
58 + }
59 +
60 + Element.setOpacity = function(element, value){
61 + element= $(element);
62 + if (value == 1){
63 + element.setStyle({ opacity:
64 + (/Gecko/.test(navigator.userAgent) && !/Konqueror|Safari|KHTML/.test(navigator.userAgent)) ?
65 + 0.999999 : 1.0 });
66 + if(/MSIE/.test(navigator.userAgent) && !window.opera)
67 + element.setStyle({filter: Element.getStyle(element,'filter').replace(/alpha\([^\)]*\)/gi,'')});
68 + } else {
69 + if(value < 0.00001) value = 0;
70 + element.setStyle({opacity: value});
71 + if(/MSIE/.test(navigator.userAgent) && !window.opera)
72 + element.setStyle(
73 + { filter: element.getStyle('filter').replace(/alpha\([^\)]*\)/gi,'') +
74 + 'alpha(opacity='+value*100+')' });
75 + }
76 + return element;
77 + }
78 +
79 + Element.getInlineOpacity = function(element){
80 + return $(element).style.opacity || '';
81 + }
82 +
83 + Element.forceRerendering = function(element) {
84 + try {
85 + element = $(element);
86 + var n = document.createTextNode(' ');
87 + element.appendChild(n);
88 + element.removeChild(n);
89 + } catch(e) { }
90 + };
91 +
92 + /*--------------------------------------------------------------------------*/
93 +
94 + Array.prototype.call = function() {
95 + var args = arguments;
96 + this.each(function(f){ f.apply(this, args) });
97 + }
98 +
99 + /*--------------------------------------------------------------------------*/
100 +
101 + var Effect = {
102 + _elementDoesNotExistError: {
103 + name: 'ElementDoesNotExistError',
104 + message: 'The specified DOM element does not exist, but is required for this effect to operate'
105 + },
106 + tagifyText: function(element) {
107 + if(typeof Builder == 'undefined')
108 + throw("Effect.tagifyText requires including script.aculo.us' builder.js library");
109 +
110 + var tagifyStyle = 'position:relative';
111 + if(/MSIE/.test(navigator.userAgent) && !window.opera) tagifyStyle += ';zoom:1';
112 +
113 + element = $(element);
114 + $A(element.childNodes).each( function(child) {
115 + if(child.nodeType==3) {
116 + child.nodeValue.toArray().each( function(character) {
117 + element.insertBefore(
118 + Builder.node('span',{style: tagifyStyle},
119 + character == ' ' ? String.fromCharCode(160) : character),
120 + child);
121 + });
122 + Element.remove(child);
123 + }
124 + });
125 + },
126 + multiple: function(element, effect) {
127 + var elements;
128 + if(((typeof element == 'object') ||
129 + (typeof element == 'function')) &&
130 + (element.length))
131 + elements = element;
132 + else
133 + elements = $(element).childNodes;
134 +
135 + var options = Object.extend({
136 + speed: 0.1,
137 + delay: 0.0
138 + }, arguments[2] || {});
139 + var masterDelay = options.delay;
140 +
141 + $A(elements).each( function(element, index) {
142 + new effect(element, Object.extend(options, { delay: index * options.speed + masterDelay }));
143 + });
144 + },
145 + PAIRS: {
146 + 'slide': ['SlideDown','SlideUp'],
147 + 'blind': ['BlindDown','BlindUp'],
148 + 'appear': ['Appear','Fade']
149 + },
150 + toggle: function(element, effect) {
151 + element = $(element);
152 + effect = (effect || 'appear').toLowerCase();
153 + var options = Object.extend({
154 + queue: { position:'end', scope:(element.id || 'global'), limit: 1 }
155 + }, arguments[2] || {});
156 + Effect[element.visible() ?
157 + Effect.PAIRS[effect][1] : Effect.PAIRS[effect][0]](element, options);
158 + }
159 + };
160 +
161 + var Effect2 = Effect; // deprecated
162 +
163 + /* ------------- transitions ------------- */
164 +
165 + Effect.Transitions = {
166 + linear: Prototype.K,
167 + sinoidal: function(pos) {
168 + return (-Math.cos(pos*Math.PI)/2) + 0.5;
169 + },
170 + reverse: function(pos) {
171 + return 1-pos;
172 + },
173 + flicker: function(pos) {
174 + return ((-Math.cos(pos*Math.PI)/4) + 0.75) + Math.random()/4;
175 + },
176 + wobble: function(pos) {
177 + return (-Math.cos(pos*Math.PI*(9*pos))/2) + 0.5;
178 + },
179 + pulse: function(pos, pulses) {
180 + pulses = pulses || 5;
181 + return (
182 + Math.round((pos % (1/pulses)) * pulses) == 0 ?
183 + ((pos * pulses * 2) - Math.floor(pos * pulses * 2)) :
184 + 1 - ((pos * pulses * 2) - Math.floor(pos * pulses * 2))
185 + );
186 + },
187 + none: function(pos) {
188 + return 0;
189 + },
190 + full: function(pos) {
191 + return 1;
192 + }
193 + };
194 +
195 + /* ------------- core effects ------------- */
196 +
197 + Effect.ScopedQueue = Class.create();
198 + Object.extend(Object.extend(Effect.ScopedQueue.prototype, Enumerable), {
199 + initialize: function() {
200 + this.effects = [];
201 + this.interval = null;
202 + },
203 + _each: function(iterator) {
204 + this.effects._each(iterator);
205 + },
206 + add: function(effect) {
207 + var timestamp = new Date().getTime();
208 +
209 + var position = (typeof effect.options.queue == 'string') ?
210 + effect.options.queue : effect.options.queue.position;
211 +
212 + switch(position) {
213 + case 'front':
214 + // move unstarted effects after this effect
215 + this.effects.findAll(function(e){ return e.state=='idle' }).each( function(e) {
216 + e.startOn += effect.finishOn;
217 + e.finishOn += effect.finishOn;
218 + });
219 + break;
220 + case 'with-last':
221 + timestamp = this.effects.pluck('startOn').max() || timestamp;
222 + break;
223 + case 'end':
224 + // start effect after last queued effect has finished
225 + timestamp = this.effects.pluck('finishOn').max() || timestamp;
226 + break;
227 + }
228 +
229 + effect.startOn += timestamp;
230 + effect.finishOn += timestamp;
231 +
232 + if(!effect.options.queue.limit || (this.effects.length < effect.options.queue.limit))
233 + this.effects.push(effect);
234 +
235 + if(!this.interval)
236 + this.interval = setInterval(this.loop.bind(this), 40);
237 + },
238 + remove: function(effect) {
239 + this.effects = this.effects.reject(function(e) { return e==effect });
240 + if(this.effects.length == 0) {
241 + clearInterval(this.interval);
242 + this.interval = null;
243 + }
244 + },
245 + loop: function() {
246 + var timePos = new Date().getTime();
247 + this.effects.invoke('loop', timePos);
248 + }
249 + });
250 +
251 + Effect.Queues = {
252 + instances: $H(),
253 + get: function(queueName) {
254 + if(typeof queueName != 'string') return queueName;
255 +
256 + if(!this.instances[queueName])
257 + this.instances[queueName] = new Effect.ScopedQueue();
258 +
259 + return this.instances[queueName];
260 + }
261 + }
262 + Effect.Queue = Effect.Queues.get('global');
263 +
264 + Effect.DefaultOptions = {
265 + transition: Effect.Transitions.sinoidal,
266 + duration: 1.0, // seconds
267 + fps: 25.0, // max. 25fps due to Effect.Queue implementation
268 + sync: false, // true for combining
269 + from: 0.0,
270 + to: 1.0,
271 + delay: 0.0,
272 + queue: 'parallel'
273 + }
274 +
275 + Effect.Base = function() {};
276 + Effect.Base.prototype = {
277 + position: null,
278 + start: function(options) {
279 + this.options = Object.extend(Object.extend({},Effect.DefaultOptions), options || {});
280 + this.currentFrame = 0;
281 + this.state = 'idle';
282 + this.startOn = this.options.delay*1000;
283 + this.finishOn = this.startOn + (this.options.duration*1000);
284 + this.event('beforeStart');
285 + if(!this.options.sync)
286 + Effect.Queues.get(typeof this.options.queue == 'string' ?
287 + 'global' : this.options.queue.scope).add(this);
288 + },
289 + loop: function(timePos) {
290 + if(timePos >= this.startOn) {
291 + if(timePos >= this.finishOn) {
292 + this.render(1.0);
293 + this.cancel();
294 + this.event('beforeFinish');
295 + if(this.finish) this.finish();
296 + this.event('afterFinish');
297 + return;
298 + }
299 + var pos = (timePos - this.startOn) / (this.finishOn - this.startOn);
300 + var frame = Math.round(pos * this.options.fps * this.options.duration);
301 + if(frame > this.currentFrame) {
302 + this.render(pos);
303 + this.currentFrame = frame;
304 + }
305 + }
306 + },
307 + render: function(pos) {
308 + if(this.state == 'idle') {
309 + this.state = 'running';
310 + this.event('beforeSetup');
311 + if(this.setup) this.setup();
312 + this.event('afterSetup');
313 + }
314 + if(this.state == 'running') {
315 + if(this.options.transition) pos = this.options.transition(pos);
316 + pos *= (this.options.to-this.options.from);
317 + pos += this.options.from;
318 + this.position = pos;
319 + this.event('beforeUpdate');
320 + if(this.update) this.update(pos);
321 + this.event('afterUpdate');
322 + }
323 + },
324 + cancel: function() {
325 + if(!this.options.sync)
326 + Effect.Queues.get(typeof this.options.queue == 'string' ?
327 + 'global' : this.options.queue.scope).remove(this);
328 + this.state = 'finished';
329 + },
330 + event: function(eventName) {
331 + if(this.options[eventName + 'Internal']) this.options[eventName + 'Internal'](this);
332 + if(this.options[eventName]) this.options[eventName](this);
333 + },
334 + inspect: function() {
335 + return '#<Effect:' + $H(this).inspect() + ',options:' + $H(this.options).inspect() + '>';
336 + }
337 + }
338 +
339 + Effect.Parallel = Class.create();
340 + Object.extend(Object.extend(Effect.Parallel.prototype, Effect.Base.prototype), {
341 + initialize: function(effects) {
342 + this.effects = effects || [];
343 + this.start(arguments[1]);
344 + },
345 + update: function(position) {
346 + this.effects.invoke('render', position);
347 + },
348 + finish: function(position) {
349 + this.effects.each( function(effect) {
350 + effect.render(1.0);
351 + effect.cancel();
352 + effect.event('beforeFinish');
353 + if(effect.finish) effect.finish(position);
354 + effect.event('afterFinish');
355 + });
356 + }
357 + });
358 +
359 + Effect.Event = Class.create();
360 + Object.extend(Object.extend(Effect.Event.prototype, Effect.Base.prototype), {
361 + initialize: function() {
362 + var options = Object.extend({
363 + duration: 0
364 + }, arguments[0] || {});
365 + this.start(options);
366 + },
367 + update: Prototype.emptyFunction
368 + });
369 +
370 + Effect.Opacity = Class.create();
371 + Object.extend(Object.extend(Effect.Opacity.prototype, Effect.Base.prototype), {
372 + initialize: function(element) {
373 + this.element = $(element);
374 + if(!this.element) throw(Effect._elementDoesNotExistError);
375 + // make this work on IE on elements without 'layout'
376 + if(/MSIE/.test(navigator.userAgent) && !window.opera && (!this.element.currentStyle.hasLayout))
377 + this.element.setStyle({zoom: 1});
378 + var options = Object.extend({
379 + from: this.element.getOpacity() || 0.0,
380 + to: 1.0
381 + }, arguments[1] || {});
382 + this.start(options);
383 + },
384 + update: function(position) {
385 + this.element.setOpacity(position);
386 + }
387 + });
388 +
389 + Effect.Move = Class.create();
390 + Object.extend(Object.extend(Effect.Move.prototype, Effect.Base.prototype), {
391 + initialize: function(element) {
392 + this.element = $(element);
393 + if(!this.element) throw(Effect._elementDoesNotExistError);
394 + var options = Object.extend({
395 + x: 0,
396 + y: 0,
397 + mode: 'relative'
398 + }, arguments[1] || {});
399 + this.start(options);
400 + },
401 + setup: function() {
402 + // Bug in Opera: Opera returns the "real" position of a static element or
403 + // relative element that does not have top/left explicitly set.
404 + // ==> Always set top and left for position relative elements in your stylesheets
405 + // (to 0 if you do not need them)
406 + this.element.makePositioned();
407 + this.originalLeft = parseFloat(this.element.getStyle('left') || '0');
408 + this.originalTop = parseFloat(this.element.getStyle('top') || '0');
409 + if(this.options.mode == 'absolute') {
410 + // absolute movement, so we need to calc deltaX and deltaY
411 + this.options.x = this.options.x - this.originalLeft;
412 + this.options.y = this.options.y - this.originalTop;
413 + }
414 + },
415 + update: function(position) {
416 + this.element.setStyle({
417 + left: Math.round(this.options.x * position + this.originalLeft) + 'px',
418 + top: Math.round(this.options.y * position + this.originalTop) + 'px'
419 + });
420 + }
421 + });
422 +
423 + // for backwards compatibility
424 + Effect.MoveBy = function(element, toTop, toLeft) {
425 + return new Effect.Move(element,
426 + Object.extend({ x: toLeft, y: toTop }, arguments[3] || {}));
427 + };
428 +
429 + Effect.Scale = Class.create();
430 + Object.extend(Object.extend(Effect.Scale.prototype, Effect.Base.prototype), {
431 + initialize: function(element, percent) {
432 + this.element = $(element);
433 + if(!this.element) throw(Effect._elementDoesNotExistError);
434 + var options = Object.extend({
435 + scaleX: true,
436 + scaleY: true,
437 + scaleContent: true,
438 + scaleFromCenter: false,
439 + scaleMode: 'box', // 'box' or 'contents' or {} with provided values
440 + scaleFrom: 100.0,
441 + scaleTo: percent
442 + }, arguments[2] || {});
443 + this.start(options);
444 + },
445 + setup: function() {
446 + this.restoreAfterFinish = this.options.restoreAfterFinish || false;
447 + this.elementPositioning = this.element.getStyle('position');
448 +
449 + this.originalStyle = {};
450 + ['top','left','width','height','fontSize'].each( function(k) {
451 + this.originalStyle[k] = this.element.style[k];
452 + }.bind(this));
453 +
454 + this.originalTop = this.element.offsetTop;
455 + this.originalLeft = this.element.offsetLeft;
456 +
457 + var fontSize = this.element.getStyle('font-size') || '100%';
458 + ['em','px','%','pt'].each( function(fontSizeType) {
459 + if(fontSize.indexOf(fontSizeType)>0) {
460 + this.fontSize = parseFloat(fontSize);
461 + this.fontSizeType = fontSizeType;
462 + }
463 + }.bind(this));
464 +
465 + this.factor = (this.options.scaleTo - this.options.scaleFrom)/100;
466 +
467 + this.dims = null;
468 + if(this.options.scaleMode=='box')
469 + this.dims = [this.element.offsetHeight, this.element.offsetWidth];
470 + if(/^content/.test(this.options.scaleMode))
471 + this.dims = [this.element.scrollHeight, this.element.scrollWidth];
472 + if(!this.dims)
473 + this.dims = [this.options.scaleMode.originalHeight,
474 + this.options.scaleMode.originalWidth];
475 + },
476 + update: function(position) {
477 + var currentScale = (this.options.scaleFrom/100.0) + (this.factor * position);
478 + if(this.options.scaleContent && this.fontSize)
479 + this.element.setStyle({fontSize: this.fontSize * currentScale + this.fontSizeType });
480 + this.setDimensions(this.dims[0] * currentScale, this.dims[1] * currentScale);
481 + },
482 + finish: function(position) {
483 + if(this.restoreAfterFinish) this.element.setStyle(this.originalStyle);
484 + },
485 + setDimensions: function(height, width) {
486 + var d = {};
487 + if(this.options.scaleX) d.width = Math.round(width) + 'px';
488 + if(this.options.scaleY) d.height = Math.round(height) + 'px';
489 + if(this.options.scaleFromCenter) {
490 + var topd = (height - this.dims[0])/2;
491 + var leftd = (width - this.dims[1])/2;
492 + if(this.elementPositioning == 'absolute') {
493 + if(this.options.scaleY) d.top = this.originalTop-topd + 'px';
494 + if(this.options.scaleX) d.left = this.originalLeft-leftd + 'px';
495 + } else {
496 + if(this.options.scaleY) d.top = -topd + 'px';
497 + if(this.options.scaleX) d.left = -leftd + 'px';
498 + }
499 + }
500 + this.element.setStyle(d);
501 + }
502 + });
503 +
504 + Effect.Highlight = Class.create();
505 + Object.extend(Object.extend(Effect.Highlight.prototype, Effect.Base.prototype), {
506 + initialize: function(element) {
507 + this.element = $(element);
508 + if(!this.element) throw(Effect._elementDoesNotExistError);
509 + var options = Object.extend({ startcolor: '#ffff99' }, arguments[1] || {});
510 + this.start(options);
511 + },
512 + setup: function() {
513 + // Prevent executing on elements not in the layout flow
514 + if(this.element.getStyle('display')=='none') { this.cancel(); return; }
515 + // Disable background image during the effect
516 + this.oldStyle = {
517 + backgroundImage: this.element.getStyle('background-image') };
518 + this.element.setStyle({backgroundImage: 'none'});
519 + if(!this.options.endcolor)
520 + this.options.endcolor = this.element.getStyle('background-color').parseColor('#ffffff');
521 + if(!this.options.restorecolor)
522 + this.options.restorecolor = this.element.getStyle('background-color');
523 + // init color calculations
524 + this._base = $R(0,2).map(function(i){ return parseInt(this.options.startcolor.slice(i*2+1,i*2+3),16) }.bind(this));
525 + 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));
526 + },
527 + update: function(position) {
528 + this.element.setStyle({backgroundColor: $R(0,2).inject('#',function(m,v,i){
529 + return m+(Math.round(this._base[i]+(this._delta[i]*position)).toColorPart()); }.bind(this)) });
530 + },
531 + finish: function() {
532 + this.element.setStyle(Object.extend(this.oldStyle, {
533 + backgroundColor: this.options.restorecolor
534 + }));
535 + }
536 + });
537 +
538 + Effect.ScrollTo = Class.create();
539 + Object.extend(Object.extend(Effect.ScrollTo.prototype, Effect.Base.prototype), {
540 + initialize: function(element) {
541 + this.element = $(element);
542 + this.start(arguments[1] || {});
543 + },
544 + setup: function() {
545 + Position.prepare();
546 + var offsets = Position.cumulativeOffset(this.element);
547 + if(this.options.offset) offsets[1] += this.options.offset;
548 + var max = window.innerHeight ?
549 + window.height - window.innerHeight :
550 + document.body.scrollHeight -
551 + (document.documentElement.clientHeight ?
552 + document.documentElement.clientHeight : document.body.clientHeight);
553 + this.scrollStart = Position.deltaY;
554 + this.delta = (offsets[1] > max ? max : offsets[1]) - this.scrollStart;
555 + },
556 + update: function(position) {
557 + Position.prepare();
558 + window.scrollTo(Position.deltaX,
559 + this.scrollStart + (position*this.delta));
560 + }
561 + });
562 +
563 + /* ------------- combination effects ------------- */
564 +
565 + Effect.Fade = function(element) {
566 + element = $(element);
567 + var oldOpacity = element.getInlineOpacity();
568 + var options = Object.extend({
569 + from: element.getOpacity() || 1.0,
570 + to: 0.0,
571 + afterFinishInternal: function(effect) {
572 + if(effect.options.to!=0) return;
573 + effect.element.hide().setStyle({opacity: oldOpacity});
574 + }}, arguments[1] || {});
575 + return new Effect.Opacity(element,options);
576 + }
577 +
578 + Effect.Appear = function(element) {
579 + element = $(element);
580 + var options = Object.extend({
581 + from: (element.getStyle('display') == 'none' ? 0.0 : element.getOpacity() || 0.0),
582 + to: 1.0,
583 + // force Safari to render floated elements properly
584 + afterFinishInternal: function(effect) {
585 + effect.element.forceRerendering();
586 + },
587 + beforeSetup: function(effect) {
588 + effect.element.setOpacity(effect.options.from).show();
589 + }}, arguments[1] || {});
590 + return new Effect.Opacity(element,options);
591 + }
592 +
593 + Effect.Puff = function(element) {
594 + element = $(element);
595 + var oldStyle = {
596 + opacity: element.getInlineOpacity(),
597 + position: element.getStyle('position'),
598 + top: element.style.top,
599 + left: element.style.left,
600 + width: element.style.width,
601 + height: element.style.height
602 + };
603 + return new Effect.Parallel(
604 + [ new Effect.Scale(element, 200,
605 + { sync: true, scaleFromCenter: true, scaleContent: true, restoreAfterFinish: true }),
606 + new Effect.Opacity(element, { sync: true, to: 0.0 } ) ],
607 + Object.extend({ duration: 1.0,
608 + beforeSetupInternal: function(effect) {
609 + Position.absolutize(effect.effects[0].element)
610 + },
611 + afterFinishInternal: function(effect) {
612 + effect.effects[0].element.hide().setStyle(oldStyle); }
613 + }, arguments[1] || {})
614 + );
615 + }
616 +
617 + Effect.BlindUp = function(element) {
618 + element = $(element);
619 + element.makeClipping();
620 + return new Effect.Scale(element, 0,
621 + Object.extend({ scaleContent: false,
622 + scaleX: false,
623 + restoreAfterFinish: true,
624 + afterFinishInternal: function(effect) {
625 + effect.element.hide().undoClipping();
626 + }
627 + }, arguments[1] || {})
628 + );
629 + }
630 +
631 + Effect.BlindDown = function(element) {
632 + element = $(element);
633 + var elementDimensions = element.getDimensions();
634 + return new Effect.Scale(element, 100, Object.extend({
635 + scaleContent: false,
636 + scaleX: false,
637 + scaleFrom: 0,
638 + scaleMode: {originalHeight: elementDimensions.height, originalWidth: elementDimensions.width},
639 + restoreAfterFinish: true,
640 + afterSetup: function(effect) {
641 + effect.element.makeClipping().setStyle({height: '0px'}).show();
642 + },
643 + afterFinishInternal: function(effect) {
644 + effect.element.undoClipping();
645 + }
646 + }, arguments[1] || {}));
647 + }
648 +
649 + Effect.SwitchOff = function(element) {
650 + element = $(element);
651 + var oldOpacity = element.getInlineOpacity();
652 + return new Effect.Appear(element, Object.extend({
653 + duration: 0.4,
654 + from: 0,
655 + transition: Effect.Transitions.flicker,
656 + afterFinishInternal: function(effect) {
657 + new Effect.Scale(effect.element, 1, {
658 + duration: 0.3, scaleFromCenter: true,
659 + scaleX: false, scaleContent: false, restoreAfterFinish: true,
660 + beforeSetup: function(effect) {
661 + effect.element.makePositioned().makeClipping();
662 + },
663 + afterFinishInternal: function(effect) {
664 + effect.element.hide().undoClipping().undoPositioned().setStyle({opacity: oldOpacity});
665 + }
666 + })
667 + }
668 + }, arguments[1] || {}));
669 + }
670 +
671 + Effect.DropOut = function(element) {
672 + element = $(element);
673 + var oldStyle = {
674 + top: element.getStyle('top'),
675 + left: element.getStyle('left'),
676 + opacity: element.getInlineOpacity() };
677 + return new Effect.Parallel(
678 + [ new Effect.Move(element, {x: 0, y: 100, sync: true }),
679 + new Effect.Opacity(element, { sync: true, to: 0.0 }) ],
680 + Object.extend(
681 + { duration: 0.5,
682 + beforeSetup: function(effect) {
683 + effect.effects[0].element.makePositioned();
684 + },
685 + afterFinishInternal: function(effect) {
686 + effect.effects[0].element.hide().undoPositioned().setStyle(oldStyle);
687 + }
688 + }, arguments[1] || {}));
689 + }
690 +
691 + Effect.Shake = function(element) {
692 + element = $(element);
693 + var oldStyle = {
694 + top: element.getStyle('top'),
695 + left: element.getStyle('left') };
696 + return new Effect.Move(element,
697 + { x: 20, y: 0, duration: 0.05, afterFinishInternal: function(effect) {
698 + new Effect.Move(effect.element,
699 + { x: -40, y: 0, duration: 0.1, afterFinishInternal: function(effect) {
700 + new Effect.Move(effect.element,
701 + { x: 40, y: 0, duration: 0.1, afterFinishInternal: function(effect) {
702 + new Effect.Move(effect.element,
703 + { x: -40, y: 0, duration: 0.1, afterFinishInternal: function(effect) {
704 + new Effect.Move(effect.element,
705 + { x: 40, y: 0, duration: 0.1, afterFinishInternal: function(effect) {
706 + new Effect.Move(effect.element,
707 + { x: -20, y: 0, duration: 0.05, afterFinishInternal: function(effect) {
708 + effect.element.undoPositioned().setStyle(oldStyle);
709 + }}) }}) }}) }}) }}) }});
710 + }
711 +
712 + Effect.SlideDown = function(element) {
713 + element = $(element).cleanWhitespace();
714 + // SlideDown need to have the content of the element wrapped in a container element with fixed height!
715 + var oldInnerBottom = element.down().getStyle('bottom');
716 + var elementDimensions = element.getDimensions();
717 + return new Effect.Scale(element, 100, Object.extend({
718 + scaleContent: false,
719 + scaleX: false,
720 + scaleFrom: window.opera ? 0 : 1,
721 + scaleMode: {originalHeight: elementDimensions.height, originalWidth: elementDimensions.width},
722 + restoreAfterFinish: true,
723 + afterSetup: function(effect) {
724 + effect.element.makePositioned();
725 + effect.element.down().makePositioned();
726 + if(window.opera) effect.element.setStyle({top: ''});
727 + effect.element.makeClipping().setStyle({height: '0px'}).show();
728 + },
729 + afterUpdateInternal: function(effect) {
730 + effect.element.down().setStyle({bottom:
731 + (effect.dims[0] - effect.element.clientHeight) + 'px' });
732 + },
733 + afterFinishInternal: function(effect) {
734 + effect.element.undoClipping().undoPositioned();
735 + effect.element.down().undoPositioned().setStyle({bottom: oldInnerBottom}); }
736 + }, arguments[1] || {})
737 + );
738 + }
739 +
740 + Effect.SlideUp = function(element) {
741 + element = $(element).cleanWhitespace();
742 + var oldInnerBottom = element.down().getStyle('bottom');
743 + return new Effect.Scale(element, window.opera ? 0 : 1,
744 + Object.extend({ scaleContent: false,
745 + scaleX: false,
746 + scaleMode: 'box',
747 + scaleFrom: 100,
748 + restoreAfterFinish: true,
749 + beforeStartInternal: function(effect) {
750 + effect.element.makePositioned();
751 + effect.element.down().makePositioned();
752 + if(window.opera) effect.element.setStyle({top: ''});
753 + effect.element.makeClipping().show();
754 + },
755 + afterUpdateInternal: function(effect) {
756 + effect.element.down().setStyle({bottom:
757 + (effect.dims[0] - effect.element.clientHeight) + 'px' });
758 + },
759 + afterFinishInternal: function(effect) {
760 + effect.element.hide().undoClipping().undoPositioned().setStyle({bottom: oldInnerBottom});
761 + effect.element.down().undoPositioned();
762 + }
763 + }, arguments[1] || {})
764 + );
765 + }
766 +
767 + // Bug in opera makes the TD containing this element expand for a instance after finish
768 + Effect.Squish = function(element) {
769 + return new Effect.Scale(element, window.opera ? 1 : 0, {
770 + restoreAfterFinish: true,
771 + beforeSetup: function(effect) {
772 + effect.element.makeClipping();
773 + },
774 + afterFinishInternal: function(effect) {
775 + effect.element.hide().undoClipping();
776 + }
777 + });
778 + }
779 +
780 + Effect.Grow = function(element) {
781 + element = $(element);
782 + var options