Browse files

Week Two (burger madness project)

  • Loading branch information...
1 parent d224c0d commit 1129583aa459aa3207d67752f243171ffe69a0f7 @newfront committed Nov 21, 2010
Showing with 10,880 additions and 0 deletions.
  1. +4 −0 week_two/burger_madness/.gitignore
  2. +30 −0 week_two/burger_madness/Gemfile
  3. +74 −0 week_two/burger_madness/Gemfile.lock
  4. +256 −0 week_two/burger_madness/README
  5. +7 −0 week_two/burger_madness/Rakefile
  6. +11 −0 week_two/burger_madness/app/controllers/application_controller.rb
  7. +56 −0 week_two/burger_madness/app/controllers/burger_controller.rb
  8. +49 −0 week_two/burger_madness/app/controllers/order_controller.rb
  9. +2 −0 week_two/burger_madness/app/helpers/application_helper.rb
  10. +2 −0 week_two/burger_madness/app/helpers/burger_helper.rb
  11. +2 −0 week_two/burger_madness/app/helpers/order_helper.rb
  12. +19 −0 week_two/burger_madness/app/models/burger.rb
  13. +4 −0 week_two/burger_madness/app/models/order.rb
  14. +4 −0 week_two/burger_madness/app/models/topping.rb
  15. +21 −0 week_two/burger_madness/app/views/burger/add_topping.html.erb
  16. +2 −0 week_two/burger_madness/app/views/burger/create.html.erb
  17. +2 −0 week_two/burger_madness/app/views/burger/destroy.html.erb
  18. +2 −0 week_two/burger_madness/app/views/burger/edit.html.erb
  19. +2 −0 week_two/burger_madness/app/views/burger/index.html.erb
  20. +12 −0 week_two/burger_madness/app/views/burger/new.html.erb
  21. +2 −0 week_two/burger_madness/app/views/burger/show.index.erb
  22. +33 −0 week_two/burger_madness/app/views/layouts/application.html.erb
  23. +9 −0 week_two/burger_madness/app/views/order/index.html.erb
  24. +10 −0 week_two/burger_madness/app/views/order/new.html.erb
  25. +9 −0 week_two/burger_madness/app/views/order/show.html.erb
  26. +1 −0 week_two/burger_madness/app/views/partials/_main_footer.html.erb
  27. +5 −0 week_two/burger_madness/app/views/partials/_main_navigation.html.erb
  28. +4 −0 week_two/burger_madness/config.ru
  29. +42 −0 week_two/burger_madness/config/application.rb
  30. +13 −0 week_two/burger_madness/config/boot.rb
  31. +22 −0 week_two/burger_madness/config/database.yml
  32. +5 −0 week_two/burger_madness/config/environment.rb
  33. +26 −0 week_two/burger_madness/config/environments/development.rb
  34. +49 −0 week_two/burger_madness/config/environments/production.rb
  35. +35 −0 week_two/burger_madness/config/environments/test.rb
  36. +7 −0 week_two/burger_madness/config/initializers/backtrace_silencers.rb
  37. +10 −0 week_two/burger_madness/config/initializers/inflections.rb
  38. +5 −0 week_two/burger_madness/config/initializers/mime_types.rb
  39. +7 −0 week_two/burger_madness/config/initializers/secret_token.rb
  40. +8 −0 week_two/burger_madness/config/initializers/session_store.rb
  41. +5 −0 week_two/burger_madness/config/locales/en.yml
  42. +32 −0 week_two/burger_madness/config/routes.rb
  43. +13 −0 week_two/burger_madness/db/migrate/20101122002028_create_burgers.rb
  44. +15 −0 week_two/burger_madness/db/migrate/20101122002128_create_toppings.rb
  45. +12 −0 week_two/burger_madness/db/migrate/20101122002310_burger_toppings.rb
  46. +14 −0 week_two/burger_madness/db/migrate/20101122002352_create_orders.rb
  47. +9 −0 week_two/burger_madness/db/migrate/20101122041433_add_order_id_column_to_burgers.rb
  48. +43 −0 week_two/burger_madness/db/schema.rb
  49. +14 −0 week_two/burger_madness/db/seeds.rb
  50. +2 −0 week_two/burger_madness/doc/README_FOR_APP
  51. 0 week_two/burger_madness/lib/tasks/.gitkeep
  52. +26 −0 week_two/burger_madness/public/404.html
  53. +26 −0 week_two/burger_madness/public/422.html
  54. +26 −0 week_two/burger_madness/public/500.html
  55. 0 week_two/burger_madness/public/favicon.ico
  56. BIN week_two/burger_madness/public/images/burger_icon.png
  57. BIN week_two/burger_madness/public/images/rails.png
  58. +2 −0 week_two/burger_madness/public/javascripts/application.js
  59. +965 −0 week_two/burger_madness/public/javascripts/controls.js
  60. +974 −0 week_two/burger_madness/public/javascripts/dragdrop.js
  61. +1,123 −0 week_two/burger_madness/public/javascripts/effects.js
  62. +167 −0 week_two/burger_madness/public/javascripts/jquery.js
  63. +6,001 −0 week_two/burger_madness/public/javascripts/prototype.js
  64. +175 −0 week_two/burger_madness/public/javascripts/rails.js
  65. +5 −0 week_two/burger_madness/public/robots.txt
  66. 0 week_two/burger_madness/public/stylesheets/.gitkeep
  67. +107 −0 week_two/burger_madness/public/stylesheets/main.css
  68. +6 −0 week_two/burger_madness/script/rails
  69. +7 −0 week_two/burger_madness/test/fixtures/burgers.yml
  70. +9 −0 week_two/burger_madness/test/fixtures/orders.yml
  71. +11 −0 week_two/burger_madness/test/fixtures/toppings.yml
  72. +29 −0 week_two/burger_madness/test/functional/burger_controller_test.rb
  73. +14 −0 week_two/burger_madness/test/functional/order_controller_test.rb
  74. +9 −0 week_two/burger_madness/test/performance/browsing_test.rb
  75. +13 −0 week_two/burger_madness/test/test_helper.rb
  76. +8 −0 week_two/burger_madness/test/unit/burger_test.rb
  77. +4 −0 week_two/burger_madness/test/unit/helpers/burger_helper_test.rb
  78. +4 −0 week_two/burger_madness/test/unit/helpers/order_helper_test.rb
  79. +8 −0 week_two/burger_madness/test/unit/order_test.rb
  80. +8 −0 week_two/burger_madness/test/unit/topping_test.rb
  81. 0 week_two/burger_madness/vendor/plugins/.gitkeep
  82. +131 −0 week_two/project_overview.rtf
View
4 week_two/burger_madness/.gitignore
@@ -0,0 +1,4 @@
+.bundle
+db/*.sqlite3
+log/*.log
+tmp/**/*
View
30 week_two/burger_madness/Gemfile
@@ -0,0 +1,30 @@
+source 'http://rubygems.org'
+
+gem 'rails', '3.0.1'
+
+# Bundle edge Rails instead:
+# gem 'rails', :git => 'git://github.com/rails/rails.git'
+
+gem 'sqlite3-ruby', :require => 'sqlite3'
+
+# Use unicorn as the web server
+# gem 'unicorn'
+
+# Deploy with Capistrano
+# gem 'capistrano'
+
+# To use debugger
+# gem 'ruby-debug'
+
+# Bundle the extra gems:
+# gem 'bj'
+# gem 'nokogiri'
+# gem 'sqlite3-ruby', :require => 'sqlite3'
+# gem 'aws-s3', :require => 'aws/s3'
+
+# Bundle gems for the local environment. Make sure to
+# put test-only gems in this group so their generators
+# and rake tasks are available in development mode:
+# group :development, :test do
+# gem 'webrat'
+# end
View
74 week_two/burger_madness/Gemfile.lock
@@ -0,0 +1,74 @@
+GEM
+ remote: http://rubygems.org/
+ specs:
+ abstract (1.0.0)
+ actionmailer (3.0.1)
+ actionpack (= 3.0.1)
+ mail (~> 2.2.5)
+ actionpack (3.0.1)
+ activemodel (= 3.0.1)
+ activesupport (= 3.0.1)
+ builder (~> 2.1.2)
+ erubis (~> 2.6.6)
+ i18n (~> 0.4.1)
+ rack (~> 1.2.1)
+ rack-mount (~> 0.6.12)
+ rack-test (~> 0.5.4)
+ tzinfo (~> 0.3.23)
+ activemodel (3.0.1)
+ activesupport (= 3.0.1)
+ builder (~> 2.1.2)
+ i18n (~> 0.4.1)
+ activerecord (3.0.1)
+ activemodel (= 3.0.1)
+ activesupport (= 3.0.1)
+ arel (~> 1.0.0)
+ tzinfo (~> 0.3.23)
+ activeresource (3.0.1)
+ activemodel (= 3.0.1)
+ activesupport (= 3.0.1)
+ activesupport (3.0.1)
+ arel (1.0.1)
+ activesupport (~> 3.0.0)
+ builder (2.1.2)
+ erubis (2.6.6)
+ abstract (>= 1.0.0)
+ i18n (0.4.2)
+ mail (2.2.9)
+ activesupport (>= 2.3.6)
+ i18n (~> 0.4.1)
+ mime-types (~> 1.16)
+ treetop (~> 1.4.8)
+ mime-types (1.16)
+ polyglot (0.3.1)
+ rack (1.2.1)
+ rack-mount (0.6.13)
+ rack (>= 1.0.0)
+ rack-test (0.5.6)
+ rack (>= 1.0)
+ rails (3.0.1)
+ actionmailer (= 3.0.1)
+ actionpack (= 3.0.1)
+ activerecord (= 3.0.1)
+ activeresource (= 3.0.1)
+ activesupport (= 3.0.1)
+ bundler (~> 1.0.0)
+ railties (= 3.0.1)
+ railties (3.0.1)
+ actionpack (= 3.0.1)
+ activesupport (= 3.0.1)
+ rake (>= 0.8.4)
+ thor (~> 0.14.0)
+ rake (0.8.7)
+ sqlite3-ruby (1.3.2)
+ thor (0.14.4)
+ treetop (1.4.8)
+ polyglot (>= 0.3.1)
+ tzinfo (0.3.23)
+
+PLATFORMS
+ ruby
+
+DEPENDENCIES
+ rails (= 3.0.1)
+ sqlite3-ruby
View
256 week_two/burger_madness/README
@@ -0,0 +1,256 @@
+== Welcome to Rails
+
+Rails is a web-application framework that includes everything needed to create
+database-backed web applications according to the Model-View-Control pattern.
+
+This pattern splits the view (also called the presentation) into "dumb"
+templates that are primarily responsible for inserting pre-built data in between
+HTML tags. The model contains the "smart" domain objects (such as Account,
+Product, Person, Post) that holds all the business logic and knows how to
+persist themselves to a database. The controller handles the incoming requests
+(such as Save New Account, Update Product, Show Post) by manipulating the model
+and directing data to the view.
+
+In Rails, the model is handled by what's called an object-relational mapping
+layer entitled Active Record. This layer allows you to present the data from
+database rows as objects and embellish these data objects with business logic
+methods. You can read more about Active Record in
+link:files/vendor/rails/activerecord/README.html.
+
+The controller and view are handled by the Action Pack, which handles both
+layers by its two parts: Action View and Action Controller. These two layers
+are bundled in a single package due to their heavy interdependence. This is
+unlike the relationship between the Active Record and Action Pack that is much
+more separate. Each of these packages can be used independently outside of
+Rails. You can read more about Action Pack in
+link:files/vendor/rails/actionpack/README.html.
+
+
+== Getting Started
+
+1. At the command prompt, create a new Rails application:
+ <tt>rails new myapp</tt> (where <tt>myapp</tt> is the application name)
+
+2. Change directory to <tt>myapp</tt> and start the web server:
+ <tt>cd myapp; rails server</tt> (run with --help for options)
+
+3. Go to http://localhost:3000/ and you'll see:
+ "Welcome aboard: You're riding Ruby on Rails!"
+
+4. Follow the guidelines to start developing your application. You can find
+the following resources handy:
+
+* The Getting Started Guide: http://guides.rubyonrails.org/getting_started.html
+* Ruby on Rails Tutorial Book: http://www.railstutorial.org/
+
+
+== Debugging Rails
+
+Sometimes your application goes wrong. Fortunately there are a lot of tools that
+will help you debug it and get it back on the rails.
+
+First area to check is the application log files. Have "tail -f" commands
+running on the server.log and development.log. Rails will automatically display
+debugging and runtime information to these files. Debugging info will also be
+shown in the browser on requests from 127.0.0.1.
+
+You can also log your own messages directly into the log file from your code
+using the Ruby logger class from inside your controllers. Example:
+
+ class WeblogController < ActionController::Base
+ def destroy
+ @weblog = Weblog.find(params[:id])
+ @weblog.destroy
+ logger.info("#{Time.now} Destroyed Weblog ID ##{@weblog.id}!")
+ end
+ end
+
+The result will be a message in your log file along the lines of:
+
+ Mon Oct 08 14:22:29 +1000 2007 Destroyed Weblog ID #1!
+
+More information on how to use the logger is at http://www.ruby-doc.org/core/
+
+Also, Ruby documentation can be found at http://www.ruby-lang.org/. There are
+several books available online as well:
+
+* Programming Ruby: http://www.ruby-doc.org/docs/ProgrammingRuby/ (Pickaxe)
+* Learn to Program: http://pine.fm/LearnToProgram/ (a beginners guide)
+
+These two books will bring you up to speed on the Ruby language and also on
+programming in general.
+
+
+== Debugger
+
+Debugger support is available through the debugger command when you start your
+Mongrel or WEBrick server with --debugger. This means that you can break out of
+execution at any point in the code, investigate and change the model, and then,
+resume execution! You need to install ruby-debug to run the server in debugging
+mode. With gems, use <tt>sudo gem install ruby-debug</tt>. Example:
+
+ class WeblogController < ActionController::Base
+ def index
+ @posts = Post.find(:all)
+ debugger
+ end
+ end
+
+So the controller will accept the action, run the first line, then present you
+with a IRB prompt in the server window. Here you can do things like:
+
+ >> @posts.inspect
+ => "[#<Post:0x14a6be8
+ @attributes={"title"=>nil, "body"=>nil, "id"=>"1"}>,
+ #<Post:0x14a6620
+ @attributes={"title"=>"Rails", "body"=>"Only ten..", "id"=>"2"}>]"
+ >> @posts.first.title = "hello from a debugger"
+ => "hello from a debugger"
+
+...and even better, you can examine how your runtime objects actually work:
+
+ >> f = @posts.first
+ => #<Post:0x13630c4 @attributes={"title"=>nil, "body"=>nil, "id"=>"1"}>
+ >> f.
+ Display all 152 possibilities? (y or n)
+
+Finally, when you're ready to resume execution, you can enter "cont".
+
+
+== Console
+
+The console is a Ruby shell, which allows you to interact with your
+application's domain model. Here you'll have all parts of the application
+configured, just like it is when the application is running. You can inspect
+domain models, change values, and save to the database. Starting the script
+without arguments will launch it in the development environment.
+
+To start the console, run <tt>rails console</tt> from the application
+directory.
+
+Options:
+
+* Passing the <tt>-s, --sandbox</tt> argument will rollback any modifications
+ made to the database.
+* Passing an environment name as an argument will load the corresponding
+ environment. Example: <tt>rails console production</tt>.
+
+To reload your controllers and models after launching the console run
+<tt>reload!</tt>
+
+More information about irb can be found at:
+link:http://www.rubycentral.com/pickaxe/irb.html
+
+
+== dbconsole
+
+You can go to the command line of your database directly through <tt>rails
+dbconsole</tt>. You would be connected to the database with the credentials
+defined in database.yml. Starting the script without arguments will connect you
+to the development database. Passing an argument will connect you to a different
+database, like <tt>rails dbconsole production</tt>. Currently works for MySQL,
+PostgreSQL and SQLite 3.
+
+== Description of Contents
+
+The default directory structure of a generated Ruby on Rails application:
+
+ |-- app
+ | |-- controllers
+ | |-- helpers
+ | |-- models
+ | `-- views
+ | `-- layouts
+ |-- config
+ | |-- environments
+ | |-- initializers
+ | `-- locales
+ |-- db
+ |-- doc
+ |-- lib
+ | `-- tasks
+ |-- log
+ |-- public
+ | |-- images
+ | |-- javascripts
+ | `-- stylesheets
+ |-- script
+ | `-- performance
+ |-- test
+ | |-- fixtures
+ | |-- functional
+ | |-- integration
+ | |-- performance
+ | `-- unit
+ |-- tmp
+ | |-- cache
+ | |-- pids
+ | |-- sessions
+ | `-- sockets
+ `-- vendor
+ `-- plugins
+
+app
+ Holds all the code that's specific to this particular application.
+
+app/controllers
+ Holds controllers that should be named like weblogs_controller.rb for
+ automated URL mapping. All controllers should descend from
+ ApplicationController which itself descends from ActionController::Base.
+
+app/models
+ Holds models that should be named like post.rb. Models descend from
+ ActiveRecord::Base by default.
+
+app/views
+ Holds the template files for the view that should be named like
+ weblogs/index.html.erb for the WeblogsController#index action. All views use
+ eRuby syntax by default.
+
+app/views/layouts
+ Holds the template files for layouts to be used with views. This models the
+ common header/footer method of wrapping views. In your views, define a layout
+ using the <tt>layout :default</tt> and create a file named default.html.erb.
+ Inside default.html.erb, call <% yield %> to render the view using this
+ layout.
+
+app/helpers
+ Holds view helpers that should be named like weblogs_helper.rb. These are
+ generated for you automatically when using generators for controllers.
+ Helpers can be used to wrap functionality for your views into methods.
+
+config
+ Configuration files for the Rails environment, the routing map, the database,
+ and other dependencies.
+
+db
+ Contains the database schema in schema.rb. db/migrate contains all the
+ sequence of Migrations for your schema.
+
+doc
+ This directory is where your application documentation will be stored when
+ generated using <tt>rake doc:app</tt>
+
+lib
+ Application specific libraries. Basically, any kind of custom code that
+ doesn't belong under controllers, models, or helpers. This directory is in
+ the load path.
+
+public
+ The directory available for the web server. Contains subdirectories for
+ images, stylesheets, and javascripts. Also contains the dispatchers and the
+ default HTML files. This should be set as the DOCUMENT_ROOT of your web
+ server.
+
+script
+ Helper scripts for automation and generation.
+
+test
+ Unit and functional tests along with fixtures. When using the rails generate
+ command, template test files will be generated for you and placed in this
+ directory.
+
+vendor
+ External libraries that the application depends on. Also includes the plugins
+ subdirectory. If the app has frozen rails, those gems also go here, under
+ vendor/rails/. This directory is in the load path.
View
7 week_two/burger_madness/Rakefile
@@ -0,0 +1,7 @@
+# Add your own tasks in files placed in lib/tasks ending in .rake,
+# for example lib/tasks/capistrano.rake, and they will automatically be available to Rake.
+
+require File.expand_path('../config/application', __FILE__)
+require 'rake'
+
+BurgerMadness::Application.load_tasks
View
11 week_two/burger_madness/app/controllers/application_controller.rb
@@ -0,0 +1,11 @@
+class ApplicationController < ActionController::Base
+ protect_from_forgery
+
+ before_filter :web_config
+
+ def web_config
+ @title = "Burger Madness"
+ end
+
+
+end
View
56 week_two/burger_madness/app/controllers/burger_controller.rb
@@ -0,0 +1,56 @@
+class BurgerController < ApplicationController
+ def index
+ redirect_to :action => :new
+ end
+
+ def show
+ end
+
+ def new
+ @burger = Burger.new
+ @title = "Create a new Burger"
+ end
+
+ def create
+ #Create new Burger Record
+ @burger = Burger.new(params[:burger])
+
+ respond_to do |format|
+ if @burger.save
+ format.html { redirect_to :action => "add_topping", :id => @burger.id, :notice => 'Burger Started.'}
+ else
+ format.html { render :action => "new"}
+ puts "Errors. #{@burger.errors.inspect}"
+ end
+ end
+
+ end
+
+ def edit
+ end
+
+ def destroy
+ end
+
+ def add_topping
+ @burger = Burger.find(params[:id])
+ @topping = Topping.all
+ if @burger
+ @burger_id = params[:id]
+ else
+ redirect_to :action => :new
+ end
+ end
+
+ def do_add_topping
+ @burger = Burger.find(params[:id])
+ @burger.toppings << Topping.find(params[:toppings])
+
+ if @burger.save
+ redirect_to :action => "add_topping", :id => @burger.id, :notice => 'Burger Topping Saved'
+ else
+ redirect_to :action => "add_topping", :id => @burger.id, :notice => 'Burger Topping Failed to Save'
+ end
+ end
+
+end
View
49 week_two/burger_madness/app/controllers/order_controller.rb
@@ -0,0 +1,49 @@
+class OrderController < ApplicationController
+ def index
+ @orders = Order.find(:all, :limit => 5)
+ @page_title = "Orders"
+ end
+
+ def new
+ @order = Order.new
+ @burger = Burger.find(params[:id])
+ end
+
+ def show
+ # Show 5 most recent orders
+ @orders = Order.all
+
+ # Show Orders Based on Rules
+ # if no parameter id, or with parameter id if params[:id].is_a? String (all), or Integer
+ if params[:id]
+ puts "Has Parameter"
+ if params[:id] == "all"
+ # List Orders
+ puts "Show ALL"
+ @page_title = "History"
+ else
+ # Show a single Record based off of this id
+ puts "Show Single Record"
+ @page_title = "Orders"
+ end
+ else
+ # show all
+ end
+ end
+
+ def create
+ @order = Order.new
+ @burger = Burger.find(params[:id])
+ @order.burgers_id = @burger.id
+ @order.price = @burger.get_price
+
+ if @order.save
+ @burger.order_id = @order.id
+ @burger.save
+ redirect_to :action => :index, :notice => "Order has been placed"
+ else
+ redirect_to :action => :index, :notice => "Order couldn't be saved"
+ end
+ end
+
+end
View
2 week_two/burger_madness/app/helpers/application_helper.rb
@@ -0,0 +1,2 @@
+module ApplicationHelper
+end
View
2 week_two/burger_madness/app/helpers/burger_helper.rb
@@ -0,0 +1,2 @@
+module BurgerHelper
+end
View
2 week_two/burger_madness/app/helpers/order_helper.rb
@@ -0,0 +1,2 @@
+module OrderHelper
+end
View
19 week_two/burger_madness/app/models/burger.rb
@@ -0,0 +1,19 @@
+class Burger < ActiveRecord::Base
+ #Burger(id: integer, name: string, created_at: datetime, updated_at: datetime)
+ has_and_belongs_to_many :toppings
+ belongs_to :order
+
+ # make sure that the Burger name field isn't blank
+ validates :name, :presence => true, :uniqueness => true
+
+ @@price = 0
+
+ # Calculate the price of the Burger
+ # Recalculate price since price can change depending on number of toppings
+ def get_price
+ @@price = 0
+ self.toppings.each {|topping| @@price += topping.price}
+ #puts "Total Burger Price: $#{@price}"
+ return @@price
+ end
+end
View
4 week_two/burger_madness/app/models/order.rb
@@ -0,0 +1,4 @@
+class Order < ActiveRecord::Base
+ #Order(id: integer, burgers_id: integer, price: integer, created_at: datetime, updated_at: datetime)
+ has_one :burger
+end
View
4 week_two/burger_madness/app/models/topping.rb
@@ -0,0 +1,4 @@
+class Topping < ActiveRecord::Base
+ #Topping(id: integer, name: string, calories: integer, price: integer, created_at: datetime, updated_at: datetime)
+ has_and_belongs_to_many :burgers
+end
View
21 week_two/burger_madness/app/views/burger/add_topping.html.erb
@@ -0,0 +1,21 @@
+<h3>Add Toppings</h3>
+<p>Burger has <%= @burger.toppings.count %> Toppings</p>
+<% if @burger.toppings.count >= 1 %>
+ <% @burger.toppings.each do |topping| %>
+ <p><%= topping.name %></p>
+ <% end %>
+ <p>Total: $<%= @burger.get_price %></p>
+<% end %>
+
+<div id="burger_toppings">
+ <%= form_for :topping, @topping, :url => {:action => "do_add_topping", :id => @burger_id} do |f|%>
+ <select name="toppings" id="toppings">
+ <% @topping.each do |top| %>
+ <option value="<%= top.id %>"><%= top.name %></option>
+ <% end %>
+ </select>
+ <%= submit_tag "Add Topping" %>
+ <% end %>
+</div>
+
+<%= link_to "Place Order", {:controller => :order, :action => :new, :id => @burger_id} if @burger.toppings.count >= 1%>
View
2 week_two/burger_madness/app/views/burger/create.html.erb
@@ -0,0 +1,2 @@
+<h1>Burger#create</h1>
+<p>Find me in app/views/burger/create.html.erb</p>
View
2 week_two/burger_madness/app/views/burger/destroy.html.erb
@@ -0,0 +1,2 @@
+<h1>Burger#destroy</h1>
+<p>Find me in app/views/burger/destroy.html.erb</p>
View
2 week_two/burger_madness/app/views/burger/edit.html.erb
@@ -0,0 +1,2 @@
+<h1>Burger#edit</h1>
+<p>Find me in app/views/burger/edit.html.erb</p>
View
2 week_two/burger_madness/app/views/burger/index.html.erb
@@ -0,0 +1,2 @@
+<h1>Burger#index</h1>
+<p>Find me in app/views/burger/index.html.erb</p>
View
12 week_two/burger_madness/app/views/burger/new.html.erb
@@ -0,0 +1,12 @@
+<h3>Create a New Burger</h3>
+<% if @burger.errors %>
+ <div class="errors">
+ <% @burger.errors.each do |error,info|%>
+ <span class="error_row">Burger <%= error %> <%= info.to_s %></span>
+ <% end %>
+ </div>
+<% end %>
+<%= form_for :burger, @burger, :url => { :action => "create" }, :html => {:class => "form_class"} do |f| %>
+ <%= f.text_field :name %>
+ <%= submit_tag "Create" %>
+<% end %>
View
2 week_two/burger_madness/app/views/burger/show.index.erb
@@ -0,0 +1,2 @@
+<h1>Burger#show</h1>
+<p>Find me in app/views/burger/new.html.erb</p>
View
33 week_two/burger_madness/app/views/layouts/application.html.erb
@@ -0,0 +1,33 @@
+<!DOCTYPE html>
+<html>
+<head>
+ <title>
+ <%= @title %>
+ </title>
+ <%= stylesheet_link_tag :all %>
+ <%= javascript_include_tag "jquery","application" %>
+ <%= csrf_meta_tag %>
+</head>
+<body>
+ <div id="mainwrap">
+ <div id="header">
+ <div id="branding">
+ <h3>Burger Madness</h3>
+ <p>Build it. Order it.</p>
+ </div>
+
+ <div id="navigation">
+ <%= render "partials/main_navigation"%>
+ </div>
+ <div class="clearfix"></div>
+ </div>
+ <div id="content">
+ <%= yield %>
+ </div>
+ <div class="clearfix"></div>
+ </div>
+ <div id="footer">
+ <%= render "partials/main_footer"%>
+ </div>
+</body>
+</html>
View
9 week_two/burger_madness/app/views/order/index.html.erb
@@ -0,0 +1,9 @@
+<h3><%= @page_title %></h3>
+<% @orders.each do |order|%>
+ <div class="order">
+ <% order.inspect %>
+ <% @burger = order.burger %>
+ <%= @burger.name %> | <%= @burger.updated_at.strftime("%A %B %d %Y")%>
+
+ </div>
+<% end %>
View
10 week_two/burger_madness/app/views/order/new.html.erb
@@ -0,0 +1,10 @@
+<h3>Place Order</h3>
+<p>Burger (<%= @burger.name %>)</p>
+<% if @burger.toppings.count >= 1 %>
+ <% @burger.toppings.each do |topping| %>
+ <p><%= topping.name %></p>
+ <% end %>
+ <p>Total: $<%= @burger.get_price %></p>
+<% end %>
+
+<%= link_to "Purchase", {:action => :create, :id => @burger.id}%>
View
9 week_two/burger_madness/app/views/order/show.html.erb
@@ -0,0 +1,9 @@
+<h3><%= @page_title %></h3>
+<% @orders.each do |order|%>
+ <div class="order">
+ <% order.inspect %>
+ <% @burger = order.burger %>
+ <%= @burger.name %> | <%= @burger.updated_at.strftime("%A %B %d %Y")%>
+
+ </div>
+<% end %>
View
1 week_two/burger_madness/app/views/partials/_main_footer.html.erb
@@ -0,0 +1 @@
+<div class="footer_info">&copy; <%= Time.now().year.to_s%> Burger Madness</div>
View
5 week_two/burger_madness/app/views/partials/_main_navigation.html.erb
@@ -0,0 +1,5 @@
+<ul>
+ <li><%= link_to 'Burgers', {:controller => :burger, :action => :index}, :class => "nav_item" %></li>
+ <li><%= link_to 'Orders', {:controller => :order, :action => :index}, :class => "nav_item" %></li>
+ <li><%= link_to 'History', {:controller => :order, :action => :show, :id => "all"}, :class => "nav_item"%></li>
+</ul>
View
4 week_two/burger_madness/config.ru
@@ -0,0 +1,4 @@
+# This file is used by Rack-based servers to start the application.
+
+require ::File.expand_path('../config/environment', __FILE__)
+run BurgerMadness::Application
View
42 week_two/burger_madness/config/application.rb
@@ -0,0 +1,42 @@
+require File.expand_path('../boot', __FILE__)
+
+require 'rails/all'
+
+# If you have a Gemfile, require the gems listed there, including any gems
+# you've limited to :test, :development, or :production.
+Bundler.require(:default, Rails.env) if defined?(Bundler)
+
+module BurgerMadness
+ class Application < Rails::Application
+ # Settings in config/environments/* take precedence over those specified here.
+ # Application configuration should go into files in config/initializers
+ # -- all .rb files in that directory are automatically loaded.
+
+ # Custom directories with classes and modules you want to be autoloadable.
+ # config.autoload_paths += %W(#{config.root}/extras)
+
+ # Only load the plugins named here, in the order given (default is alphabetical).
+ # :all can be used as a placeholder for all plugins not explicitly named.
+ # config.plugins = [ :exception_notification, :ssl_requirement, :all ]
+
+ # Activate observers that should always be running.
+ # config.active_record.observers = :cacher, :garbage_collector, :forum_observer
+
+ # Set Time.zone default to the specified zone and make Active Record auto-convert to this zone.
+ # Run "rake -D time" for a list of tasks for finding time zone names. Default is UTC.
+ # config.time_zone = 'Central Time (US & Canada)'
+
+ # The default locale is :en and all translations from config/locales/*.rb,yml are auto loaded.
+ # config.i18n.load_path += Dir[Rails.root.join('my', 'locales', '*.{rb,yml}').to_s]
+ # config.i18n.default_locale = :de
+
+ # JavaScript files you want as :defaults (application.js is always included).
+ # config.action_view.javascript_expansions[:defaults] = %w(jquery rails)
+
+ # Configure the default encoding used in templates for Ruby 1.9.
+ config.encoding = "utf-8"
+
+ # Configure sensitive parameters which will be filtered from the log file.
+ config.filter_parameters += [:password]
+ end
+end
View
13 week_two/burger_madness/config/boot.rb
@@ -0,0 +1,13 @@
+require 'rubygems'
+
+# Set up gems listed in the Gemfile.
+gemfile = File.expand_path('../../Gemfile', __FILE__)
+begin
+ ENV['BUNDLE_GEMFILE'] = gemfile
+ require 'bundler'
+ Bundler.setup
+rescue Bundler::GemNotFound => e
+ STDERR.puts e.message
+ STDERR.puts "Try running `bundle install`."
+ exit!
+end if File.exist?(gemfile)
View
22 week_two/burger_madness/config/database.yml
@@ -0,0 +1,22 @@
+# SQLite version 3.x
+# gem install sqlite3-ruby (not necessary on OS X Leopard)
+development:
+ adapter: sqlite3
+ database: db/development.sqlite3
+ pool: 5
+ timeout: 5000
+
+# Warning: The database defined as "test" will be erased and
+# re-generated from your development database when you run "rake".
+# Do not set this db to the same as development or production.
+test:
+ adapter: sqlite3
+ database: db/test.sqlite3
+ pool: 5
+ timeout: 5000
+
+production:
+ adapter: sqlite3
+ database: db/production.sqlite3
+ pool: 5
+ timeout: 5000
View
5 week_two/burger_madness/config/environment.rb
@@ -0,0 +1,5 @@
+# Load the rails application
+require File.expand_path('../application', __FILE__)
+
+# Initialize the rails application
+BurgerMadness::Application.initialize!
View
26 week_two/burger_madness/config/environments/development.rb
@@ -0,0 +1,26 @@
+BurgerMadness::Application.configure do
+ # Settings specified here will take precedence over those in config/environment.rb
+
+ # In the development environment your application's code is reloaded on
+ # every request. This slows down response time but is perfect for development
+ # since you don't have to restart the webserver when you make code changes.
+ config.cache_classes = false
+
+ # Log error messages when you accidentally call methods on nil.
+ config.whiny_nils = true
+
+ # Show full error reports and disable caching
+ config.consider_all_requests_local = true
+ config.action_view.debug_rjs = true
+ config.action_controller.perform_caching = false
+
+ # Don't care if the mailer can't send
+ config.action_mailer.raise_delivery_errors = false
+
+ # Print deprecation notices to the Rails logger
+ config.active_support.deprecation = :log
+
+ # Only use best-standards-support built into browsers
+ config.action_dispatch.best_standards_support = :builtin
+end
+
View
49 week_two/burger_madness/config/environments/production.rb
@@ -0,0 +1,49 @@
+BurgerMadness::Application.configure do
+ # Settings specified here will take precedence over those in config/environment.rb
+
+ # The production environment is meant for finished, "live" apps.
+ # Code is not reloaded between requests
+ config.cache_classes = true
+
+ # Full error reports are disabled and caching is turned on
+ config.consider_all_requests_local = false
+ config.action_controller.perform_caching = true
+
+ # Specifies the header that your server uses for sending files
+ config.action_dispatch.x_sendfile_header = "X-Sendfile"
+
+ # For nginx:
+ # config.action_dispatch.x_sendfile_header = 'X-Accel-Redirect'
+
+ # If you have no front-end server that supports something like X-Sendfile,
+ # just comment this out and Rails will serve the files
+
+ # See everything in the log (default is :info)
+ # config.log_level = :debug
+
+ # Use a different logger for distributed setups
+ # config.logger = SyslogLogger.new
+
+ # Use a different cache store in production
+ # config.cache_store = :mem_cache_store
+
+ # Disable Rails's static asset server
+ # In production, Apache or nginx will already do this
+ config.serve_static_assets = false
+
+ # Enable serving of images, stylesheets, and javascripts from an asset server
+ # config.action_controller.asset_host = "http://assets.example.com"
+
+ # Disable delivery errors, bad email addresses will be ignored
+ # config.action_mailer.raise_delivery_errors = false
+
+ # Enable threaded mode
+ # config.threadsafe!
+
+ # Enable locale fallbacks for I18n (makes lookups for any locale fall back to
+ # the I18n.default_locale when a translation can not be found)
+ config.i18n.fallbacks = true
+
+ # Send deprecation notices to registered listeners
+ config.active_support.deprecation = :notify
+end
View
35 week_two/burger_madness/config/environments/test.rb
@@ -0,0 +1,35 @@
+BurgerMadness::Application.configure do
+ # Settings specified here will take precedence over those in config/environment.rb
+
+ # The test environment is used exclusively to run your application's
+ # test suite. You never need to work with it otherwise. Remember that
+ # your test database is "scratch space" for the test suite and is wiped
+ # and recreated between test runs. Don't rely on the data there!
+ config.cache_classes = true
+
+ # Log error messages when you accidentally call methods on nil.
+ config.whiny_nils = true
+
+ # Show full error reports and disable caching
+ config.consider_all_requests_local = true
+ config.action_controller.perform_caching = false
+
+ # Raise exceptions instead of rendering exception templates
+ config.action_dispatch.show_exceptions = false
+
+ # Disable request forgery protection in test environment
+ config.action_controller.allow_forgery_protection = false
+
+ # Tell Action Mailer not to deliver emails to the real world.
+ # The :test delivery method accumulates sent emails in the
+ # ActionMailer::Base.deliveries array.
+ config.action_mailer.delivery_method = :test
+
+ # Use SQL instead of Active Record's schema dumper when creating the test database.
+ # This is necessary if your schema can't be completely dumped by the schema dumper,
+ # like if you have constraints or database-specific column types
+ # config.active_record.schema_format = :sql
+
+ # Print deprecation notices to the stderr
+ config.active_support.deprecation = :stderr
+end
View
7 week_two/burger_madness/config/initializers/backtrace_silencers.rb
@@ -0,0 +1,7 @@
+# Be sure to restart your server when you modify this file.
+
+# You can add backtrace silencers for libraries that you're using but don't wish to see in your backtraces.
+# Rails.backtrace_cleaner.add_silencer { |line| line =~ /my_noisy_library/ }
+
+# You can also remove all the silencers if you're trying to debug a problem that might stem from framework code.
+# Rails.backtrace_cleaner.remove_silencers!
View
10 week_two/burger_madness/config/initializers/inflections.rb
@@ -0,0 +1,10 @@
+# Be sure to restart your server when you modify this file.
+
+# Add new inflection rules using the following format
+# (all these examples are active by default):
+# ActiveSupport::Inflector.inflections do |inflect|
+# inflect.plural /^(ox)$/i, '\1en'
+# inflect.singular /^(ox)en/i, '\1'
+# inflect.irregular 'person', 'people'
+# inflect.uncountable %w( fish sheep )
+# end
View
5 week_two/burger_madness/config/initializers/mime_types.rb
@@ -0,0 +1,5 @@
+# Be sure to restart your server when you modify this file.
+
+# Add new mime types for use in respond_to blocks:
+# Mime::Type.register "text/richtext", :rtf
+# Mime::Type.register_alias "text/html", :iphone
View
7 week_two/burger_madness/config/initializers/secret_token.rb
@@ -0,0 +1,7 @@
+# Be sure to restart your server when you modify this file.
+
+# Your secret key for verifying the integrity of signed cookies.
+# If you change this key, all old signed cookies will become invalid!
+# Make sure the secret is at least 30 characters and all random,
+# no regular words or you'll be exposed to dictionary attacks.
+BurgerMadness::Application.config.secret_token = '775a253564c4fc837f0174ff250298cfa7b92ec6458b582830d0b902ad9d091958c295bca5bc75609b190ba11301f8c9036e3ebea9ebb45c329f66f45265e671'
View
8 week_two/burger_madness/config/initializers/session_store.rb
@@ -0,0 +1,8 @@
+# Be sure to restart your server when you modify this file.
+
+BurgerMadness::Application.config.session_store :cookie_store, :key => '_burger_madness_session'
+
+# Use the database for sessions instead of the cookie-based default,
+# which shouldn't be used to store highly confidential information
+# (create the session table with "rake db:sessions:create")
+# BurgerMadness::Application.config.session_store :active_record_store
View
5 week_two/burger_madness/config/locales/en.yml
@@ -0,0 +1,5 @@
+# Sample localization file for English. Add more files in this directory for other locales.
+# See http://github.com/svenfuchs/rails-i18n/tree/master/rails%2Flocale for starting points.
+
+en:
+ hello: "Hello world"
View
32 week_two/burger_madness/config/routes.rb
@@ -0,0 +1,32 @@
+BurgerMadness::Application.routes.draw do
+ get "order/index"
+
+ get "order/show/"
+
+ get "order/create"
+
+ get "order/new"
+
+ get "burger/index"
+
+ get "burger/new"
+
+ post "burger/create"
+
+ get "burger/edit"
+
+ get "burger/destroy"
+
+ get "burger/show"
+
+ get "burger/add_topping"
+
+ post "burger/do_add_topping"
+
+ match "/burger/list" => "burger#index"
+
+ match "/order/list/:id" => "order#index"
+
+ root :to => "burger#index"
+
+end
View
13 week_two/burger_madness/db/migrate/20101122002028_create_burgers.rb
@@ -0,0 +1,13 @@
+class CreateBurgers < ActiveRecord::Migration
+ def self.up
+ create_table :burgers do |t|
+ t.string :name
+
+ t.timestamps
+ end
+ end
+
+ def self.down
+ drop_table :burgers
+ end
+end
View
15 week_two/burger_madness/db/migrate/20101122002128_create_toppings.rb
@@ -0,0 +1,15 @@
+class CreateToppings < ActiveRecord::Migration
+ def self.up
+ create_table :toppings do |t|
+ t.string :name
+ t.integer :calories
+ t.integer :price
+
+ t.timestamps
+ end
+ end
+
+ def self.down
+ drop_table :toppings
+ end
+end
View
12 week_two/burger_madness/db/migrate/20101122002310_burger_toppings.rb
@@ -0,0 +1,12 @@
+class BurgerToppings < ActiveRecord::Migration
+ def self.up
+ create_table :burgers_toppings, :id => false do |t|
+ t.references :burger
+ t.references :topping
+ end
+ end
+
+ def self.down
+ drop_table :burgers_toppings
+ end
+end
View
14 week_two/burger_madness/db/migrate/20101122002352_create_orders.rb
@@ -0,0 +1,14 @@
+class CreateOrders < ActiveRecord::Migration
+ def self.up
+ create_table :orders do |t|
+ t.integer :burgers_id
+ t.integer :price
+
+ t.timestamps
+ end
+ end
+
+ def self.down
+ drop_table :orders
+ end
+end
View
9 week_two/burger_madness/db/migrate/20101122041433_add_order_id_column_to_burgers.rb
@@ -0,0 +1,9 @@
+class AddOrderIdColumnToBurgers < ActiveRecord::Migration
+ def self.up
+ add_column :burgers, :order_id, :integer
+ end
+
+ def self.down
+ remove_column :burgers, :order_id
+ end
+end
View
43 week_two/burger_madness/db/schema.rb
@@ -0,0 +1,43 @@
+# This file is auto-generated from the current state of the database. Instead
+# of editing this file, please use the migrations feature of Active Record to
+# incrementally modify your database, and then regenerate this schema definition.
+#
+# Note that this schema.rb definition is the authoritative source for your
+# database schema. If you need to create the application database on another
+# system, you should be using db:schema:load, not running all the migrations
+# from scratch. The latter is a flawed and unsustainable approach (the more migrations
+# you'll amass, the slower it'll run and the greater likelihood for issues).
+#
+# It's strongly recommended to check this file into your version control system.
+
+ActiveRecord::Schema.define(:version => 20101122041433) do
+
+ create_table "burgers", :force => true do |t|
+ t.string "name"
+ t.datetime "created_at"
+ t.datetime "updated_at"
+ t.integer "orders_id"
+ t.integer "order_id"
+ end
+
+ create_table "burgers_toppings", :id => false, :force => true do |t|
+ t.integer "burger_id"
+ t.integer "topping_id"
+ end
+
+ create_table "orders", :force => true do |t|
+ t.integer "burgers_id"
+ t.integer "price"
+ t.datetime "created_at"
+ t.datetime "updated_at"
+ end
+
+ create_table "toppings", :force => true do |t|
+ t.string "name"
+ t.integer "calories"
+ t.integer "price"
+ t.datetime "created_at"
+ t.datetime "updated_at"
+ end
+
+end
View
14 week_two/burger_madness/db/seeds.rb
@@ -0,0 +1,14 @@
+# Create some Toppings for each Burger Object
+Topping.create(:name => "pickles", :calories => 35, :price => 1)
+Topping.create(:name => "onions", :calories => 30, :price => 1)
+Topping.create(:name => "avacado", :calories => 80, :price => 1)
+Topping.create(:name => "bacon", :calories => 240, :price => 1)
+Topping.create(:name => "beef patty", :calories => 940, :price => 6)
+Topping.create(:name => "ahi tuna patty", :calories => 540, :price => 9)
+Topping.create(:name => "black bean patty", :calories => 240, :price => 4)
+Topping.create(:name => "boca patty", :calories => 280, :price => 6)
+Topping.create(:name => "turkey patty", :calories => 680, :price => 6)
+
+# Create some Burgers for the Default List
+Burger.create(:name => "Joe's Pitch n Put")
+Burger.create(:name => "Fred's Ahi Yum Yum")
View
2 week_two/burger_madness/doc/README_FOR_APP
@@ -0,0 +1,2 @@
+Use this README file to introduce your application and point to useful places in the API for learning more.
+Run "rake doc:app" to generate API documentation for your models, controllers, helpers, and libraries.
View
0 week_two/burger_madness/lib/tasks/.gitkeep
No changes.
View
26 week_two/burger_madness/public/404.html
@@ -0,0 +1,26 @@
+<!DOCTYPE html>
+<html>
+<head>
+ <title>The page you were looking for doesn't exist (404)</title>
+ <style type="text/css">
+ body { background-color: #fff; color: #666; text-align: center; font-family: arial, sans-serif; }
+ div.dialog {
+ width: 25em;
+ padding: 0 4em;
+ margin: 4em auto 0 auto;
+ border: 1px solid #ccc;
+ border-right-color: #999;
+ border-bottom-color: #999;
+ }
+ h1 { font-size: 100%; color: #f00; line-height: 1.5em; }
+ </style>
+</head>
+
+<body>
+ <!-- This file lives in public/404.html -->
+ <div class="dialog">
+ <h1>The page you were looking for doesn't exist.</h1>
+ <p>You may have mistyped the address or the page may have moved.</p>
+ </div>
+</body>
+</html>
View
26 week_two/burger_madness/public/422.html
@@ -0,0 +1,26 @@
+<!DOCTYPE html>
+<html>
+<head>
+ <title>The change you wanted was rejected (422)</title>
+ <style type="text/css">
+ body { background-color: #fff; color: #666; text-align: center; font-family: arial, sans-serif; }
+ div.dialog {
+ width: 25em;
+ padding: 0 4em;
+ margin: 4em auto 0 auto;
+ border: 1px solid #ccc;
+ border-right-color: #999;
+ border-bottom-color: #999;
+ }
+ h1 { font-size: 100%; color: #f00; line-height: 1.5em; }
+ </style>
+</head>
+
+<body>
+ <!-- This file lives in public/422.html -->
+ <div class="dialog">
+ <h1>The change you wanted was rejected.</h1>
+ <p>Maybe you tried to change something you didn't have access to.</p>
+ </div>
+</body>
+</html>
View
26 week_two/burger_madness/public/500.html
@@ -0,0 +1,26 @@
+<!DOCTYPE html>
+<html>
+<head>
+ <title>We're sorry, but something went wrong (500)</title>
+ <style type="text/css">
+ body { background-color: #fff; color: #666; text-align: center; font-family: arial, sans-serif; }
+ div.dialog {
+ width: 25em;
+ padding: 0 4em;
+ margin: 4em auto 0 auto;
+ border: 1px solid #ccc;
+ border-right-color: #999;
+ border-bottom-color: #999;
+ }
+ h1 { font-size: 100%; color: #f00; line-height: 1.5em; }
+ </style>
+</head>
+
+<body>
+ <!-- This file lives in public/500.html -->
+ <div class="dialog">
+ <h1>We're sorry, but something went wrong.</h1>
+ <p>We've been notified about this issue and we'll take a look at it shortly.</p>
+ </div>
+</body>
+</html>
View
0 week_two/burger_madness/public/favicon.ico
No changes.
View
BIN week_two/burger_madness/public/images/burger_icon.png
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
View
BIN week_two/burger_madness/public/images/rails.png
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
View
2 week_two/burger_madness/public/javascripts/application.js
@@ -0,0 +1,2 @@
+// Place your application-specific JavaScript functions and classes here
+// This file is automatically included by javascript_include_tag :defaults
View
965 week_two/burger_madness/public/javascripts/controls.js
@@ -0,0 +1,965 @@
+// script.aculo.us controls.js v1.8.3, Thu Oct 08 11:23:33 +0200 2009
+
+// Copyright (c) 2005-2009 Thomas Fuchs (http://script.aculo.us, http://mir.aculo.us)
+// (c) 2005-2009 Ivan Krstic (http://blogs.law.harvard.edu/ivan)
+// (c) 2005-2009 Jon Tirsen (http://www.tirsen.com)
+// Contributors:
+// Richard Livsey
+// Rahul Bhargava
+// Rob Wills
+//
+// script.aculo.us is freely distributable under the terms of an MIT-style license.
+// For details, see the script.aculo.us web site: http://script.aculo.us/
+
+// Autocompleter.Base handles all the autocompletion functionality
+// that's independent of the data source for autocompletion. This
+// includes drawing the autocompletion menu, observing keyboard
+// and mouse events, and similar.
+//
+// Specific autocompleters need to provide, at the very least,
+// a getUpdatedChoices function that will be invoked every time
+// the text inside the monitored textbox changes. This method
+// should get the text for which to provide autocompletion by
+// invoking this.getToken(), NOT by directly accessing
+// this.element.value. This is to allow incremental tokenized
+// autocompletion. Specific auto-completion logic (AJAX, etc)
+// belongs in getUpdatedChoices.
+//
+// Tokenized incremental autocompletion is enabled automatically
+// when an autocompleter is instantiated with the 'tokens' option
+// in the options parameter, e.g.:
+// new Ajax.Autocompleter('id','upd', '/url/', { tokens: ',' });
+// will incrementally autocomplete with a comma as the token.
+// Additionally, ',' in the above example can be replaced with
+// a token array, e.g. { tokens: [',', '\n'] } which
+// enables autocompletion on multiple tokens. This is most
+// useful when one of the tokens is \n (a newline), as it
+// allows smart autocompletion after linebreaks.
+
+if(typeof Effect == 'undefined')
+ throw("controls.js requires including script.aculo.us' effects.js library");
+
+var Autocompleter = { };
+Autocompleter.Base = Class.create({
+ baseInitialize: function(element, update, options) {
+ element = $(element);
+ this.element = element;
+ this.update = $(update);
+ this.hasFocus = false;
+ this.changed = false;
+ this.active = false;
+ this.index = 0;
+ this.entryCount = 0;
+ this.oldElementValue = this.element.value;
+
+ if(this.setOptions)
+ this.setOptions(options);
+ else
+ this.options = options || { };
+
+ this.options.paramName = this.options.paramName || this.element.name;
+ this.options.tokens = this.options.tokens || [];
+ this.options.frequency = this.options.frequency || 0.4;
+ this.options.minChars = this.options.minChars || 1;
+ this.options.onShow = this.options.onShow ||
+ function(element, update){
+ if(!update.style.position || update.style.position=='absolute') {
+ update.style.position = 'absolute';
+ Position.clone(element, update, {
+ setHeight: false,
+ offsetTop: element.offsetHeight
+ });
+ }
+ Effect.Appear(update,{duration:0.15});
+ };
+ this.options.onHide = this.options.onHide ||
+ function(element, update){ new Effect.Fade(update,{duration:0.15}) };
+
+ if(typeof(this.options.tokens) == 'string')
+ this.options.tokens = new Array(this.options.tokens);
+ // Force carriage returns as token delimiters anyway
+ if (!this.options.tokens.include('\n'))
+ this.options.tokens.push('\n');
+
+ this.observer = null;
+
+ this.element.setAttribute('autocomplete','off');
+
+ Element.hide(this.update);
+
+ Event.observe(this.element, 'blur', this.onBlur.bindAsEventListener(this));
+ Event.observe(this.element, 'keydown', this.onKeyPress.bindAsEventListener(this));
+ },
+
+ show: function() {
+ if(Element.getStyle(this.update, 'display')=='none') this.options.onShow(this.element, this.update);
+ if(!this.iefix &&
+ (Prototype.Browser.IE) &&
+ (Element.getStyle(this.update, 'position')=='absolute')) {
+ new Insertion.After(this.update,
+ '<iframe id="' + this.update.id + '_iefix" '+
+ 'style="display:none;position:absolute;filter:progid:DXImageTransform.Microsoft.Alpha(opacity=0);" ' +
+ 'src="javascript:false;" frameborder="0" scrolling="no"></iframe>');
+ this.iefix = $(this.update.id+'_iefix');
+ }
+ if(this.iefix) setTimeout(this.fixIEOverlapping.bind(this), 50);
+ },
+
+ fixIEOverlapping: function() {
+ Position.clone(this.update, this.iefix, {setTop:(!this.update.style.height)});
+ this.iefix.style.zIndex = 1;
+ this.update.style.zIndex = 2;
+ Element.show(this.iefix);
+ },
+
+ hide: function() {
+ this.stopIndicator();
+ if(Element.getStyle(this.update, 'display')!='none') this.options.onHide(this.element, this.update);
+ if(this.iefix) Element.hide(this.iefix);
+ },
+
+ startIndicator: function() {
+ if(this.options.indicator) Element.show(this.options.indicator);
+ },
+
+ stopIndicator: function() {
+ if(this.options.indicator) Element.hide(this.options.indicator);
+ },
+
+ onKeyPress: function(event) {
+ if(this.active)
+ switch(event.keyCode) {
+ case Event.KEY_TAB:
+ case Event.KEY_RETURN:
+ this.selectEntry();
+ Event.stop(event);
+ case Event.KEY_ESC:
+ this.hide();
+ this.active = false;
+ Event.stop(event);
+ return;
+ case Event.KEY_LEFT:
+ case Event.KEY_RIGHT:
+ return;
+ case Event.KEY_UP:
+ this.markPrevious();
+ this.render();
+ Event.stop(event);
+ return;
+ case Event.KEY_DOWN:
+ this.markNext();
+ this.render();
+ Event.stop(event);
+ return;
+ }
+ else
+ if(event.keyCode==Event.KEY_TAB || event.keyCode==Event.KEY_RETURN ||
+ (Prototype.Browser.WebKit > 0 && event.keyCode == 0)) return;
+
+ this.changed = true;
+ this.hasFocus = true;
+
+ if(this.observer) clearTimeout(this.observer);
+ this.observer =
+ setTimeout(this.onObserverEvent.bind(this), this.options.frequency*1000);
+ },
+
+ activate: function() {
+ this.changed = false;
+ this.hasFocus = true;
+ this.getUpdatedChoices();
+ },
+
+ onHover: function(event) {
+ var element = Event.findElement(event, 'LI');
+ if(this.index != element.autocompleteIndex)
+ {
+ this.index = element.autocompleteIndex;
+ this.render();
+ }
+ Event.stop(event);
+ },
+
+ onClick: function(event) {
+ var element = Event.findElement(event, 'LI');
+ this.index = element.autocompleteIndex;
+ this.selectEntry();
+ this.hide();
+ },
+
+ onBlur: function(event) {
+ // needed to make click events working
+ setTimeout(this.hide.bind(this), 250);
+ this.hasFocus = false;
+ this.active = false;
+ },
+
+ render: function() {
+ if(this.entryCount > 0) {
+ for (var i = 0; i < this.entryCount; i++)
+ this.index==i ?
+ Element.addClassName(this.getEntry(i),"selected") :
+ Element.removeClassName(this.getEntry(i),"selected");
+ if(this.hasFocus) {
+ this.show();
+ this.active = true;
+ }
+ } else {
+ this.active = false;
+ this.hide();
+ }
+ },
+
+ markPrevious: function() {
+ if(this.index > 0) this.index--;
+ else this.index = this.entryCount-1;
+ this.getEntry(this.index).scrollIntoView(true);
+ },
+
+ markNext: function() {
+ if(this.index < this.entryCount-1) this.index++;
+ else this.index = 0;
+ this.getEntry(this.index).scrollIntoView(false);
+ },
+
+ getEntry: function(index) {
+ return this.update.firstChild.childNodes[index];
+ },
+
+ getCurrentEntry: function() {
+ return this.getEntry(this.index);
+ },
+
+ selectEntry: function() {
+ this.active = false;
+ this.updateElement(this.getCurrentEntry());
+ },
+
+ updateElement: function(selectedElement) {
+ if (this.options.updateElement) {
+ this.options.updateElement(selectedElement);
+ return;
+ }
+ var value = '';
+ if (this.options.select) {
+ var nodes = $(selectedElement).select('.' + this.options.select) || [];
+ if(nodes.length>0) value = Element.collectTextNodes(nodes[0], this.options.select);
+ } else
+ value = Element.collectTextNodesIgnoreClass(selectedElement, 'informal');
+
+ var bounds = this.getTokenBounds();
+ if (bounds[0] != -1) {
+ var newValue = this.element.value.substr(0, bounds[0]);
+ var whitespace = this.element.value.substr(bounds[0]).match(/^\s+/);
+ if (whitespace)
+ newValue += whitespace[0];
+ this.element.value = newValue + value + this.element.value.substr(bounds[1]);
+ } else {
+ this.element.value = value;
+ }
+ this.oldElementValue = this.element.value;
+ this.element.focus();
+
+ if (this.options.afterUpdateElement)
+ this.options.afterUpdateElement(this.element, selectedElement);
+ },
+
+ updateChoices: function(choices) {
+ if(!this.changed && this.hasFocus) {
+ this.update.innerHTML = choices;
+ Element.cleanWhitespace(this.update);
+ Element.cleanWhitespace(this.update.down());
+
+ if(this.update.firstChild && this.update.down().childNodes) {
+ this.entryCount =
+ this.update.down().childNodes.length;
+ for (var i = 0; i < this.entryCount; i++) {
+ var entry = this.getEntry(i);
+ entry.autocompleteIndex = i;
+ this.addObservers(entry);
+ }
+ } else {
+ this.entryCount = 0;
+ }
+
+ this.stopIndicator();
+ this.index = 0;
+
+ if(this.entryCount==1 && this.options.autoSelect) {
+ this.selectEntry();
+ this.hide();
+ } else {
+ this.render();
+ }
+ }
+ },
+
+ addObservers: function(element) {
+ Event.observe(element, "mouseover", this.onHover.bindAsEventListener(this));
+ Event.observe(element, "click", this.onClick.bindAsEventListener(this));
+ },
+
+ onObserverEvent: function() {
+ this.changed = false;
+ this.tokenBounds = null;
+ if(this.getToken().length>=this.options.minChars) {
+ this.getUpdatedChoices();
+ } else {
+ this.active = false;
+ this.hide();
+ }
+ this.oldElementValue = this.element.value;
+ },
+
+ getToken: function() {
+ var bounds = this.getTokenBounds();
+ return this.element.value.substring(bounds[0], bounds[1]).strip();
+ },
+
+ getTokenBounds: function() {
+ if (null != this.tokenBounds) return this.tokenBounds;
+ var value = this.element.value;
+ if (value.strip().empty()) return [-1, 0];
+ var diff = arguments.callee.getFirstDifferencePos(value, this.oldElementValue);
+ var offset = (diff == this.oldElementValue.length ? 1 : 0);
+ var prevTokenPos = -1, nextTokenPos = value.length;
+ var tp;
+ for (var index = 0, l = this.options.tokens.length; index < l; ++index) {
+ tp = value.lastIndexOf(this.options.tokens[index], diff + offset - 1);
+ if (tp > prevTokenPos) prevTokenPos = tp;
+ tp = value.indexOf(this.options.tokens[index], diff + offset);
+ if (-1 != tp && tp < nextTokenPos) nextTokenPos = tp;
+ }
+ return (this.tokenBounds = [prevTokenPos + 1, nextTokenPos]);
+ }
+});
+
+Autocompleter.Base.prototype.getTokenBounds.getFirstDifferencePos = function(newS, oldS) {
+ var boundary = Math.min(newS.length, oldS.length);
+ for (var index = 0; index < boundary; ++index)
+ if (newS[index] != oldS[index])
+ return index;
+ return boundary;
+};
+
+Ajax.Autocompleter = Class.create(Autocompleter.Base, {
+ initialize: function(element, update, url, options) {
+ this.baseInitialize(element, update, options);
+ this.options.asynchronous = true;
+ this.options.onComplete = this.onComplete.bind(this);
+ this.options.defaultParams = this.options.parameters || null;
+ this.url = url;
+ },
+
+ getUpdatedChoices: function() {
+ this.startIndicator();
+
+ var entry = encodeURIComponent(this.options.paramName) + '=' +
+ encodeURIComponent(this.getToken());
+
+ this.options.parameters = this.options.callback ?
+ this.options.callback(this.element, entry) : entry;
+
+ if(this.options.defaultParams)
+ this.options.parameters += '&' + this.options.defaultParams;
+
+ new Ajax.Request(this.url, this.options);
+ },
+
+ onComplete: function(request) {
+ this.updateChoices(request.responseText);
+ }
+});
+
+// The local array autocompleter. Used when you'd prefer to
+// inject an array of autocompletion options into the page, rather
+// than sending out Ajax queries, which can be quite slow sometimes.
+//
+// The constructor takes four parameters. The first two are, as usual,
+// the id of the monitored textbox, and id of the autocompletion menu.
+// The third is the array you want to autocomplete from, and the fourth
+// is the options block.
+//
+// Extra local autocompletion options:
+// - choices - How many autocompletion choices to offer
+//
+// - partialSearch - If false, the autocompleter will match entered
+// text only at the beginning of strings in the
+// autocomplete array. Defaults to true, which will
+// match text at the beginning of any *word* in the
+// strings in the autocomplete array. If you want to
+// search anywhere in the string, additionally set
+// the option fullSearch to true (default: off).
+//
+// - fullSsearch - Search anywhere in autocomplete array strings.
+//
+// - partialChars - How many characters to enter before triggering
+// a partial match (unlike minChars, which defines
+// how many characters are required to do any match
+// at all). Defaults to 2.
+//
+// - ignoreCase - Whether to ignore case when autocompleting.
+// Defaults to true.
+//
+// It's possible to pass in a custom function as the 'selector'
+// option, if you prefer to write your own autocompletion logic.
+// In that case, the other options above will not apply unless
+// you support them.
+
+Autocompleter.Local = Class.create(Autocompleter.Base, {
+ initialize: function(element, update, array, options) {
+ this.baseInitialize(element, update, options);
+ this.options.array = array;
+ },
+
+ getUpdatedChoices: function() {
+ this.updateChoices(this.options.selector(this));
+ },
+
+ setOptions: function(options) {
+ this.options = Object.extend({
+ choices: 10,
+ partialSearch: true,
+ partialChars: 2,
+ ignoreCase: true,
+ fullSearch: false,
+ selector: function(instance) {
+ var ret = []; // Beginning matches
+ var partial = []; // Inside matches
+ var entry = instance.getToken();
+ var count = 0;
+
+ for (var i = 0; i < instance.options.array.length &&
+ ret.length < instance.options.choices ; i++) {
+
+ var elem = instance.options.array[i];
+ var foundPos = instance.options.ignoreCase ?
+ elem.toLowerCase().indexOf(entry.toLowerCase()) :
+ elem.indexOf(entry);
+
+ while (foundPos != -1) {
+ if (foundPos == 0 && elem.length != entry.length) {
+ ret.push("<li><strong>" + elem.substr(0, entry.length) + "</strong>" +
+ elem.substr(entry.length) + "</li>");
+ break;
+ } else if (entry.length >= instance.options.partialChars &&
+ instance.options.partialSearch && foundPos != -1) {
+ if (instance.options.fullSearch || /\s/.test(elem.substr(foundPos-1,1))) {
+ partial.push("<li>" + elem.substr(0, foundPos) + "<strong>" +
+ elem.substr(foundPos, entry.length) + "</strong>" + elem.substr(
+ foundPos + entry.length) + "</li>");
+ break;
+ }
+ }
+
+ foundPos = instance.options.ignoreCase ?
+ elem.toLowerCase().indexOf(entry.toLowerCase(), foundPos + 1) :
+ elem.indexOf(entry, foundPos + 1);
+
+ }
+ }
+ if (partial.length)
+ ret = ret.concat(partial.slice(0, instance.options.choices - ret.length));
+ return "<ul>" + ret.join('') + "</ul>";
+ }
+ }, options || { });
+ }
+});
+
+// AJAX in-place editor and collection editor
+// Full rewrite by Christophe Porteneuve <tdd@tddsworld.com> (April 2007).
+
+// Use this if you notice weird scrolling problems on some browsers,
+// the DOM might be a bit confused when this gets called so do this
+// waits 1 ms (with setTimeout) until it does the activation
+Field.scrollFreeActivate = function(field) {
+ setTimeout(function() {
+ Field.activate(field);
+ }, 1);
+};
+
+Ajax.InPlaceEditor = Class.create({
+ initialize: function(element, url, options) {
+ this.url = url;
+ this.element = element = $(element);
+ this.prepareOptions();
+ this._controls = { };
+ arguments.callee.dealWithDeprecatedOptions(options); // DEPRECATION LAYER!!!
+ Object.extend(this.options, options || { });
+ if (!this.options.formId && this.element.id) {
+ this.options.formId = this.element.id + '-inplaceeditor';
+ if ($(this.options.formId))
+ this.options.formId = '';
+ }
+ if (this.options.externalControl)
+ this.options.externalControl = $(this.options.externalControl);
+ if (!this.options.externalControl)
+ this.options.externalControlOnly = false;
+ this._originalBackground = this.element.getStyle('background-color') || 'transparent';
+ this.element.title = this.options.clickToEditText;
+ this._boundCancelHandler = this.handleFormCancellation.bind(this);
+ this._boundComplete = (this.options.onComplete || Prototype.emptyFunction).bind(this);
+ this._boundFailureHandler = this.handleAJAXFailure.bind(this);
+ this._boundSubmitHandler = this.handleFormSubmission.bind(this);
+ this._boundWrapperHandler = this.wrapUp.bind(this);
+ this.registerListeners();
+ },
+ checkForEscapeOrReturn: function(e) {
+ if (!this._editing || e.ctrlKey || e.altKey || e.shiftKey) return;
+ if (Event.KEY_ESC == e.keyCode)
+ this.handleFormCancellation(e);
+ else if (Event.KEY_RETURN == e.keyCode)
+ this.handleFormSubmission(e);
+ },
+ createControl: function(mode, handler, extraClasses) {
+ var control = this.options[mode + 'Control'];
+ var text = this.options[mode + 'Text'];
+ if ('button' == control) {
+ var btn = document.createElement('input');
+ btn.type = 'submit';
+ btn.value = text;
+ btn.className = 'editor_' + mode + '_button';
+ if ('cancel' == mode)
+ btn.onclick = this._boundCancelHandler;
+ this._form.appendChild(btn);
+ this._controls[mode] = btn;
+ } else if ('link' == control) {
+ var link = document.createElement('a');
+ link.href = '#';
+ link.appendChild(document.createTextNode(text));
+ link.onclick = 'cancel' == mode ? this._boundCancelHandler : this._boundSubmitHandler;
+ link.className = 'editor_' + mode + '_link';
+ if (extraClasses)
+ link.className += ' ' + extraClasses;
+ this._form.appendChild(link);
+ this._controls[mode] = link;
+ }
+ },
+ createEditField: function() {
+ var text = (this.options.loadTextURL ? this.options.loadingText : this.getText());
+ var fld;
+ if (1 >= this.options.rows && !/\r|\n/.test(this.getText())) {
+ fld = document.createElement('input');
+ fld.type = 'text';
+ var size = this.options.size || this.options.cols || 0;
+ if (0 < size) fld.size = size;
+ } else {
+ fld = document.createElement('textarea');
+ fld.rows = (1 >= this.options.rows ? this.options.autoRows : this.options.rows);
+ fld.cols = this.options.cols || 40;
+ }
+ fld.name = this.options.paramName;
+ fld.value = text; // No HTML breaks conversion anymore
+ fld.className = 'editor_field';
+ if (this.options.submitOnBlur)
+ fld.onblur = this._boundSubmitHandler;
+ this._controls.editor = fld;
+ if (this.options.loadTextURL)
+ this.loadExternalText();
+ this._form.appendChild(this._controls.editor);
+ },
+ createForm: function() {
+ var ipe = this;
+ function addText(mode, condition) {
+ var text = ipe.options['text' + mode + 'Controls'];
+ if (!text || condition === false) return;
+ ipe._form.appendChild(document.createTextNode(text));
+ };
+ this._form = $(document.createElement('form'));
+ this._form.id = this.options.formId;
+ this._form.addClassName(this.options.formClassName);
+ this._form.onsubmit = this._boundSubmitHandler;
+ this.createEditField();
+ if ('textarea' == this._controls.editor.tagName.toLowerCase())
+ this._form.appendChild(document.createElement('br'));
+ if (this.options.onFormCustomization)
+ this.options.onFormCustomization(this, this._form);
+ addText('Before', this.options.okControl || this.options.cancelControl);
+ this.createControl('ok', this._boundSubmitHandler);
+ addText('Between', this.options.okControl && this.options.cancelControl);
+ this.createControl('cancel', this._boundCancelHandler, 'editor_cancel');
+ addText('After', this.options.okControl || this.options.cancelControl);
+ },
+ destroy: function() {
+ if (this._oldInnerHTML)
+ this.element.innerHTML = this._oldInnerHTML;
+ this.leaveEditMode();
+ this.unregisterListeners();
+ },
+ enterEditMode: function(e) {
+ if (this._saving || this._editing) return;
+ this._editing = true;
+ this.triggerCallback('onEnterEditMode');
+ if (this.options.externalControl)
+ this.options.externalControl.hide();
+ this.element.hide();
+ this.createForm();
+ this.element.parentNode.insertBefore(this._form, this.element);
+ if (!this.options.loadTextURL)
+ this.postProcessEditField();
+ if (e) Event.stop(e);
+ },
+ enterHover: function(e) {
+ if (this.options.hoverClassName)
+ this.element.addClassName(this.options.hoverClassName);
+ if (this._saving) return;
+ this.triggerCallback('onEnterHover');
+ },
+ getText: function() {
+ return this.element.innerHTML.unescapeHTML();
+ },
+ handleAJAXFailure: function(transport) {
+ this.triggerCallback('onFailure', transport);
+ if (this._oldInnerHTML) {
+ this.element.innerHTML = this._oldInnerHTML;
+ this._oldInnerHTML = null;
+ }
+ },
+ handleFormCancellation: function(e) {
+ this.wrapUp();
+ if (e) Event.stop(e);
+ },
+ handleFormSubmission: function(e) {
+ var form = this._form;
+ var value = $F(this._controls.editor);
+ this.prepareSubmission();
+ var params = this.options.callback(form, value) || '';
+ if (Object.isString(params))
+ params = params.toQueryParams();
+ params.editorId = this.element.id;
+ if (this.options.htmlResponse) {
+ var options = Object.extend({ evalScripts: true }, this.options.ajaxOptions);
+ Object.extend(options, {
+ parameters: params,
+ onComplete: this._boundWrapperHandler,
+ onFailure: this._boundFailureHandler
+ });
+ new Ajax.Updater({ success: this.element }, this.url, options);
+ } else {
+ var options = Object.extend({ method: 'get' }, this.options.ajaxOptions);
+ Object.extend(options, {
+ parameters: params,
+ onComplete: this._boundWrapperHandler,
+ onFailure: this._boundFailureHandler
+ });
+ new Ajax.Request(this.url, options);
+ }
+ if (e) Event.stop(e);
+ },
+ leaveEditMode: function() {
+ this.element.removeClassName(this.options.savingClassName);
+ this.removeForm();
+ this.leaveHover();
+ this.element.style.backgroundColor = this._originalBackground;
+ this.element.show();
+ if (this.options.externalControl)
+ this.options.externalControl.show();
+ this._saving = false;
+ this._editing = false;
+ this._oldInnerHTML = null;
+ this.triggerCallback('onLeaveEditMode');
+ },
+ leaveHover: function(e) {
+ if (this.options.hoverClassName)
+ this.element.removeClassName(this.options.hoverClassName);
+ if (this._saving) return;
+ this.triggerCallback('onLeaveHover');
+ },
+ loadExternalText: function() {
+ this._form.addClassName(this.options.loadingClassName);
+ this._controls.editor.disabled = true;
+ var options = Object.extend({ method: 'get' }, this.options.ajaxOptions);
+ Object.extend(options, {
+ parameters: 'editorId=' + encodeURIComponent(this.element.id),
+ onComplete: Prototype.emptyFunction,
+ onSuccess: function(transport) {
+ this._form.removeClassName(this.options.loadingClassName);
+ var text = transport.responseText;
+ if (this.options.stripLoadedTextTags)
+ text = text.stripTags();
+ this._controls.editor.value = text;
+ this._controls.editor.disabled = false;
+ this.postProcessEditField();
+ }.bind(this),
+ onFailure: this._boundFailureHandler
+ });
+ new Ajax.Request(this.options.loadTextURL, options);
+ },
+ postProcessEditField: function() {
+ var fpc = this.options.fieldPostCreation;
+ if (fpc)
+ $(this._controls.editor)['focus' == fpc ? 'focus' : 'activate']();
+ },
+ prepareOptions: function() {
+ this.options = Object.clone(Ajax.InPlaceEditor.DefaultOptions);
+ Object.extend(this.options, Ajax.InPlaceEditor.DefaultCallbacks);
+ [this._extraDefaultOptions].flatten().compact().each(function(defs) {
+ Object.extend(this.options, defs);
+ }.bind(this));
+ },
+ prepareSubmission: function() {
+ this._saving = true;
+ this.removeForm();
+ this.leaveHover();
+ this.showSaving();
+ },
+ registerListeners: function() {
+ this._listeners = { };
+ var listener;
+ $H(Ajax.InPlaceEditor.Listeners).each(function(pair) {
+ listener = this[pair.value].bind(this);
+ this._listeners[pair.key] = listener;
+ if (!this.options.externalControlOnly)
+ this.element.observe(pair.key, listener);
+ if (this.options.externalControl)
+ this.options.externalControl.observe(pair.key, listener);
+ }.bind(this));
+ },
+ removeForm: function() {
+ if (!this._form) return;
+ this._form.remove();
+ this._form = null;
+ this._controls = { };
+ },
+ showSaving: function() {
+ this._oldInnerHTML = this.element.innerHTML;
+ this.element.innerHTML = this.options.savingText;
+ this.element.addClassName(this.options.savingClassName);
+ this.element.style.backgroundColor = this._originalBackground;
+ this.element.show();
+ },
+ triggerCallback: function(cbName, arg) {
+ if ('function' == typeof this.options[cbName]) {
+ this.options[cbName](this, arg);
+ }
+ },
+ unregisterListeners: function() {
+ $H(this._listeners).each(function(pair) {
+ if (!this.options.externalControlOnly)
+ this.element.stopObserving(pair.key, pair.value);
+ if (this.options.externalControl)
+ this.options.externalControl.stopObserving(pair.key, pair.value);
+ }.bind(this));
+ },
+ wrapUp: function(transport) {
+ this.leaveEditMode();
+ // Can't use triggerCallback due to backward compatibility: requires
+ // binding + direct element
+ this._boundComplete(transport, this.element);
+ }
+});
+
+Object.extend(Ajax.InPlaceEditor.prototype, {
+ dispose: Ajax.InPlaceEditor.prototype.destroy
+});
+
+Ajax.InPlaceCollectionEditor = Class.create(Ajax.InPlaceEditor, {
+ initialize: function($super, element, url, options) {
+ this._extraDefaultOptions = Ajax.InPlaceCollectionEditor.DefaultOptions;
+ $super(element, url, options);
+ },
+
+ createEditField: function() {
+ var list = document.createElement('select');
+ list.name = this.options.paramName;
+ list.size = 1;
+ this._controls.editor = list;
+ this._collection = this.options.collection || [];
+ if (this.options.loadCollectionURL)
+ this.loadCollection();
+ else
+ this.checkForExternalText();
+ this._form.appendChild(this._controls.editor);
+ },
+
+ loadCollection: function() {
+ this._form.addClassName(this.options.loadingClassName);
+ this.showLoadingText(this.options.loadingCollectionText);
+ var options = Object.extend({ method: 'get' }, this.options.ajaxOptions);
+ Object.extend(options, {
+ parameters: 'editorId=' + encodeURIComponent(this.element.id),
+ onComplete: Prototype.emptyFunction,
+ onSuccess: function(transport) {
+ var js = transport.responseText.strip();
+ if (!/^\[.*\]$/.test(js)) // TODO: improve sanity check
+ throw('Server returned an invalid collection representation.');
+ this._collection = eval(js);
+ this.checkForExternalText();
+ }.bind(this),
+ onFailure: this.onFailure
+ });
+ new Ajax.Request(this.options.loadCollectionURL, options);
+ },
+
+ showLoadingText: function(text) {
+ this._controls.editor.disabled = true;
+ var tempOption = this._controls.editor.firstChild;
+ if (!tempOption) {
+ tempOption = document.createElement('option');