Merged changes from jdong's branch into HEAD.
author<mako@atdot.cc> <>
Fri, 17 Aug 2007 20:49:15 +0000 (16:49 -0400)
committer<mako@atdot.cc> <>
Fri, 17 Aug 2007 20:49:15 +0000 (16:49 -0400)
89 files changed:
TODO
app/apis/selectricity_api.rb
app/controllers/graph_controller.rb
app/controllers/quickvote_controller.rb
app/models/quick_vote.rb
app/models/selectricity_service.rb
app/views/quickvote/_defeats_list.rhtml [new file with mode: 0644]
app/views/quickvote/_pref_table.rhtml
app/views/quickvote/mapvoters.rhtml [new file with mode: 0644]
app/views/quickvote/results.rhtml
config/environment.rb
config/gmaps_api_key.yml [new file with mode: 0644]
db/schema.rb
lib/rubyvote/condorcet.rb
lib/rubyvote/election.rb
lib/whois/data/ipv4.yaml [new file with mode: 0644]
lib/whois/data/ipv6.yaml [new file with mode: 0644]
lib/whois/server/server.rb [new file with mode: 0644]
lib/whois/whois.rb [new file with mode: 0755]
public/javascripts/clusterer.js [new file with mode: 0644]
public/javascripts/geoRssOverlay.js [new file with mode: 0644]
public/javascripts/markerGroup.js [new file with mode: 0644]
public/javascripts/wms-gs.js [new file with mode: 0644]
public/javascripts/ym4r-gm.js [new file with mode: 0644]
test/fixtures/full_voters.yml [deleted file]
test/fixtures/quick_voters.yml [deleted file]
test/fixtures/quick_votes.yml [deleted file]
test/functional/election_controller_test.rb
test/functional/graph_controller_test.rb [moved from test/functional/graphs_controller_test.rb with 52% similarity]
test/functional/user_controller_test.rb [deleted file]
test/unit/full_voter_test.rb [deleted file]
test/unit/quick_vote_test.rb [deleted file]
test/unit/quick_voter_test.rb [deleted file]
test/unit/raw_voter_list_test.rb [deleted file]
test/unit/selectricityservice_test.rb [new file with mode: 0644]
test/unit/vote_test.rb [deleted file]
test/unit/voter_notify_test.rb [deleted file]
vendor/plugins/geokit/MIT-LICENSE [new file with mode: 0644]
vendor/plugins/geokit/README [new file with mode: 0644]
vendor/plugins/geokit/Rakefile [new file with mode: 0644]
vendor/plugins/geokit/about.yml [new file with mode: 0644]
vendor/plugins/geokit/assets/api_keys_template [new file with mode: 0644]
vendor/plugins/geokit/init.rb [new file with mode: 0644]
vendor/plugins/geokit/install.rb [new file with mode: 0644]
vendor/plugins/geokit/lib/geo_kit/acts_as_mappable.rb [new file with mode: 0644]
vendor/plugins/geokit/lib/geo_kit/defaults.rb [new file with mode: 0644]
vendor/plugins/geokit/lib/geo_kit/geocoders.rb [new file with mode: 0644]
vendor/plugins/geokit/lib/geo_kit/ip_geocode_lookup.rb [new file with mode: 0644]
vendor/plugins/geokit/lib/geo_kit/mappable.rb [new file with mode: 0644]
vendor/plugins/geokit/test/acts_as_mappable_test.rb [new file with mode: 0644]
vendor/plugins/geokit/test/base_geocoder_test.rb [new file with mode: 0644]
vendor/plugins/geokit/test/bounds_test.rb [new file with mode: 0644]
vendor/plugins/geokit/test/ca_geocoder_test.rb [new file with mode: 0644]
vendor/plugins/geokit/test/fixtures/companies.yml [new file with mode: 0644]
vendor/plugins/geokit/test/fixtures/custom_locations.yml [new file with mode: 0644]
vendor/plugins/geokit/test/fixtures/locations.yml [new file with mode: 0644]
vendor/plugins/geokit/test/fixtures/stores.yml [new file with mode: 0644]
vendor/plugins/geokit/test/geoloc_test.rb [new file with mode: 0644]
vendor/plugins/geokit/test/google_geocoder_test.rb [new file with mode: 0644]
vendor/plugins/geokit/test/ip_geocode_lookup_test.rb [new file with mode: 0644]
vendor/plugins/geokit/test/ipgeocoder_test.rb [new file with mode: 0644]
vendor/plugins/geokit/test/latlng_test.rb [new file with mode: 0644]
vendor/plugins/geokit/test/multi_geocoder_test.rb [new file with mode: 0644]
vendor/plugins/geokit/test/schema.rb [new file with mode: 0644]
vendor/plugins/geokit/test/test_helper.rb [new file with mode: 0644]
vendor/plugins/geokit/test/us_geocoder_test.rb [new file with mode: 0644]
vendor/plugins/geokit/test/yahoo_geocoder_test.rb [new file with mode: 0644]
vendor/plugins/ym4r_gm/README [new file with mode: 0644]
vendor/plugins/ym4r_gm/gmaps_api_key.yml [new file with mode: 0644]
vendor/plugins/ym4r_gm/init.rb [new file with mode: 0644]
vendor/plugins/ym4r_gm/install.rb [new file with mode: 0644]
vendor/plugins/ym4r_gm/javascript/clusterer.js [new file with mode: 0644]
vendor/plugins/ym4r_gm/javascript/geoRssOverlay.js [new file with mode: 0644]
vendor/plugins/ym4r_gm/javascript/markerGroup.js [new file with mode: 0644]
vendor/plugins/ym4r_gm/javascript/wms-gs.js [new file with mode: 0644]
vendor/plugins/ym4r_gm/javascript/ym4r-gm.js [new file with mode: 0644]
vendor/plugins/ym4r_gm/lib/gm_plugin/control.rb [new file with mode: 0644]
vendor/plugins/ym4r_gm/lib/gm_plugin/geocoding.rb [new file with mode: 0644]
vendor/plugins/ym4r_gm/lib/gm_plugin/helper.rb [new file with mode: 0644]
vendor/plugins/ym4r_gm/lib/gm_plugin/key.rb [new file with mode: 0644]
vendor/plugins/ym4r_gm/lib/gm_plugin/layer.rb [new file with mode: 0644]
vendor/plugins/ym4r_gm/lib/gm_plugin/map.rb [new file with mode: 0644]
vendor/plugins/ym4r_gm/lib/gm_plugin/mapping.rb [new file with mode: 0644]
vendor/plugins/ym4r_gm/lib/gm_plugin/overlay.rb [new file with mode: 0644]
vendor/plugins/ym4r_gm/lib/gm_plugin/point.rb [new file with mode: 0644]
vendor/plugins/ym4r_gm/lib/ym4r_gm.rb [new file with mode: 0644]
vendor/plugins/ym4r_gm/rakefile.rb [new file with mode: 0644]
vendor/plugins/ym4r_gm/tasks/gm_tasks.rake [new file with mode: 0644]
vendor/plugins/ym4r_gm/test/gm_test.rb [new file with mode: 0644]

diff --git a/TODO b/TODO
index 246b67370573cba31d68912ad5d8d28ab097d971..be982eeb0f2e80459948cc28269d7a197049e975 100644 (file)
--- a/TODO
+++ b/TODO
@@ -1,5 +1,2 @@
 Known bugs or issues:
 
-* make sure that quickvotes names are not integers
-* Run testcases against QuickVotes results (after refactor work)
-
index 8a8dce4d8072faca8cbc29b7e9e1d496c2a521c9..b1210c6e861eb9b02c1d8a7693ee5885241d5986 100644 (file)
@@ -1,3 +1,17 @@
+class ElectionStruct < ActionWebService::Struct
+  member :name, :string
+  member :description, :string
+  member :candidate_ids, [:int]
+  member :candidate_names, [:string]
+  member :id, :int
+end
+class VoteInfo < ActionWebService::Struct
+  member :voter_id, :int
+  member :voter_ipaddress, :string
+  member :vote_time, :int
+  member :vote, [:int]
+end
+
 class VoteResultStruct < ActionWebService::Struct
   member :plurality_winners, [:int]
   member :approval_winners, [:int]
@@ -16,6 +30,10 @@ class SelectricityAPI < ActionWebService::API::Base
   api_method :get_quickvote_results, :expects => [:string], :returns => [VoteResultStruct]
   api_method :get_quickvote_candidate_map, :expects => [:string], :returns => [CandidateMap]
   api_method :quickvote_candidate_ids_to_names, :expects => [:string,[:int]], :returns => [[:string]]
+  api_method :get_quickvote_votes, :expects => [:string], :returns => [ [VoteInfo] ]
+  api_method :list_quickvotes, :expects => [], :returns => [[ElectionStruct]]
+  api_method :get_quickvote, :expects => [:string], :returns => [ElectionStruct]
+  api_method :create_quickvote, :expects => [ElectionStruct], :returns => [:string]
 end
 
 
index bbd5cd79f9f4934d0e9f878046e8f88851a41155..8b617da9c19e163db72d3b84b362840d14a370c4 100644 (file)
@@ -82,6 +82,7 @@ class GraphController < ApplicationController
     #pref_tally = make_preference_tally(@election)
     
     #@borda_result = BordaVote.new(pref_tally).result
+    @election.results unless @election.borda_result
     data, labels = get_borda_points(@election.borda_result)
     
     graph = GruffGraff.new( :graph_type => Gruff::Bar,
@@ -169,7 +170,8 @@ class GraphController < ApplicationController
     
     # Now I need to create an array with all the times votes were made
     election.votes.each do |vote|
-        voter_days << Date.parse(vote.time.to_s)
+      next unless vote.time
+      voter_days << Date.parse(vote.time.to_s)
     end
     voter_days.sort!
     
@@ -215,6 +217,7 @@ class GraphController < ApplicationController
     # Will build a graph over time, as each successive interval will have more
     # vote objects  
     election.votes.each do |vote|
+      next unless vote.time
       buckets.keys.sort.each do |inter|
         if vote.time < inter
           buckets[inter] << vote
index 83a6cc5fc659e5bcfabcc75a1d6e31baa7af5474..e327ed6a17a55ed967e8f24120299554bc640794 100644 (file)
@@ -15,7 +15,7 @@ class QuickvoteController < ApplicationController
      
       # store the candidate grabbed through ajax and stored in flash
       @quickvote.candidatelist = flash[:candlist]
-
+      @quickvote.description=CGI.escapeHTML(@quickvote.description)
       # try to save, if it fails, show the page again (the flash should
       # still be intact
       if @quickvote.save
@@ -34,11 +34,13 @@ class QuickvoteController < ApplicationController
   end
 
   def add_candidate
-    candidate_name = params[:ajax][:newcandidate]
-    if flash.has_key?(:candlist) and flash[:candlist].instance_of?(Array) 
-      flash[:candlist] << candidate_name
-    else
-      flash[:candlist] = [ candidate_name ]
+    candidate_name = CGI.escapeHTML(params[:ajax][:newcandidate])
+    unless candidate_name.strip.empty?
+      if flash.has_key?(:candlist) and flash[:candlist].instance_of?(Array) 
+        flash[:candlist] << candidate_name unless flash[:candlist].index(candidate_name)
+     else
+       flash[:candlist] = [ candidate_name ]
+      end
     end
     flash.keep(:candlist)
     render_partial 'candidate_list'
@@ -135,7 +137,22 @@ class QuickvoteController < ApplicationController
     render :nothing => true
   end
                
-
+  def mapvoters
+    @map = GMap.new("map_div_id") 
+    @map.control_init(:large_map => true, :map_type => true) 
+    center=nil
+    QuickVote.ident_to_quickvote(params[:id]).voters.each do |voter|
+      next unless voter.ipaddress
+      location = GeoKit::Geocoders::IpGeocoder.geocode(voter.ipaddress)
+      next unless location.lng and location.lat
+      unless center
+        center=[location.lat,location.lng]
+        @map.center_zoom_init(center,4)
+      end
+      marker = GMarker.new([location.lat,location.lng], :title => "Voter", :info_window => (voter.ipaddress or "unknown")+"   "+voter.vote.votestring)
+      @map.overlay_init(marker)
+    end
+  end
   ###############################################################
   # the following method pertains to displaying the results of a
   # quickvote
index c427b981d78120d54ee429f8f2ee9280f9f310a9..ad727170f036c2b60019ffe6d7a63759d6ddfd8f 100644 (file)
@@ -1,6 +1,7 @@
 class QuickVote < Election
   after_validation :create_candidates
   validates_uniqueness_of :name
+  validates_presence_of :name
   attr_accessor :raw_candidates
   attr_accessor :reviewed
   attr_accessor :plurality_result
@@ -10,12 +11,19 @@ class QuickVote < Election
   attr_accessor :borda_result
 
   def validate
-    if @raw_candidates.length < 2
-      errors.add("You must list at least two candidates.")
+    if not @raw_candidates or @raw_candidates.length < 2
+        errors.add(nil, "You must list at least two candidates.")
     end
-
+    
     if name =~ /[^A-Za-z0-9]/
-      errors.add("The name must only include numbers and letters.")
+      errors.add(:name, "must only include numbers and letters.")
+    end
+    if name =~ /^[0-9]+$/
+      errors.add(:name, "must not be a number")
+    end
+    
+    if name =~ /^(create|index|confirm|change|results)$/
+      errors.add(:name, " is a reserved word.")
     end
   end
   
@@ -32,7 +40,7 @@ class QuickVote < Election
   end
 
   def name
-    read_attribute( :name ).downcase()
+    read_attribute( :name ).downcase() if read_attribute( :name )
   end
 
   def reviewed?
@@ -40,6 +48,7 @@ class QuickVote < Election
   end
 
   def create_candidates
+    return unless errors.empty?
     @raw_candidates.each do |name|
       candidate = Candidate.new({:name => name})
       self.candidates << candidate
@@ -75,6 +84,7 @@ class QuickVote < Election
 
   ### Convert a shortname or id into a QuickVote
   def self.ident_to_quickvote(ident)
+    return nil unless ident
     if ident.match(/^\d+$/)
       quickvote = QuickVote.find(ident)
     else
index add5ab9c2bb08f951ce315c852f6f9ba9bf2a140..9e276ef502e89b0a41acde7c7f9ef25412cb3342 100644 (file)
@@ -5,6 +5,12 @@ class SelectricityService < ActionWebService::Base
   def cast_quickvote(election_name, voter_id, vote_list)
     election = QuickVote.ident_to_quickvote election_name
     if election
+      candidates=election.candidates.collect { |c| c.id }
+      vote_list[0].each do |vote|
+        raise ArgumentError.new "Invalid Candidate ID #{vote}" unless candidates.index(vote)
+      end
+      raise ArgumentError.new "You must rank all candidates" unless candidates.length <= vote_list[0].length
+      raise ArgumentError.new "Please rank each candidate only once" if vote_list[0].uniq!
       voter = QuickVoter.new
       voter.election = election
       voter.ipaddress = "XMLRPC Request"
@@ -15,6 +21,8 @@ class SelectricityService < ActionWebService::Base
       voter.save!
       voter.vote.confirm!
       voter.save!
+    else
+      raise ArgumentError.new "Cannot find election #{election_name}"
     end
   end
   def quickvote_candidate_ids_to_names(shortname, id_list)
@@ -65,5 +73,36 @@ class SelectricityService < ActionWebService::Base
     result.candidate_names=candidates.values
     result
   end
-    
+  def get_quickvote_votes(shortname)
+    qv=QuickVote.ident_to_quickvote(shortname)
+    votes=Array.new
+    unless qv
+      return result
+    end
+    qv.votes.each  do |vote|
+      votes << VoteInfo.new(:voter_id => vote.voter.id, :voter_ipaddress => vote.voter.ipaddress, :vote_time => vote.time.to_i, :vote => vote.votes)
+    end
+    return votes
+  end
+  def list_quickvotes()
+    all=Array.new
+    QuickVote.find_all.each do |election|
+      all << get_quickvote(election.name)
+    end
+    return all
+  end
+  def get_quickvote(shortname)
+    return ElectionStruct.new unless election=QuickVote.ident_to_quickvote(shortname)
+    return ElectionStruct.new (:id => election.id, :name => election.name, :description => election.description, :candidate_ids => election.candidates.collect {|c| c.id }, :candidate_names => election.candidates.collect {|c| c.name } )
+  end
+  def create_quickvote(election)
+    qv=QuickVote.new(:name => election.name, :description => election.description)
+    qv.candidatelist=election.candidate_names
+    if qv.save
+      return ""
+    else
+      return "Saving quickvote FAILED:"+qv.errors.inspect
+    end
+  end
+
 end
diff --git a/app/views/quickvote/_defeats_list.rhtml b/app/views/quickvote/_defeats_list.rhtml
new file mode 100644 (file)
index 0000000..248c294
--- /dev/null
@@ -0,0 +1,15 @@
+<% victories, tied =@election.condorcet_result.list_defeats -%>
+<%candidates = @election.candidates.sort.collect {|candidate| candidate.id}%>
+<% names = Hash.new -%>
+<% candidates.each do |candidate| -%>
+       <%names[candidate] = Candidate.find(candidate).name -%>
+<% end -%>
+
+<% victories.each do |victory| -%>
+<%= names[victory[0]] %> beat <%= names[victory[1]] %> by <%= victory[2]%> 
+votes.<br />
+<% end -%>
+
+<% tied.each do |tie| -%>
+<%= names[tie[0]]%> tied with <%= names[tie[1]]%><br />
+<% end -%>
index dfcb6cca9ea31438ad480ce56b8814761743b1b8..32f5de4bc81254afef3a36fbae12a82ab331d21b 100644 (file)
@@ -1,13 +1,17 @@
-<% candidates = @election.candidates.sort.collect {|candidate| candidate.id} -%>
+<% candidates = @election.candidates.sort.collect {|candidate| candidate.id}-%>
+<% names = Hash.new -%>
+<% candidates.each do |candidate| -%>
+       <%names[candidate] = Candidate.find(candidate).name -%>
+<% end -%>
 <table class="voterbox">
   <tr>
        <td> </td>
        <% candidates.each do |candidate| -%>
-         <th><%= candidate -%></th>
+         <th><%= names[candidate] -%></th>
        <% end -%>
 <% candidates.each do |winner| -%>
   <tr>
-       <th><%= winner %></th>
+       <th><%= names[winner] %></th>
   <% candidates.each do |loser| -%> 
     <% if winner == loser -%>
       <td> -- </td>
@@ -16,4 +20,5 @@
     <% end -%>
   <% end -%>
  </tr>
-<%end -%>
\ No newline at end of file
+<% end -%>
+
diff --git a/app/views/quickvote/mapvoters.rhtml b/app/views/quickvote/mapvoters.rhtml
new file mode 100644 (file)
index 0000000..8f94cd0
--- /dev/null
@@ -0,0 +1,3 @@
+<%= GMap.header %>
+<%= @map.to_html %>  
+<%= @map.div(:width => 800, :height => 400) %>  
index 3b3a54d9ef68e11128b22891956d9bdb05cdf9fd..0cbd6d00e5f84b6091d19ca1bb55848518aa5c26 100644 (file)
@@ -1,4 +1,4 @@
-<%require 'IPAddr' %>
+<%require 'whois/whois' %>
 <h1>Results</h1>
 
 <% if @election.shortdesc %>
@@ -144,22 +144,30 @@ by several other names.</p>
 
 <div class="clearbox"></div>
 
-<h2>Voters</h2>
+<h2>Voters <%= link_to "[Stalk Voters]", :controller => "quickvote", :action => "mapvoters", :id => @election.id %></h2>
 <table class="voterbox">
 <tr>
-<th>IP Address</th>
-<th>DNS/Host</th>
+<th>IP/Host</th>
+<th>Origin</th>
 <th>Vote</th>
 </tr>
 <% for voter in @election.voters %>
   <% next unless voter.voted? %>
   <tr>
-  <td><%= voter.ipaddress %></td>
-  <td><% begin %>
-      <%= `host #{IPAddr.new(voter.ipaddress).to_s}`.sub(/^.*pointer (.*)\.$/, '\1') %>
+    <td><% begin %>
+        <% raise ArgumentError.new, "Local Server" if voter.ipaddress == "127.0.0.1" %>
+        <% raise ArgumentError.new, "XML-RPC Voter" if voter.ipaddress == "XMLRPC Request" %>
+        <% w= Whois::Whois.new(IPAddr.new(voter.ipaddress).to_s,true)%>
+        <%=(w.host == nil or w.host.empty?) ? voter.ipaddress : w.host%>
+      </td>
+      <td>
+        <%w.search_whois%>
+        <%= (w.all.grep(/^(OrgName|org-name)/)[0] or "").sub(/^(OrgName|org-name)\:/,'').strip -%> - <%=  (w.all.grep(/^(NetName|netname)/)[0] or "").sub(/^(NetName|netname)\:/,'').strip %>
     
     <% rescue ArgumentError => err %>
-      <%= voter.ipaddress %>
+      <%= err %>
+    </td>
+    <td><%= err%>
     <% end %>
     </td>
   <td><%= voter.vote.votestring %></td>
@@ -167,6 +175,7 @@ by several other names.</p>
 <% end %>
 </table>
 
+<%= render :partial => 'defeats_list' %>
 <%= render :partial => 'pref_table' %>
 
 <%= image_tag( graph_url( :action => 'votes_per_day', :id => @election ) ) %><br />
index 77d020c81efd5ccc126a529c6855f5161d05468b..ba927343d1dc89aca7a36e7ee2b63e0eaadb4623 100644 (file)
@@ -88,3 +88,53 @@ end
 ActionMailer::Base.delivery_method = :sendmail
 ActionMailer::Base.default_charset = "utf-8"
 
+# These defaults are used in GeoKit::Mappable.distance_to and in acts_as_mappable
+GeoKit::default_units = :miles
+GeoKit::default_formula = :sphere
+
+# This is the timeout value in seconds to be used for calls to the geocoder web
+# services.  For no timeout at all, comment out the setting.  The timeout unit
+# is in seconds. 
+GeoKit::Geocoders::timeout = 3
+
+# These settings are used if web service calls must be routed through a proxy.
+# These setting can be nil if not needed, otherwise, addr and port must be 
+# filled in at a minimum.  If the proxy requires authentication, the username
+# and password can be provided as well.
+GeoKit::Geocoders::proxy_addr = nil
+GeoKit::Geocoders::proxy_port = nil
+GeoKit::Geocoders::proxy_user = nil
+GeoKit::Geocoders::proxy_pass = nil
+
+# This is your yahoo application key for the Yahoo Geocoder.
+# See http://developer.yahoo.com/faq/index.html#appid
+# and http://developer.yahoo.com/maps/rest/V1/geocode.html
+GeoKit::Geocoders::yahoo = 'REPLACE_WITH_YOUR_YAHOO_KEY'
+    
+# This is your Google Maps geocoder key. 
+# See http://www.google.com/apis/maps/signup.html
+# and http://www.google.com/apis/maps/documentation/#Geocoding_Examples
+GeoKit::Geocoders::google = 'REPLACE_WITH_YOUR_GOOGLE_KEY'
+    
+# This is your username and password for geocoder.us.
+# To use the free service, the value can be set to nil or false.  For 
+# usage tied to an account, the value should be set to username:password.
+# See http://geocoder.us
+# and http://geocoder.us/user/signup
+GeoKit::Geocoders::geocoder_us = false 
+
+# This is your authorization key for geocoder.ca.
+# To use the free service, the value can be set to nil or false.  For 
+# usage tied to an account, set the value to the key obtained from
+# Geocoder.ca.
+# See http://geocoder.ca
+# and http://geocoder.ca/?register=1
+GeoKit::Geocoders::geocoder_ca = false
+
+# This is the order in which the geocoders are called in a failover scenario
+# If you only want to use a single geocoder, put a single symbol in the array.
+# Valid symbols are :google, :yahoo, :us, and :ca.
+# Be aware that there are Terms of Use restrictions on how you can use the 
+# various geocoders.  Make sure you read up on relevant Terms of Use for each
+# geocoder you are going to use.
+GeoKit::Geocoders::provider_order = [:google,:us]
diff --git a/config/gmaps_api_key.yml b/config/gmaps_api_key.yml
new file mode 100644 (file)
index 0000000..b1641f5
--- /dev/null
@@ -0,0 +1,13 @@
+#Fill here the Google Maps API keys for your application\r
+#In this sample:\r
+#For development and test, we have only one possible host (localhost:3000), so there is only a single key associated with the mode.\r
+#In production, the app can be accessed through 2 different hosts: thepochisuperstarmegashow.com and exmaple.com. There then needs a 2-key hash. If you deployed to one host, only the API key would be needed (as in development and test).\r
+\r
+development:\r
+ ABQIAAAA479zRK1hoNqMcKLTMuBcTRScPKE_l4RVNk_lv74wWGSk9YyVlRQ16fPZdTl-PBiKfGdEjSpSL8gVtA\r
+test:\r
+ ABQIAAAAzMUFFnT9uH0xq39J0Y4kbhTJQa0g3IQ9GZqIMmInSLzwtGDKaBR6j135zrztfTGVOm2QlWnkaidDIQ\r
+\r
+production:\r
+ thepochisuperstarmegashow.com: ABQIAAAAzMUFFnT9uH0Sfg76Y4kbhTJQa0g3IQ9GZqIMmInSLzwtGDmlRT6e90j135zat56yhJKQlWnkaidDIQ\r
+ example.com: ABQIAAAAzMUFFnT9uH0Sfg98Y4kbhGFJQa0g3IQ9GZqIMmInSLrthJKGDmlRT98f4j135zat56yjRKQlWnkmod3TB\r
index b86be118134b706e923f7971fe30264943053679..45d7b416a2eb0a25c752c23b3ddfe74920236c8f 100644 (file)
@@ -2,65 +2,70 @@
 # migrations feature of ActiveRecord to incrementally modify your database, and
 # then regenerate this schema definition.
 
-ActiveRecord::Schema.define(:version => 0) do
+ActiveRecord::Schema.define() do
 
   create_table "candidates", :force => true do |t|
-    t.column "election_id", :integer, :default => 0, :null => false
-    t.column "name", :string, :limit => 100, :default => "", :null => false
-    t.column "picture", :binary, :default => "", :null => false
+    t.column "election_id",      :integer,                                :null => false
+    t.column "name",             :string,  :limit => 100, :default => "", :null => false
+    t.column "description",      :text
+    t.column "picture_filename", :string,  :limit => 200
+    t.column "picture_data",     :binary
+    t.column "picture_type",     :string,  :limit => 100
   end
 
   create_table "elections", :force => true do |t|
-    t.column "name", :string, :limit => 100, :default => "", :null => false
-    t.column "description", :text, :default => "", :null => false
-    t.column "anonymous", :integer, :limit => 4, :default => 0, :null => false
-    t.column "startdate", :datetime, :null => false
-    t.column "enddate", :datetime
+    t.column "name",        :string,   :limit => 100, :default => "", :null => false
+    t.column "description", :text,                    :default => "", :null => false
+    t.column "anonymous",   :integer,  :limit => 4,   :default => 1,  :null => false
+    t.column "startdate",   :datetime
+    t.column "enddate",     :datetime,                                :null => false
+    t.column "active",      :integer,  :limit => 4,   :default => 0,  :null => false
+    t.column "user_id",     :integer
+    t.column "type",        :string,   :limit => 100, :default => "", :null => false
   end
 
+  add_index "elections", ["user_id"], :name => "fk_user_election"
+
   create_table "rankings", :force => true do |t|
-    t.column "vote_id", :integer
+    t.column "vote_id",      :integer
     t.column "candidate_id", :integer
-    t.column "rank", :integer
+    t.column "rank",         :integer
   end
 
   create_table "tokens", :force => true do |t|
-    t.column "token", :string, :limit => 100, :default => "", :null => false
-    t.column "vote_id", :integer, :default => 0, :null => false
+    t.column "token",   :string,  :limit => 100, :default => "", :null => false
+    t.column "vote_id", :integer,                                :null => false
   end
 
   add_index "tokens", ["vote_id"], :name => "fk_vote_token"
 
   create_table "users", :force => true do |t|
-    t.column "login", :string, :limit => 80, :default => "", :null => false
-    t.column "salted_password", :string, :limit => 40, :default => "", :null => false
-    t.column "email", :string, :limit => 60, :default => "", :null => false
-    t.column "firstname", :string, :limit => 40
-    t.column "lastname", :string, :limit => 40
-    t.column "salt", :string, :limit => 40, :default => "", :null => false
-    t.column "verified", :integer, :default => 0
-    t.column "role", :string, :limit => 40
-    t.column "security_token", :string, :limit => 40
-    t.column "token_expiry", :datetime
-    t.column "created_at", :datetime
-    t.column "updated_at", :datetime
-    t.column "logged_in_at", :datetime
-    t.column "deleted", :integer, :default => 0
-    t.column "delete_after", :datetime
+    t.column "login",                     :text
+    t.column "ip",                        :text,                   :default => "", :null => false
+    t.column "email",                     :text
+    t.column "crypted_password",          :string,   :limit => 40
+    t.column "salt",                      :string,   :limit => 40
+    t.column "created_at",                :datetime
+    t.column "updated_at",                :datetime
+    t.column "remember_token",            :text
+    t.column "remember_token_expires_at", :datetime
   end
 
   create_table "voters", :force => true do |t|
-    t.column "email", :string, :limit => 100, :default => "", :null => false
-    t.column "password", :string, :limit => 100, :default => "", :null => false
-    t.column "contacted", :integer, :limit => 4, :default => 0, :null => false
-    t.column "election_id", :integer, :default => 0, :null => false
+    t.column "email",       :string,  :limit => 100
+    t.column "password",    :string,  :limit => 100
+    t.column "contacted",   :integer, :limit => 4,   :default => 0, :null => false
+    t.column "election_id", :integer,                               :null => false
+    t.column "session_id",  :string,  :limit => 32
+    t.column "ipaddress",   :string,  :limit => 32
   end
 
   add_index "voters", ["election_id"], :name => "fk_election_voter"
 
   create_table "votes", :force => true do |t|
-    t.column "voter_id", :integer
-    t.column "confirmed", :integer, :limit => 4, :default => 0, :null => false
+    t.column "voter_id",  :integer
+    t.column "confirmed", :integer,  :limit => 4, :default => 0, :null => false
+    t.column "time",      :datetime
   end
 
   add_index "votes", ["voter_id"], :name => "fk_vote_voter"
index bf4e548da45bcbb6d9c3ebfa57269d065bf09b6a..f86e59d1295cdc876b9d9f380892452c5f3bab04 100644 (file)
@@ -153,14 +153,37 @@ class CondorcetResult < ElectionResult
     super(voteobj)
     @matrix = voteobj.votes
   end
-
+  
+  def victories_and_ties
+    victors = Array.new
+    ties = Array.new
+    candidates = @matrix.keys.sort
+    
+    candidates.each do |candidate|
+      candidates.each do |challenger|
+        next if candidate == challenger
+        diff = @matrix[candidate][challenger] - @matrix[challenger][candidate]
+        if diff > 0 
+          victors << [candidate, challenger, diff]
+        elsif diff == 0 && ties.include?([challenger, candidate]) == false
+          ties << [candidate, challenger] 
+        end
+      end
+    end
+    
+    victories = victors.sort {|a,b| b[2] <=> a[2]}
+    
+    return victories, ties    
+  end
+        
   protected
   def defeats(candidates=nil, votes=nil)
-    candidates = @election.candidates unless candidates
-    votes = @election.votes unless votes
+    candidates ||= @election.candidates || []
+    # we're assumign that if there are candidates, there must be at
+    # least one vote for them
+    votes ||= @election.votes 
 
     defeats = Array.new
-    candidates = [candidates] unless candidates.class == Array
     candidates.each do |candidate|
       candidates.each do |challenger|
         next if candidate == challenger
@@ -182,14 +205,15 @@ class PureCondorcetResult < CondorcetResult
   end
 
   protected
-
+  
   def condorcet
     votes = @election.votes
     candidates = @election.candidates
-    unless votes.length>0 and candidates.length>0
-      @winners=[]
-      return @winners
+
+    unless votes.length > 0 and candidates.length > 0
+      return @winners=[]
     end
+
     victors = Hash.new
     candidates.each do |candidate|
       victors[candidate] = Array.new
@@ -219,14 +243,13 @@ class CloneproofSSDResult < CondorcetResult
   def initialize(voteobj=nil)
     super(voteobj)
     @winners = self.cpssd()
-    @winners.delete nil
   end
 
   protected
 
   def cpssd
     votes = @election.votes
-    candidates = *@election.candidates
+    candidates = @election.candidates.dup
 
     def in_schwartz_set?(candidate, candidates, transitive_defeats)
       candidates.each do |challenger|
index ffd31c846e56400e9df945361d5a4c11ebb9df9d..5a5824341a57c1f4c9f6aef7ec14ed41f40dc693 100644 (file)
@@ -45,7 +45,7 @@ class ElectionVote
           if self.verify_vote(vote)
             self.tally_vote(vote)
           else
-            raise InvalidVoteError.new ("Invalid vote object", vote)
+            raise InvalidVoteError.new("Invalid vote object", vote)
           end
         end
       else
diff --git a/lib/whois/data/ipv4.yaml b/lib/whois/data/ipv4.yaml
new file mode 100644 (file)
index 0000000..13e2724
--- /dev/null
@@ -0,0 +1,201 @@
+--- 
+222.96.0.0/12: Nicor
+218.160.0.0/12: Twnic
+209.94.192.0/19: Lacnic
+155.232.0.0/13: Afrinic
+164.146.0.0/15: Afrinic
+202.16.0.0/14: Nicad
+218.216.0.0/13: Nicad
+202.0.0.0/7: Apnic
+192.71.0.0/16: Ripe
+61.112.0.0/12: Nicad
+141.64.0.0/12: Ripe
+43.0.0.0/8: V6nic
+211.112.0.0/13: Nicor
+211.20.0.0/15: Twnic
+202.224.0.0/11: Nicad
+151.100.0.0/16: Ripe
+160.124.0.0/16: Afrinic
+214.0.0.0/7: Arin
+210.242.0.0/15: Twnic
+61.192.0.0/12: Nicad
+163.156.0.0/14: Ripe
+171.16.0.0/12: Ripe
+200.128.0.0/9: Nicbr
+219.96.0.0/11: Nicad
+149.240.0.0/13: Ripe
+164.0.0.0/11: Ripe
+151.0.0.0/10: Ripe
+192.72.253.0/24: Arin
+221.144.0.0/12: Nicor
+203.66.0.0/16: Twnic
+202.11.0.0/16: Nicad
+0.0.0.0/1: Arin
+149.248.0.0/14: Ripe
+59.0.0.0/11: Nicor
+41.0.0.0/8: Afrinic
+149.204.0.0/16: Ripe
+218.232.0.0/13: Nicor
+218.224.0.0/13: Nicad
+210.248.0.0/13: Nicad
+210.204.0.0/14: Nicor
+116.0.0.0/6: Apnic
+202.24.0.0/15: Nicad
+200.0.0.0/7: Lacnic
+200.17.0.0/16: Nicbr
+125.128.0.0/11: Nicor
+150.254.0.0/16: Ripe
+164.32.0.0/13: Ripe
+211.192.0.0/10: Nicor
+203.69.0.0/16: Twnic
+192.118.0.0/16: Ripe
+202.39.128.0/17: Twnic
+220.149.0.0/16: Nicor
+212.0.0.0/7: Ripe
+211.128.0.0/13: Nicad
+211.120.0.0/13: Nicad
+210.71.128.0/16: Twnic
+203.140.0.0/15: Nicad
+96.0.0.0/3: 
+196.0.0.0/6: Arin
+192.164.0.0/14: Ripe
+165.144.0.0/14: Afrinic
+155.240.0.0/16: Afrinic
+218.36.0.0/14: Nicor
+213.154.64.0/19: Afrinic
+210.240.0.0/16: Twnic
+210.128.0.0/11: Nicad
+210.59.128.0/17: Twnic
+223.0.0.0/8: 
+219.248.0.0/13: Nicor
+211.72.0.0/16: Twnic
+203.74.0.0/15: Twnic
+203.0.0.0/10: Apnic
+196.0.0.0/8: Afrinic
+149.202.0.0/15: Ripe
+210.241.224.0/19: Twnic
+96.0.0.0/6: Arin
+171.32.0.0/15: Ripe
+220.64.0.0/11: Nicor
+219.240.0.0/15: Nicor
+210.0.0.0/7: Apnic
+211.16.0.0/14: Nicad
+210.92.0.0/14: Nicor
+202.32.0.0/14: Nicad
+220.103.0.0/16: Nicor
+211.75.0.0/16: Twnic
+202.20.128.0/17: Nicor
+208.0.0.0/7: Arin
+202.48.0.0/16: Nicad
+163.200.0.0/14: Afrinic
+61.208.0.0/13: Nicad
+139.24.0.0/14: Ripe
+62.0.0.0/8: Ripe
+222.232.0.0/13: Nicor
+61.84.0.0/15: Nicor
+194.0.0.0/7: Ripe
+126.0.0.0/8: Apnic
+150.183.0.0/16: Nicor
+141.80.0.0/14: Ripe
+163.195.0.0/16: Afrinic
+160.115.0.0/16: Afrinic
+211.32.0.0/11: Nicor
+192.72.0.0/16: Apnic
+164.40.0.0/16: Ripe
+210.61.0.0/16: Twnic
+160.120.0.0/14: Afrinic
+221.160.0.0/13: Nicor
+160.44.0.0/14: Ripe
+151.96.0.0/14: Ripe
+220.0.0.0/6: Apnic
+222.112.0.0/13: Nicor
+220.104.0.0/13: Nicad
+203.136.0.0/14: Nicad
+149.208.0.0/12: Ripe
+141.0.0.0/10: Ripe
+192.116.0.0/15: Ripe
+192.106.0.0/16: Ripe
+202.30.0.0/15: Nicor
+60.0.0.0/7: Apnic
+200.18.0.0/15: Nicbr
+160.220.0.0/16: Ripe
+124.0.0.0/7: Apnic
+58.0.0.0/7: Apnic
+218.0.0.0/7: Apnic
+204.0.0.0/14: Ginntt
+193.0.0.0/8: Ripe
+200.20.0.0/16: Nicbr
+192.162.0.0/16: Ripe
+202.15.0.0/16: Nicad
+163.196.0.0/14: Afrinic
+222.122.0.0/16: Nicor
+221.138.0.0/13: Nicor
+121.128.0.0/10: Nicor
+211.0.0.0/12: Nicad
+210.241.0.0/15: Twnic
+210.216.0.0/13: Nicor
+61.72.0.0/13: Nicor
+192.114.0.0/15: Ripe
+80.0.0.0/5: Ripe
+210.188.0.0/14: Nicad
+210.178.0.0/15: Nicor
+210.90.0.0/15: Nicor
+203.180.0.0/14: Nicad
+202.208.0.0/12: Nicad
+146.48.0.0/16: Ripe
+163.160.0.0/12: Ripe
+192.72.254.0/24: Arin
+213.154.32.0/19: Afrinic
+211.168.0.0/13: Nicor
+211.22.0.0/16: Twnic
+210.180.0.0/14: Nicor
+139.28.0.0/15: Ripe
+165.148.0.0/15: Afrinic
+222.120.0.0/15: Nicor
+220.96.0.0/14: Nicad
+216.0.0.0/8: Arin
+210.96.0.0/11: Nicor
+192.0.0.0/8: Arin
+133.0.0.0/8: Nicad
+149.206.0.0/15: Ripe
+160.116.0.0/14: Afrinic
+218.144.0.0/12: Nicor
+217.0.0.0/8: Ripe
+210.224.0.0/12: Nicad
+210.160.0.0/12: Nicad
+210.65.0.0/16: Twnic
+160.216.0.0/14: Ripe
+92.0.0.0/7: Ripe
+164.148.0.0/14: Afrinic
+189.0.0.0/8: Lacnic
+202.23.0.0/16: Nicad
+145.0.0.0/8: Ripe
+204.0.0.0/6: Arin
+165.143.0.0/16: Afrinic
+169.208.0.0/12: Apnic
+211.104.0.0/13: Nicor
+210.196.0.0/14: Nicad
+24.132.0.0/14: Ripe
+149.224.0.0/12: Ripe
+202.26.0.0/16: Nicad
+218.48.0.0/13: Nicor
+218.40.0.0/13: Nicad
+211.176.0.0/12: Nicor
+203.178.0.0/15: Nicad
+139.20.0.0/14: Ripe
+151.64.0.0/11: Ripe
+190.0.0.0/8: Lacnic
+200.96.0.0/13: Nicbr
+61.80.0.0/14: Nicor
+164.128.0.0/12: Ripe
+160.48.0.0/12: Ripe
+128.0.0.0/2: Arin
+141.84.0.0/15: Ripe
+210.62.252.0/22: Twnic
+203.224.0.0/11: Nicor
+77.0.0.0/8: Ripe
+120.0.0.0/6: Apnic
+88.0.0.0/6: Ripe
+188.0.0.0/8: Ripe
+202.13.0.0/16: Nicad
+78.0.0.0/7: Ripe
diff --git a/lib/whois/data/ipv6.yaml b/lib/whois/data/ipv6.yaml
new file mode 100644 (file)
index 0000000..1e3e31c
--- /dev/null
@@ -0,0 +1,33 @@
+--- 
+2001:4A00::/23: Ripe
+2001:4600::/23: Ripe
+2001:4200::/23: Afrinic
+2001:0200::/23: Apnic
+2400:0000::/12: Apnic
+2001:1C00::/22: Ripe
+2001:8000::/18: Apnic
+2001:1800::/23: Arin
+2001:0600::/23: Ripe
+3FFE:0000::/16: Ipv6Bone
+2001:5000::/20: Ripe
+2001:1A00::/23: Ripe
+2001:0C00::/22: Apnic
+2001:0800::/22: Ripe
+2800:0000::/12: Lacnic
+2620:0000::/23: Arin
+2001:0400::/23: Arin
+2C00:0000::/12: Afrinic
+2610:0000::/23: Arin
+2003:0000::/18: Ripe
+2001:4000::/23: Ripe
+2600:0000::/12: Arin
+2002:0000::/16: Ipv6ToIpv4
+2001:2000::/19: Ripe
+2001:0000::/32: Teredo
+2A00:0000::/12: Ripe
+2001:4C00::/22: Ripe
+2400:0000::/20: Kornet
+2001:4800::/23: Arin
+2001:4400::/23: Apnic
+2001:1400::/22: Ripe
+2001:1000::/22: Lacnic
diff --git a/lib/whois/server/server.rb b/lib/whois/server/server.rb
new file mode 100644 (file)
index 0000000..43a6c86
--- /dev/null
@@ -0,0 +1,131 @@
+module Server
+
+    # Define if the module has or not the Class in this module
+    def self.class_exist? str
+        begin
+            self.class_eval str.to_s
+            return true
+        rescue NameError
+            return false
+        end
+    end
+
+    # Class For define a model of Server
+    class Server
+        attr_reader :server
+    end
+    
+    # Class for the server Afrinic
+    class Afrinic < Server
+    
+        def initialize
+            @server = 'whois.afrinic.net'
+        end
+    end
+
+    # Class for the Server Apnic
+    class Apnic < Server
+
+        def initialize
+            @server = 'whois.apnic.net'
+        end
+    end
+
+    # Class for the Server Ripe
+    class Ripe < Server
+        def initialize
+            @server = 'whois.ripe.net'
+        end
+    end
+
+    # Class for the Server Arin
+    class Arin < Server
+        def initialize
+            @server = 'whois.arin.net'
+        end
+    end
+
+    # Class for the Server Lacnic
+    class Lacnic < Server
+        def initialize
+            @server = 'whois.lacnic.net'
+        end
+    end
+
+    # Class for Server whois.nic.or.kr
+    class Nicor < Server
+        def initialize
+            @server = 'whois.nic.or.kr'
+        end
+    end
+    
+    # Class for Server whois.nic.ad.jp
+    class Nicad < Server
+        def initialize
+            @server = 'whois.nic.ad.jp'
+        end
+    end
+
+    # Class for Server whois.nic.br
+    class Nicbr < Server
+        def initialize
+            @server = 'whois.nic.br'
+        end
+    end
+
+    # Class for the teredo RFC 4773 
+    class Teredo < Server
+        def initialize
+            @server = nil
+        end
+    end
+
+    # Class for 6To4 RFC 3056
+    class Ipv6ToIpv4 < Server
+        def initialize
+             @server = nil
+         end
+    end
+
+    # Class for server whois.kornet.net
+    class Kornet < Server
+        def initialize
+             @server = 'whois.kornet.net'
+         end
+    end
+
+    # Class for server whois.v6nic.net
+    class V6nic < Server
+        def initialize
+             @server = 'whois.v6nic.net'
+         end
+    end
+
+    # Class for server whois.twnic.net
+    class Twnic < Server
+        def initialize
+            @server = 'whois.twnic.net'
+        end
+    end
+
+    # Class for server whois.verio.net
+    class Verio < Server
+        def initialize
+            @server = 'whois.verio.net'
+        end
+    end
+
+    # Class for server whois.6bone.net
+    class Ipv6Bone < Server
+        def initialize
+            @server = 'whois.6bone.net'
+        end
+    end
+
+    class Ginntt < Server
+      def initialize
+        @server = 'rwhois.gin.ntt.net'
+      end
+    end
+        
+end
diff --git a/lib/whois/whois.rb b/lib/whois/whois.rb
new file mode 100755 (executable)
index 0000000..9b07aef
--- /dev/null
@@ -0,0 +1,158 @@
+#!/usr/bin/ruby -w
+
+require 'socket'
+require 'resolv'
+require 'ipaddr'
+require 'yaml'
+require File.dirname(__FILE__) + '/server/server'
+
+# Module for manage all Whois Class
+module Whois
+
+    # Base exception of Whois
+    class WhoisException < Exception
+    end
+
+    # Exception of Whois who made report a bug
+    class WhoisExceptionError < WhoisException
+        def initialize (i)
+            WhoisException.initialize('Report a bug with error #{i} to http://rubyforge.org/projects/whois/')
+        end
+    end
+
+    # Class to get all information about Host or IP with the Whois request
+    class Whois
+
+        Version = '0.4.0'
+
+        attr_reader :all
+        attr_reader :server
+        attr_reader :ip
+        attr_reader :host
+        attr_accessor :host_search
+
+        # Initialize with a request. The request must be an IPv4, or a host string
+        #
+        # The first params now is :
+        #  * a string which a Ipv4, Ipv6 or a host.
+        #  * A IPAddr instance
+        #
+        # A second param, host_search is optionnal. By default he is false.
+        # If this value is true, a resolv host is made for know the host to this IPv4
+        def initialize(request, host_search=false)
+            @host_search = host_search
+            @host = nil
+            if request.instance_of? IPAddr
+                if request.ipv4?
+                    @ip = request
+                    @server = server_ipv4
+                elsif request.ipv6?
+                    @ip = request
+                    @server = server_ipv6
+                else
+                    raise WhoisExceptionError.new(1)
+                end
+            elsif Resolv::IPv4::Regex =~ request
+                ipv4_init request
+                unless self.server
+                    raise WhoisException.new("no server found for this IPv4 : #{request}")
+                end
+            elsif Resolv::IPv6::Regex =~ request
+                ipv6_init request
+                unless self.server
+                    raise WhoisException.new("no server found for this Ipv6 : #{request}")
+                end
+            else
+                # Test if the request is an host or not
+                begin
+                    ip = Resolv.getaddress request
+                    @ip = IPAddr.new ip
+                    @server = server_ipv4
+                    @host = request
+                rescue Resolv::ResolvError
+                    raise WhoisException.new('host #{request} has no DNS result')
+                end
+            end
+            
+            search_host unless @host
+        end
+        
+        # Ask of whois server
+        def search_whois
+            s = TCPsocket.open(self.server.server, 43)
+            s.write("#{self.ip.to_s}\n")
+            ret = ''
+            while s.gets do ret += $_ end
+            s.close
+            @all = ret
+        end
+
+
+        # Search the host for this IPv4, if the value host_search is true, else host = nil
+        def search_host
+            begin
+                if @host_search
+                    @host = Resolv.getname self.ip.to_s
+                else
+                    @host = nil
+                end
+            rescue Resolv::ResolvError
+                @host = nil
+            end
+        end
+    
+    private
+    
+        # Init value for a ipv4 request
+        def ipv4_init (ip)
+            @ip = IPAddr.new ip
+            @server = server_ipv4
+        end
+
+        # Init value for a ipv6 request
+        def ipv6_init (ip)
+            @ip = IPAddr.new ip
+            @server = server_ipv6
+        end
+
+        # Return the Server with the hash of mask
+        def server_with_hash(ip_hash)
+          # Sort by mask of Ip Range
+          arr_tmp = ip_hash.sort{|b,c| c[0][/\/(.+)/, 1].to_i <=> b[0][/\/(.+)/, 1].to_i}
+          arr_tmp.each do |l|
+            ip_range = IPAddr.new l[0]
+            if ip_range.include? self.ip
+              return Object.instance_eval("Server::#{l[1]}.new")
+            end
+          end
+        end
+
+        # Define the server of Whois in IPC6 list of YAML
+        def server_ipv6
+          ipv6_list = YAML::load_file(File.dirname(__FILE__) + '/data/ipv6.yaml')
+          server = server_with_hash(ipv6_list)
+          unless server.kind_of? Server::Server
+            raise WhoisException.new("no server found for this IPv6 : #{self.ip}")
+          else
+            return server
+          end
+        end
+        
+        # Define the server of Whois in IPV4 list of YAML
+        def server_ipv4
+          ipv4_list = YAML::load_file(File.dirname(__FILE__) + '/data/ipv4.yaml')
+          server = server_with_hash(ipv4_list)
+          unless server.kind_of? Server::Server
+            raise WhoisException.new("no server found for this IPv4 : #{self.ip}")
+          else
+            return server
+          end
+        end
+    end
+end
+
+
+if $0 == __FILE__
+  w = Whois::Whois.new '218.14.221.147'
+  puts w.search_whois
+end
diff --git a/public/javascripts/clusterer.js b/public/javascripts/clusterer.js
new file mode 100644 (file)
index 0000000..eeb6dd9
--- /dev/null
@@ -0,0 +1,444 @@
+// Clusterer.js - marker clustering routines for Google Maps apps
+//
+// The original version of this code is available at:
+// http://www.acme.com/javascript/
+//
+// Copyright Â© 2005,2006 by Jef Poskanzer <jef@mail.acme.com>.
+// All rights reserved.
+//
+// Modified for inclusion into the YM4R library in accordance with the 
+// following license:
+//
+// Redistribution and use in source and binary forms, with or without
+// modification, are permitted provided that the following conditions
+// are met:
+// 1. Redistributions of source code must retain the above copyright
+//    notice, this list of conditions and the following disclaimer.
+// 2. Redistributions in binary form must reproduce the above copyright
+//    notice, this list of conditions and the following disclaimer in the
+//    documentation and/or other materials provided with the distribution.
+//
+// THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
+// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+// ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
+// FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+// DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+// OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+// HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+// LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+// OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+// SUCH DAMAGE.
+//
+// For commentary on this license please see http://www.acme.com/license.html
+
+
+// Constructor.
+Clusterer = function(markers,icon,maxVisibleMarkers,gridSize,minMarkersPerCluster,maxLinesPerInfoBox) {        
+    this.markers = [];
+    if(markers){
+       for(var i =0 ; i< markers.length ; i++){
+           this.addMarker(markers[i]);
+       }
+    }    
+    this.clusters = [];
+    this.timeout = null;
+        
+    this.maxVisibleMarkers = maxVisibleMarkers || 150;
+    this.gridSize = gridSize || 5;
+    this.minMarkersPerCluster = minMarkersPerCluster || 5;
+    this.maxLinesPerInfoBox = maxLinesPerInfoBox || 10;
+    
+    this.icon = icon || G_DEFAULT_ICON;
+}
+
+Clusterer.prototype = new GOverlay();
+
+Clusterer.prototype.initialize = function ( map ){
+    this.map = map;
+    this.currentZoomLevel = map.getZoom();
+   
+    GEvent.addListener( map, 'zoomend', Clusterer.makeCaller( Clusterer.display, this ) );
+    GEvent.addListener( map, 'moveend', Clusterer.makeCaller( Clusterer.display, this ) );
+    GEvent.addListener( map, 'infowindowclose', Clusterer.makeCaller( Clusterer.popDown, this ) );
+    //Set map for each marker
+    for(var i = 0,len = this.markers.length ; i < len ; i++){
+       this.markers[i].setMap( map );
+    }
+    this.displayLater();
+}
+
+Clusterer.prototype.remove = function(){
+     for ( var i = 0; i < this.markers.length; ++i ){
+        this.removeMarker(this.markers[i]);
+     }
+}
+
+Clusterer.prototype.copy = function(){
+    return new Clusterer(this.markers,this.icon,this.maxVisibleMarkers,this.gridSize,this.minMarkersPerCluster,this.maxLinesPerInfoBox);
+}
+
+Clusterer.prototype.redraw = function(force){
+    this.displayLater();
+}
+
+// Call this to change the cluster icon.
+Clusterer.prototype.setIcon = function ( icon ){
+    this.icon = icon;
+}
+
+// Call this to add a marker.
+Clusterer.prototype.addMarker = function ( marker, description){
+    marker.onMap = false;
+    this.markers.push( marker );
+    marker.description = marker.description || description;
+    if(this.map != null){
+       marker.setMap(this.map);
+       this.displayLater();
+    }
+};
+
+
+// Call this to remove a marker.
+Clusterer.prototype.removeMarker = function ( marker ){
+    for ( var i = 0; i < this.markers.length; ++i )
+       if ( this.markers[i] == marker ){
+           if ( marker.onMap )
+               this.map.removeOverlay( marker );
+           for ( var j = 0; j < this.clusters.length; ++j ){
+               var cluster = this.clusters[j];
+               if ( cluster != null ){
+                   for ( var k = 0; k < cluster.markers.length; ++k )
+                       if ( cluster.markers[k] == marker ){
+                           cluster.markers[k] = null;
+                           --cluster.markerCount;
+                           break;
+                       }
+                   if ( cluster.markerCount == 0 ){
+                       this.clearCluster( cluster );
+                       this.clusters[j] = null;
+                       }
+                   else if ( cluster == this.poppedUpCluster )
+                       Clusterer.rePop( this );
+                   }
+               }
+           this.markers[i] = null;
+           break;
+           }
+    this.displayLater();
+};
+
+Clusterer.prototype.displayLater = function (){
+    if ( this.timeout != null )
+       clearTimeout( this.timeout );
+    this.timeout = setTimeout( Clusterer.makeCaller( Clusterer.display, this ), 50 );
+};
+
+Clusterer.display = function ( clusterer ){
+    var i, j, marker, cluster, len, len2;
+
+    clearTimeout( clusterer.timeout );
+
+    var newZoomLevel = clusterer.map.getZoom();
+    if ( newZoomLevel != clusterer.currentZoomLevel ){
+       // When the zoom level changes, we have to remove all the clusters.
+       for ( i = 0 , len = clusterer.clusters.length; i < len; ++i ){
+           if ( clusterer.clusters[i] != null ){
+               clusterer.clearCluster( clusterer.clusters[i] );
+               clusterer.clusters[i] = null;
+           }
+       }
+       clusterer.clusters.length = 0;
+       clusterer.currentZoomLevel = newZoomLevel;
+    }
+
+    // Get the current bounds of the visible area.
+    var bounds = clusterer.map.getBounds();
+
+    // Expand the bounds a little, so things look smoother when scrolling
+    // by small amounts.
+    var sw = bounds.getSouthWest();
+    var ne = bounds.getNorthEast();
+    var dx = ne.lng() - sw.lng();
+    var dy = ne.lat() - sw.lat();
+    dx *= 0.10;
+    dy *= 0.10;
+    bounds = new GLatLngBounds(
+      new GLatLng( sw.lat() - dy, sw.lng() - dx ),
+      new GLatLng( ne.lat() + dy, ne.lng() + dx ) 
+    );
+
+    // Partition the markers into visible and non-visible lists.
+    var visibleMarkers = [];
+    var nonvisibleMarkers = [];
+    for ( i = 0, len = clusterer.markers.length ; i < len; ++i ){
+       marker = clusterer.markers[i];
+       if ( marker != null )
+           if ( bounds.contains( marker.getPoint() ) )
+               visibleMarkers.push( marker );
+           else
+               nonvisibleMarkers.push( marker );
+    }
+
+    // Take down the non-visible markers.
+    for ( i = 0, len = nonvisibleMarkers.length ; i < len; ++i ){
+       marker = nonvisibleMarkers[i];
+       if ( marker.onMap ){
+           clusterer.map.removeOverlay( marker );
+           marker.onMap = false;
+       }
+    }
+
+    // Take down the non-visible clusters.
+    for ( i = 0, len = clusterer.clusters.length ; i < len ; ++i ){
+       cluster = clusterer.clusters[i];
+       if ( cluster != null && ! bounds.contains( cluster.marker.getPoint() ) && cluster.onMap ){
+           clusterer.map.removeOverlay( cluster.marker );
+           cluster.onMap = false;
+       }
+    }
+
+    // Clustering!  This is some complicated stuff.  We have three goals
+    // here.  One, limit the number of markers & clusters displayed, so the
+    // maps code doesn't slow to a crawl.  Two, when possible keep existing
+    // clusters instead of replacing them with new ones, so that the app pans
+    // better.  And three, of course, be CPU and memory efficient.
+    if ( visibleMarkers.length > clusterer.maxVisibleMarkers ){
+       // Add to the list of clusters by splitting up the current bounds
+       // into a grid.
+       var latRange = bounds.getNorthEast().lat() - bounds.getSouthWest().lat();
+       var latInc = latRange / clusterer.gridSize;
+       var lngInc = latInc / Math.cos( ( bounds.getNorthEast().lat() + bounds.getSouthWest().lat() ) / 2.0 * Math.PI / 180.0 );
+       for ( var lat = bounds.getSouthWest().lat(); lat <= bounds.getNorthEast().lat(); lat += latInc )
+           for ( var lng = bounds.getSouthWest().lng(); lng <= bounds.getNorthEast().lng(); lng += lngInc ){
+               cluster = new Object();
+               cluster.clusterer = clusterer;
+               cluster.bounds = new GLatLngBounds( new GLatLng( lat, lng ), new GLatLng( lat + latInc, lng + lngInc ) );
+               cluster.markers = [];
+               cluster.markerCount = 0;
+               cluster.onMap = false;
+               cluster.marker = null;
+               clusterer.clusters.push( cluster );
+           }
+
+       // Put all the unclustered visible markers into a cluster - the first
+       // one it fits in, which favors pre-existing clusters.
+       for ( i = 0, len = visibleMarkers.length ; i < len; ++i ){
+           marker = visibleMarkers[i];
+           if ( marker != null && ! marker.inCluster ){
+               for ( j = 0, len2 = clusterer.clusters.length ; j < len2 ; ++j ){
+                   cluster = clusterer.clusters[j];
+                   if ( cluster != null && cluster.bounds.contains( marker.getPoint() ) ){
+                       cluster.markers.push( marker );
+                       ++cluster.markerCount;
+                       marker.inCluster = true;
+                   }
+               }
+           }
+       }
+
+       // Get rid of any clusters containing only a few markers.
+       for ( i = 0, len = clusterer.clusters.length ; i < len ; ++i )
+           if ( clusterer.clusters[i] != null && clusterer.clusters[i].markerCount < clusterer.minMarkersPerCluster ){
+               clusterer.clearCluster( clusterer.clusters[i] );
+               clusterer.clusters[i] = null;
+           }
+
+       // Shrink the clusters list.
+       for ( i = clusterer.clusters.length - 1; i >= 0; --i )
+           if ( clusterer.clusters[i] != null )
+               break;
+           else
+               --clusterer.clusters.length;
+
+       // Ok, we have our clusters.  Go through the markers in each
+       // cluster and remove them from the map if they are currently up.
+       for ( i = 0, len = clusterer.clusters.length ; i < len; ++i ){
+           cluster = clusterer.clusters[i];
+           if ( cluster != null ){
+               for ( j = 0 , len2 = cluster.markers.length ; j < len2; ++j ){
+                   marker = cluster.markers[j];
+                   if ( marker != null && marker.onMap ){
+                       clusterer.map.removeOverlay( marker );
+                       marker.onMap = false;
+                   }
+               }
+           }
+       }
+       
+       // Now make cluster-markers for any clusters that need one.
+       for ( i = 0, len = clusterer.clusters.length; i < len; ++i ){
+           cluster = clusterer.clusters[i];
+           if ( cluster != null && cluster.marker == null ){
+               // Figure out the average coordinates of the markers in this
+               // cluster.
+               var xTotal = 0.0, yTotal = 0.0;
+               for ( j = 0, len2 = cluster.markers.length; j < len2 ; ++j ){
+                   marker = cluster.markers[j];
+                   if ( marker != null ){
+                       xTotal += ( + marker.getPoint().lng() );
+                       yTotal += ( + marker.getPoint().lat() );
+                   }
+               }
+               var location = new GLatLng( yTotal / cluster.markerCount, xTotal / cluster.markerCount );
+               marker = new GMarker( location, { icon: clusterer.icon } );
+               cluster.marker = marker;
+               GEvent.addListener( marker, 'click', Clusterer.makeCaller( Clusterer.popUp, cluster ) );
+           }
+       }
+    }
+
+    // Display the visible markers not already up and not in clusters.
+    for ( i = 0, len = visibleMarkers.length; i < len; ++i ){
+       marker = visibleMarkers[i];
+       if ( marker != null && ! marker.onMap && ! marker.inCluster )
+       {
+           clusterer.map.addOverlay( marker );
+           marker.addedToMap();
+           marker.onMap = true;
+       }
+    }
+
+    // Display the visible clusters not already up.
+    for ( i = 0, len = clusterer.clusters.length ; i < len; ++i ){
+       cluster = clusterer.clusters[i];
+       if ( cluster != null && ! cluster.onMap && bounds.contains( cluster.marker.getPoint() )){
+           clusterer.map.addOverlay( cluster.marker );
+           cluster.onMap = true;
+       }
+    }
+
+    // In case a cluster is currently popped-up, re-pop to get any new
+    // markers into the infobox.
+    Clusterer.rePop( clusterer );
+};
+
+
+Clusterer.popUp = function ( cluster ){
+    var clusterer = cluster.clusterer;
+    var html = '<table width="300">';
+    var n = 0;
+    for ( var i = 0 , len = cluster.markers.length; i < len; ++i )
+       {
+       var marker = cluster.markers[i];
+       if ( marker != null )
+           {
+           ++n;
+           html += '<tr><td>';
+           if ( marker.getIcon().smallImage != null )
+               html += '<img src="' + marker.getIcon().smallImage + '">';
+           else
+               html += '<img src="' + marker.getIcon().image + '" width="' + ( marker.getIcon().iconSize.width / 2 ) + '" height="' + ( marker.getIcon().iconSize.height / 2 ) + '">';
+           html += '</td><td>' + marker.description + '</td></tr>';
+           if ( n == clusterer.maxLinesPerInfoBox - 1 && cluster.markerCount > clusterer.maxLinesPerInfoBox  )
+               {
+               html += '<tr><td colspan="2">...and ' + ( cluster.markerCount - n ) + ' more</td></tr>';
+               break;
+               }
+           }
+       }
+    html += '</table>';
+    clusterer.map.closeInfoWindow();
+    cluster.marker.openInfoWindowHtml( html );
+    clusterer.poppedUpCluster = cluster;
+};
+
+Clusterer.rePop = function ( clusterer ){
+    if ( clusterer.poppedUpCluster != null )
+       Clusterer.popUp( clusterer.poppedUpCluster );
+};
+
+Clusterer.popDown = function ( clusterer ){
+    clusterer.poppedUpCluster = null;
+};
+
+Clusterer.prototype.clearCluster = function ( cluster ){
+    var i, marker;
+
+    for ( i = 0; i < cluster.markers.length; ++i ){
+       if ( cluster.markers[i] != null ){
+           cluster.markers[i].inCluster = false;
+           cluster.markers[i] = null;
+       }
+    }
+    
+    cluster.markers.length = 0;
+    cluster.markerCount = 0;
+    
+    if ( cluster == this.poppedUpCluster )
+       this.map.closeInfoWindow();
+    
+    if ( cluster.onMap )
+    {
+       this.map.removeOverlay( cluster.marker );
+       cluster.onMap = false;
+    }
+};
+
+// This returns a function closure that calls the given routine with the
+// specified arg.
+Clusterer.makeCaller = function ( func, arg ){
+    return function () { func( arg ); };
+};
+
+
+// Augment GMarker so it handles markers that have been created but
+// not yet addOverlayed.
+GMarker.prototype.setMap = function ( map ){
+    this.map = map;
+};
+
+GMarker.prototype.getMap = function (){
+    return this.map;
+}
+
+GMarker.prototype.addedToMap = function (){
+    this.map = null;
+};
+
+
+GMarker.prototype.origOpenInfoWindow = GMarker.prototype.openInfoWindow;
+GMarker.prototype.openInfoWindow = function ( node, opts ){
+    if ( this.map != null )
+       return this.map.openInfoWindow( this.getPoint(), node, opts );
+    else
+       return this.origOpenInfoWindow( node, opts );
+};
+
+GMarker.prototype.origOpenInfoWindowHtml = GMarker.prototype.openInfoWindowHtml;
+GMarker.prototype.openInfoWindowHtml = function ( html, opts ){
+    if ( this.map != null )
+       return this.map.openInfoWindowHtml( this.getPoint(), html, opts );
+    else
+       return this.origOpenInfoWindowHtml( html, opts );
+};
+
+GMarker.prototype.origOpenInfoWindowTabs = GMarker.prototype.openInfoWindowTabs;
+GMarker.prototype.openInfoWindowTabs = function ( tabNodes, opts ){
+    if ( this.map != null )
+       return this.map.openInfoWindowTabs( this.getPoint(), tabNodes, opts );
+    else
+       return this.origOpenInfoWindowTabs( tabNodes, opts );
+};
+
+GMarker.prototype.origOpenInfoWindowTabsHtml = GMarker.prototype.openInfoWindowTabsHtml;
+GMarker.prototype.openInfoWindowTabsHtml = function ( tabHtmls, opts ){
+    if ( this.map != null )
+       return this.map.openInfoWindowTabsHtml( this.getPoint(), tabHtmls, opts );
+    else
+       return this.origOpenInfoWindowTabsHtml( tabHtmls, opts );
+};
+
+GMarker.prototype.origShowMapBlowup = GMarker.prototype.showMapBlowup;
+GMarker.prototype.showMapBlowup = function ( opts ){
+    if ( this.map != null )
+       return this.map.showMapBlowup( this.getPoint(), opts );
+    else
+       return this.origShowMapBlowup( opts );
+};
+
+
+function addDescriptionToMarker(marker, description){
+    marker.description = description;
+    return marker;
+}
diff --git a/public/javascripts/geoRssOverlay.js b/public/javascripts/geoRssOverlay.js
new file mode 100644 (file)
index 0000000..315c26d
--- /dev/null
@@ -0,0 +1,194 @@
+// GeoRssOverlay: GMaps API extension to display a group of markers from
+// a RSS feed
+//
+// Copyright 2006 Mikel Maron (email: mikel_maron yahoo com)
+//
+// The original version of this code is called MGeoRSS and can be found
+// at the following address:
+// http://brainoff.com/gmaps/mgeorss.html
+//
+// Modified by Andrew Turner to add support for the GeoRss Simple vocabulary
+//
+// Modified and bundled with YM4R in accordance with the following
+// license:
+//
+// This work is public domain
+
+function GeoRssOverlay(rssurl,icon,proxyurl,options){
+    this.rssurl = rssurl;
+    this.icon = icon;
+    this.proxyurl = proxyurl;
+    if(options['visible'] == undefined)
+       this.visible = true;
+    else
+       this.visible = options['visible'];
+    this.listDiv = options['listDiv']; //ID of the item list DIV
+    this.contentDiv = options['contentDiv']; //ID of the content DIV
+    this.listItemClass = options['listItemClass']; //Class of the list item DIV
+    this.limitItems = options['limit']; //Maximum number of displayed entries
+    this.request = false;
+    this.markers = [];
+}
+
+GeoRssOverlay.prototype = new GOverlay();
+
+GeoRssOverlay.prototype.initialize=function(map) {
+    this.map = map;
+    this.load();
+}
+
+GeoRssOverlay.prototype.redraw = function(force){
+    //nothing to do : the markers are already taken care of
+}
+
+GeoRssOverlay.prototype.remove = function(){
+    for(var i= 0, len = this.markers.length ; i< len; i++){
+       this.map.removeOverlay(this.markers[i]);
+    }
+}
+
+GeoRssOverlay.prototype.showHide=function() {
+    if (this.visible) {
+       for (var i=0;i<this.markers.length;i++) {
+           this.map.removeOverlay(this.markers[i]);
+       }
+       this.visible = false;
+    } else {
+       for (var i=0;i<this.markers.length;i++) {
+           this.map.addOverlay(this.markers[i]);
+       }
+       this.visible = true;
+    }
+}
+
+GeoRssOverlay.prototype.showMarker = function(id){
+    var marker = this.markers[id];
+    if(marker != undefined){
+       GEvent.trigger(marker,"click");
+    }
+}
+
+GeoRssOverlay.prototype.copy = function(){
+    var oCopy = new GeoRssOVerlay(this.rssurl,this.icon,this.proxyurl);
+    oCopy.markers = [];
+    for(var i = 0 , len = this.markers.length ;i < len ; i++){
+       oCopy.markers.push(this.markers[i].copy());
+    }
+    return oCopy;
+}
+
+GeoRssOverlay.prototype.load=function() {
+    if (this.request != false) { 
+       return; 
+    }
+    this.request = GXmlHttp.create();
+    if (this.proxyurl != undefined) {
+       this.request.open("GET",this.proxyurl + '?q=' + encodeURIComponent(this.rssurl),true);
+    } else {
+       this.request.open("GET",this.rssurl, true);
+    }
+    var m = this;
+    this.request.onreadystatechange = function() {
+       m.callback();
+    }
+    this.request.send(null);
+}
+
+GeoRssOverlay.prototype.callback = function() {
+    if (this.request.readyState == 4) {
+       if (this.request.status == "200") {
+           var xmlDoc = this.request.responseXML;
+           if(xmlDoc.documentElement.getElementsByTagName("item").length != 0){
+               //RSS
+               var items = xmlDoc.documentElement.getElementsByTagName("item");
+           }else if(xmlDoc.documentElement.getElementsByTagName("entry").length != 0){
+               //Atom
+               var items = xmlDoc.documentElement.getElementsByTagName("entry");
+           }
+           for (var i = 0, len = this.limitItems?Math.min(this.limitItems,items.length):items.length; i < len; i++) {
+               try {
+                   var marker = this.createMarker(items[i],i);
+                   this.markers.push(marker);
+                   if(this.visible){
+                       this.map.addOverlay(marker);
+                   }
+               } catch (e) {
+               }
+           }
+       }
+       this.request = false;
+    }
+}
+
+GeoRssOverlay.prototype.createMarker = function(item,index) {
+    
+    var title = item.getElementsByTagName("title")[0].childNodes[0].nodeValue;
+    if(item.getElementsByTagName("description").length != 0){
+       //Rss
+       var description = item.getElementsByTagName("description")[0].childNodes[0].nodeValue;
+       var link = item.getElementsByTagName("link")[0].childNodes[0].nodeValue;    }else if(item.getElementsByTagName("summary").length != 0){
+       //Atom
+       var description = item.getElementsByTagName("summary")[0].childNodes[0].nodeValue;
+       var link = item.getElementsByTagName("link")[0].attributes[0].nodeValue;
+       }
+    /* namespaces are handled by spec in moz, not in ie */
+    if (navigator.userAgent.toLowerCase().indexOf("msie") < 0) {
+               if(item.getElementsByTagNameNS("http://www.w3.org/2003/01/geo/wgs84_pos#","lat").length != 0){
+           //W3C Geo Vocabulary
+           var lat = item.getElementsByTagNameNS("http://www.w3.org/2003/01/geo/wgs84_pos#","lat")[0].childNodes[0].nodeValue;
+           var lng = item.getElementsByTagNameNS("http://www.w3.org/2003/01/geo/wgs84_pos#","long")[0].childNodes[0].nodeValue;
+       }else if(item.getElementsByTagNameNS("http://www.georss.org/georss","point").length != 0){
+           
+           //Simple
+           var latlng = item.getElementsByTagNameNS("http://www.georss.org/georss","point")[0].childNodes[0].nodeValue.split(" ");
+           var lat = latlng[0];
+           var lng = latlng[1];
+       }
+    } else {
+       
+       if(item.getElementsByTagName("geo:lat").length != 0){
+           //W3C Geo Vocabulary
+           var lat = item.getElementsByTagName("geo:lat")[0].childNodes[0].nodeValue;
+           var lng = item.getElementsByTagName("geo:long")[0].childNodes[0].nodeValue;
+       }else if(item.getElementsByTagName("georss:point").length != 0){
+           //Simple
+           var latlng = item.getElementsByTagName("georss:point")[0].childNodes[0].nodeValue.split(" ");
+           var lat = latlng[0];
+           var lng = latlng[1];
+       }
+    }
+    
+    var point = new GLatLng(parseFloat(lat), parseFloat(lng));
+    var marker = new GMarker(point,{'title': title});
+    var html = "<a href=\"" + link + "\">" + title + "</a><p/>" + description;
+    
+    if(this.contentDiv == undefined){
+       GEvent.addListener(marker, "click", function() {
+           marker.openInfoWindowHtml(html);
+       });
+    }else{
+       var contentDiv = this.contentDiv;
+       GEvent.addListener(marker, "click", function() {
+           document.getElementById(contentDiv).innerHTML = html;
+       });
+    }
+    
+    if(this.listDiv != undefined){
+       var a = document.createElement('a'); 
+       a.innerHTML = title;
+       a.setAttribute("href","#");
+       var georss = this;
+       a.onclick = function(){
+           georss.showMarker(index);
+           return false;
+       };
+       var div = document.createElement('div');
+       if(this.listItemClass != undefined){
+           div.setAttribute("class",this.listItemClass);
+       }
+       div.appendChild(a);
+       document.getElementById(this.listDiv).appendChild(div);
+    }
+    
+    return marker;
+}
diff --git a/public/javascripts/markerGroup.js b/public/javascripts/markerGroup.js
new file mode 100644 (file)
index 0000000..02fe624
--- /dev/null
@@ -0,0 +1,114 @@
+function GMarkerGroup(active, markers, markersById) {\r
+    this.active = active;\r
+    this.markers = markers || new Array();\r
+    this.markersById = markersById || new Object();\r
+}\r
+\r
+GMarkerGroup.prototype = new GOverlay();\r
+\r
+GMarkerGroup.prototype.initialize = function(map) {\r
+    this.map = map;\r
+    \r
+    if(this.active){\r
+       for(var i = 0 , len = this.markers.length; i < len; i++) {\r
+           this.map.addOverlay(this.markers[i]);\r
+       }\r
+       for(var id in this.markersById){\r
+           this.map.addOverlay(this.markersById[id]);\r
+       }\r
+    }\r
+}\r
+\r
+//If not already done (ie if not inactive) remove all the markers from the map\r
+GMarkerGroup.prototype.remove = function() {\r
+    this.deactivate();\r
+}\r
+\r
+GMarkerGroup.prototype.redraw = function(force){\r
+    //Nothing to do : markers are already taken care of\r
+}\r
+\r
+//Copy the data to a new Marker Group\r
+GMarkerGroup.prototype.copy = function() {\r
+    var overlay = new GMarkerGroup(this.active);\r
+    overlay.markers = this.markers; //Need to do deep copy\r
+    overlay.markersById = this.markersById; //Need to do deep copy\r
+    return overlay;\r
+}\r
+\r
+//Inactivate the Marker group and clear the internal content\r
+GMarkerGroup.prototype.clear = function(){\r
+    //deactivate the map first (which removes the markers from the map)\r
+    this.deactivate();\r
+    //Clear the internal content\r
+    this.markers = new Array();\r
+    this.markersById = new Object();\r
+}\r
+\r
+//Add a marker to the GMarkerGroup ; Adds it now to the map if the GMarkerGroup is active\r
+GMarkerGroup.prototype.addMarker = function(marker,id){\r
+    if(id == undefined){\r
+       this.markers.push(marker);\r
+    }else{\r
+       this.markersById[id] = marker;\r
+    }\r
+    if(this.active && this.map != undefined ){\r
+       this.map.addOverlay(marker);\r
+    }\r
+}\r
+\r
+//Open the info window (or info window tabs) of a marker\r
+GMarkerGroup.prototype.showMarker = function(id){\r
+    var marker = this.markersById[id];\r
+    if(marker != undefined){\r
+       GEvent.trigger(marker,"click");\r
+    }\r
+}\r
+\r
+//Activate (or deactivate depending on the argument) the GMarkerGroup\r
+GMarkerGroup.prototype.activate = function(active){\r
+    active = (active == undefined) ? true : active;\r
+    if(!active){\r
+       if(this.active){\r
+           if(this.map != undefined){\r
+               for(var i = 0 , len = this.markers.length; i < len; i++){\r
+                   this.map.removeOverlay(this.markers[i])\r
+               }\r
+               for(var id in this.markersById){\r
+                   this.map.removeOverlay(this.markersById[id]);\r
+               }\r
+           }\r
+           this.active = false;\r
+       }\r
+    }else{\r
+       if(!this.active){\r
+           if(this.map != undefined){\r
+               for(var i = 0 , len = this.markers.length; i < len; i++){\r
+                   this.map.addOverlay(this.markers[i]);\r
+               }\r
+               for(var id in this.markersById){\r
+                   this.map.addOverlay(this.markersById[id]);\r
+               }\r
+           }\r
+           this.active = true;\r
+       }\r
+    }\r
+}\r
+\r
+GMarkerGroup.prototype.centerAndZoomOnMarkers = function() {\r
+    if(this.map != undefined){\r
+       //merge markers and markersById\r
+       var tmpMarkers = this.markers.slice();\r
+       for (var id in this.markersById){\r
+           tmpMarkers.push(this.markersById[id]);\r
+       }\r
+       if(tmpMarkers.length > 0){\r
+           this.map.centerAndZoomOnMarkers(tmpMarkers);\r
+       } \r
+    }\r
+}      \r
+\r
+//Deactivate the Group Overlay (convenience method)\r
+GMarkerGroup.prototype.deactivate = function(){\r
+    this.activate(false);\r
+}\r
diff --git a/public/javascripts/wms-gs.js b/public/javascripts/wms-gs.js
new file mode 100644 (file)
index 0000000..c67146b
--- /dev/null
@@ -0,0 +1,69 @@
+/*
+ * Call generic wms service for GoogleMaps v2
+ * John Deck, UC Berkeley
+ * Inspiration & Code from:
+ *     Mike Williams http://www.econym.demon.co.uk/googlemaps2/ V2 Reference & custommap code
+ *     Brian Flood http://www.spatialdatalogic.com/cs/blogs/brian_flood/archive/2005/07/11/39.aspx V1 WMS code
+ *     Kyle Mulka http://blog.kylemulka.com/?p=287  V1 WMS code modifications
+ *      http://search.cpan.org/src/RRWO/GPS-Lowrance-0.31/lib/Geo/Coordinates/MercatorMeters.pm
+ *
+ * Modified by Chris Holmes, TOPP to work by default with GeoServer.
+ *
+ * Bundled with YM4R with John Deck's permission.
+ * Slightly modified to fit YM4R.
+ * See johndeck.blogspot.com for the original version and for examples and instructions of how to use it.
+ */
+
+var WGS84_SEMI_MAJOR_AXIS = 6378137.0; //equatorial radius
+var WGS84_ECCENTRICITY = 0.0818191913108718138;
+var DEG2RAD=0.0174532922519943;
+var PI=3.14159267;
+
+function dd2MercMetersLng(p_lng) { 
+       return WGS84_SEMI_MAJOR_AXIS * (p_lng*DEG2RAD); 
+}
+
+function dd2MercMetersLat(p_lat) {
+        var lat_rad = p_lat * DEG2RAD;
+       return WGS84_SEMI_MAJOR_AXIS * Math.log(Math.tan((lat_rad + PI / 2) / 2) * Math.pow( ((1 - WGS84_ECCENTRICITY * Math.sin(lat_rad)) / (1 + WGS84_ECCENTRICITY * Math.sin(lat_rad))), (WGS84_ECCENTRICITY/2)));
+}
+
+function addWMSPropertiesToLayer(tile_layer,base_url,layers,styles,format,merc_proj,use_geo){
+   tile_layer.format = format;
+   tile_layer.baseURL = base_url;
+   tile_layer.styles = styles;
+   tile_layer.layers = layers;
+   tile_layer.mercatorEpsg = merc_proj;
+   tile_layer.useGeographic = use_geo;
+   return tile_layer;
+}
+
+getTileUrlForWMS=function(a,b,c) {
+       var lULP = new GPoint(a.x*256,(a.y+1)*256);
+       var lLRP = new GPoint((a.x+1)*256,a.y*256);
+       var lUL = G_NORMAL_MAP.getProjection().fromPixelToLatLng(lULP,b,c);
+       var lLR = G_NORMAL_MAP.getProjection().fromPixelToLatLng(lLRP,b,c);
+        
+       if (this.useGeographic){
+           var lBbox=lUL.x+","+lUL.y+","+lLR.x+","+lLR.y;
+          var lSRS="EPSG:4326";
+       }else{
+          var lBbox=dd2MercMetersLng(lUL.x)+","+dd2MercMetersLat(lUL.y)+","+dd2MercMetersLng(lLR.x)+","+dd2MercMetersLat(lLR.y);
+          var lSRS="EPSG:" + this.mercatorEpsg;
+        }
+       var lURL=this.baseURL;
+       lURL+="?REQUEST=GetMap";
+       lURL+="&SERVICE=WMS";
+       lURL+="&VERSION=1.1.1";
+       lURL+="&LAYERS="+this.layers;
+       lURL+="&STYLES="+this.styles; 
+       lURL+="&FORMAT=image/"+this.format;
+       lURL+="&BGCOLOR=0xFFFFFF";
+       lURL+="&TRANSPARENT=TRUE";
+       lURL+="&SRS="+lSRS;
+       lURL+="&BBOX="+lBbox;
+       lURL+="&WIDTH=256";
+       lURL+="&HEIGHT=256";
+       lURL+="&reaspect=false";
+       return lURL;
+}
diff --git a/public/javascripts/ym4r-gm.js b/public/javascripts/ym4r-gm.js
new file mode 100644 (file)
index 0000000..1c768df
--- /dev/null
@@ -0,0 +1,117 @@
+// JS helper functions for YM4R\r
+\r
+function addInfoWindowToMarker(marker,info,options){\r
+       GEvent.addListener(marker, "click", function() {marker.openInfoWindowHtml(info,options);});\r
+       return marker;\r
+}\r
+\r
+function addInfoWindowTabsToMarker(marker,info,options){\r
+     GEvent.addListener(marker, "click", function() {marker.openInfoWindowTabsHtml(info,options);});\r
+     return marker;\r
+}\r
+\r
+function addPropertiesToLayer(layer,getTile,copyright,opacity,isPng){\r
+    layer.getTileUrl = getTile;\r
+    layer.getCopyright = copyright;\r
+    layer.getOpacity = opacity;\r
+    layer.isPng = isPng;\r
+    return layer;\r
+}\r
+\r
+function addOptionsToIcon(icon,options){\r
+    for(var k in options){\r
+       icon[k] = options[k];\r
+    }\r
+    return icon;\r
+}\r
+\r
+function addCodeToFunction(func,code){\r
+    if(func == undefined)\r
+       return code;\r
+    else{\r
+       return function(){\r
+           func();\r
+           code();\r
+       }\r
+    }\r
+}\r
+\r
+function addGeocodingToMarker(marker,address){\r
+    marker.orig_initialize = marker.initialize;\r
+    orig_redraw = marker.redraw;\r
+    marker.redraw = function(force){}; //empty the redraw method so no error when called by addOverlay.\r
+    marker.initialize = function(map){\r
+       new GClientGeocoder().getLatLng(address,\r
+                                       function(latlng){\r
+           if(latlng){\r
+               marker.redraw = orig_redraw;\r
+               marker.orig_initialize(map); //init before setting point\r
+               marker.setPoint(latlng);\r
+           }//do nothing\r
+       });\r
+    };\r
+    return marker;\r
+}\r
+\r
+\r
+\r
+GMap2.prototype.centerAndZoomOnMarkers = function(markers) {\r
+     var bounds = new GLatLngBounds(markers[0].getPoint(),\r
+                                   markers[0].getPoint());\r
+     for (var i=1, len = markers.length ; i<len; i++) {\r
+        bounds.extend(markers[i].getPoint());\r
+     }\r
+     \r
+     this.centerAndZoomOnBounds(bounds);\r
+ } \r
+\r
+GMap2.prototype.centerAndZoomOnPoints = function(points) {\r
+     var bounds = new GLatLngBounds(points[0],\r
+                                   points[0]);\r
+     for (var i=1, len = points.length ; i<len; i++) {\r
+        bounds.extend(points[i]);\r
+     }\r
+     \r
+     this.centerAndZoomOnBounds(bounds);\r
+ } \r
+\r
+GMap2.prototype.centerAndZoomOnBounds = function(bounds) {\r
+    var center = bounds.getCenter();\r
+    this.setCenter(center, this.getBoundsZoomLevel(bounds));\r
+} \r
+\r
+//For full screen mode\r
+function setWindowDims(elem) {\r
+    if (window.innerWidth){\r
+       elem.style.height = (window.innerHeight) + 'px;';\r
+       elem.style.width = (window.innerWidth) + 'px;';\r
+    }else if (document.body.clientWidth){\r
+       elem.style.width = (document.body.clientWidth) + 'px';\r
+       elem.style.height = (document.body.clientHeight) + 'px';\r
+    }\r
+}\r
+\r
+ManagedMarker = function(markers,minZoom,maxZoom) {\r
+    this.markers = markers;\r
+    this.minZoom = minZoom;\r
+    this.maxZoom = maxZoom;\r
+}\r
+\r
+//Add the markers and refresh\r
+function addMarkersToManager(manager,managedMarkers){\r
+    for(var i = 0, length = managedMarkers.length; i < length;i++) {\r
+       mm = managedMarkers[i];\r
+       manager.addMarkers(mm.markers,mm.minZoom,mm.maxZoom);\r
+    }\r
+    manager.refresh();\r
+    return manager;\r
+}\r
+\r
+\r
+var INVISIBLE = new GLatLng(0,0); //almost always invisible\r
+\r
+if(self.Event && Event.observe){\r
+    Event.observe(window, 'unload', GUnload);\r
+}else{\r
+    window.onunload = GUnload;\r
+}\r
diff --git a/test/fixtures/full_voters.yml b/test/fixtures/full_voters.yml
deleted file mode 100644 (file)
index 8794d28..0000000
+++ /dev/null
@@ -1,5 +0,0 @@
-# Read about fixtures at http://ar.rubyonrails.org/classes/Fixtures.html
-first:
-  id: 1
-another:
-  id: 2
diff --git a/test/fixtures/quick_voters.yml b/test/fixtures/quick_voters.yml
deleted file mode 100644 (file)
index 8794d28..0000000
+++ /dev/null
@@ -1,5 +0,0 @@
-# Read about fixtures at http://ar.rubyonrails.org/classes/Fixtures.html
-first:
-  id: 1
-another:
-  id: 2
diff --git a/test/fixtures/quick_votes.yml b/test/fixtures/quick_votes.yml
deleted file mode 100644 (file)
index 8794d28..0000000
+++ /dev/null
@@ -1,5 +0,0 @@
-# Read about fixtures at http://ar.rubyonrails.org/classes/Fixtures.html
-first:
-  id: 1
-another:
-  id: 2
index 18733048979d34d2b351ab4798fb1220f589fac9..52b16d5fba3a7732f450c4ca5f9b33841705cbdb 100644 (file)
@@ -1,88 +1,19 @@
 require File.dirname(__FILE__) + '/../test_helper'
-require 'elections_controller'
+require 'election_controller'
 
 # Re-raise errors caught by the controller.
-class ElectionsController; def rescue_action(e) raise e end; end
+class ElectionController; def rescue_action(e) raise e end; end
 
-class ElectionsControllerTest < Test::Unit::TestCase
+class ElectionControllerTest < Test::Unit::TestCase
   fixtures :elections
 
   def setup
-    @controller = ElectionsController.new
+    @controller = ElectionController.new
     @request    = ActionController::TestRequest.new
     @response   = ActionController::TestResponse.new
   end
-
-  def test_index
-    get :index
-    assert_response :success
-    assert_template 'list'
-  end
-
-  def test_list
-    get :list
-
-    assert_response :success
-    assert_template 'list'
-
-    assert_not_nil assigns(:elections)
-  end
-
-  def test_show
-    get :show, :id => 1
-
-    assert_response :success
-    assert_template 'show'
-
-    assert_not_nil assigns(:election)
-    assert assigns(:election).valid?
-  end
-
-  def test_new
-    get :new
-
-    assert_response :success
-    assert_template 'new'
-
-    assert_not_nil assigns(:election)
-  end
-
-  def test_create
-    num_elections = Election.count
-
-    post :create, :election => {}
-
-    assert_response :redirect
-    assert_redirected_to :action => 'list'
-
-    assert_equal num_elections + 1, Election.count
-  end
-
-  def test_edit
-    get :edit, :id => 1
-
-    assert_response :success
-    assert_template 'edit'
-
-    assert_not_nil assigns(:election)
-    assert assigns(:election).valid?
-  end
-
-  def test_update
-    post :update, :id => 1
-    assert_response :redirect
-    assert_redirected_to :action => 'show', :id => 1
-  end
-
-  def test_destroy
-    assert_not_nil Election.find(1)
-
-    post :destroy, :id => 1
-    assert_response :redirect
-    assert_redirected_to :action => 'list'
-
-    assert_raise(ActiveRecord::RecordNotFound) {
-      Election.find(1)
-    }
+  def test_true
+    #Make rake happy when empty
+    assert true
   end
 end
similarity index 52%
rename from test/functional/graphs_controller_test.rb
rename to test/functional/graph_controller_test.rb
index 8e206d355b7b90c16bbe18ceb9873f2a6222ab56..45943351ceac77e198f75d70b9594dc2f449bf0b 100644 (file)
@@ -1,24 +1,22 @@
 require File.dirname(__FILE__) + '/../test_helper'
-require 'graphs_controller'
+require 'graph_controller'
 
 # Re-raise errors caught by the controller.
-class GraphsController; def rescue_action(e) raise e end; end
+class GraphController; def rescue_action(e) raise e end; end
 
-class GraphsControllerTest < Test::Unit::TestCase
+class GraphControllerTest < Test::Unit::TestCase
 
   #fixtures :data
 
   def setup
-    @controller = GraphsController.new
+    @controller = GraphController.new
     @request    = ActionController::TestRequest.new
     @response   = ActionController::TestResponse.new
   end
 
   # TODO Replace this with your actual tests
   def test_show
-    get :show
-    assert_response :success
-    assert_equal 'image/png', @response.headers['Content-Type']
+    assert true
   end
   
 end
diff --git a/test/functional/user_controller_test.rb b/test/functional/user_controller_test.rb
deleted file mode 100644 (file)
index b97a404..0000000
+++ /dev/null
@@ -1,18 +0,0 @@
-require File.dirname(__FILE__) + '/../test_helper'
-require 'user_controller'
-
-# Re-raise errors caught by the controller.
-class UserController; def rescue_action(e) raise e end; end
-
-class UserControllerTest < Test::Unit::TestCase
-  def setup
-    @controller = UserController.new
-    @request    = ActionController::TestRequest.new
-    @response   = ActionController::TestResponse.new
-  end
-
-  # Replace this with your real tests.
-  def test_truth
-    assert true
-  end
-end
diff --git a/test/unit/full_voter_test.rb b/test/unit/full_voter_test.rb
deleted file mode 100644 (file)
index 833ca44..0000000
+++ /dev/null
@@ -1,10 +0,0 @@
-require File.dirname(__FILE__) + '/../test_helper'
-
-class FullVoterTest < Test::Unit::TestCase
-  fixtures :full_voters
-
-  # Replace this with your real tests.
-  def test_truth
-    assert true
-  end
-end
diff --git a/test/unit/quick_vote_test.rb b/test/unit/quick_vote_test.rb
deleted file mode 100644 (file)
index 5846db2..0000000
+++ /dev/null
@@ -1,10 +0,0 @@
-require File.dirname(__FILE__) + '/../test_helper'
-
-class QuickVoteTest < Test::Unit::TestCase
-  fixtures :quick_votes
-
-  # Replace this with your real tests.
-  def test_truth
-    assert true
-  end
-end
diff --git a/test/unit/quick_voter_test.rb b/test/unit/quick_voter_test.rb
deleted file mode 100644 (file)
index d6e0a11..0000000
+++ /dev/null
@@ -1,10 +0,0 @@
-require File.dirname(__FILE__) + '/../test_helper'
-
-class QuickVoterTest < Test::Unit::TestCase
-  fixtures :quick_voters
-
-  # Replace this with your real tests.
-  def test_truth
-    assert true
-  end
-end
diff --git a/test/unit/raw_voter_list_test.rb b/test/unit/raw_voter_list_test.rb
deleted file mode 100644 (file)
index 3ed0984..0000000
+++ /dev/null
@@ -1,10 +0,0 @@
-require File.dirname(__FILE__) + '/../test_helper'
-
-class RawVoterListTest < Test::Unit::TestCase
-  fixtures :raw_voter_lists
-
-  # Replace this with your real tests.
-  def test_truth
-    assert_kind_of RawVoterList, raw_voter_lists(:first)
-  end
-end
diff --git a/test/unit/selectricityservice_test.rb b/test/unit/selectricityservice_test.rb
new file mode 100644 (file)
index 0000000..877f7e9
--- /dev/null
@@ -0,0 +1,123 @@
+require File.dirname(__FILE__) + '/../test_helper'
+require 'selectricity_service_controller'
+
+class SelectricityServiceTest < Test::Unit::TestCase
+  def setup
+    @controller=SelectricityServiceController.new
+    @request=ActionController::TestRequest.new
+    @response   = ActionController::TestResponse.new
+  end
+
+  def test_list_quickvotes
+    result= invoke_delegated :vote, :list_quickvotes
+    assert_instance_of Array, result
+    assert_equal result.length, 0
+  end
+  def test_create_quickvote
+    election = ElectionStruct.new :name => "TestVote", :description => "Test Vote", :candidate_names => ["Apple", "Orange", "Banana", "Pineapple"]
+    assert_create_quickvote_succeeds election
+  end
+  def test_cast_quickvote
+    test_create_quickvote
+    election = invoke_delegated :vote, :get_quickvote, "TestVote"
+    casted_vote = election.candidate_ids.sort_by {rand} #Shuffles
+    invoke_delegated :vote, :cast_quickvote, "TestVote", 42, [casted_vote]
+    quickvote_votes= invoke_delegated :vote, :get_quickvote_votes, "TestVote"
+    assert_equal quickvote_votes.length, 1
+    assert_equal quickvote_votes[0].vote, casted_vote
+  end
+  def test_cast_mass_quickvote
+    test_create_quickvote
+    election = invoke_delegated :vote, :get_quickvote, "TestVote"
+    20.times do |t|
+      casted_vote = election.candidate_ids.sort_by {rand}
+      invoke_delegated :vote, :cast_quickvote, "TestVote", t, [casted_vote]
+    end
+    quickvote_votes= invoke_delegated :vote, :get_quickvote_votes, "TestVote"
+    assert_equal quickvote_votes.length, 20
+  end
+  def test_create_mass_quickvote
+    10.times do |t|
+      election = ElectionStruct.new :name => "test#{t}", :description => "Test Vote", :candidate_names => ["Apple", "Orange", "Banana", "Pineapple"]
+      assert_create_quickvote_succeeds election
+    end
+  end
+  def test_create_quickvote_bad_name
+    election = ElectionStruct.new :name => "invalid space", :description => "Test Vote", :candidate_names => ["Apple", "Orange", "Banana", "Pineapple"]
+    assert_create_quickvote_fails election
+  end
+  def test_create_quickvote_nil
+    election =  ElectionStruct.new
+    assert_create_quickvote_fails election
+  end
+  def test_create_quickvote_name_nil
+    election = ElectionStruct.new :name => "", :description => "Test Vote", :candidate_names => ["Apple", "Orange", "Banana", "Pineapple"]
+    assert_create_quickvote_fails election
+  end
+  def test_create_quickvote_description_nil
+    election = ElectionStruct.new :name => "foobar", :description => nil, :candidate_names => ["Apple", "Orange", "Banana", "Pineapple"]
+    assert_create_quickvote_fails election
+    
+  end
+  def test_create_quickvote_description_whitespace
+    election = ElectionStruct.new :name => "foobar", :description => "       ", :candidate_names => ["Apple", "Orange", "Banana", "Pineapple"]
+    assert_create_quickvote_fails election
+    election = ElectionStruct.new :name => "foobar", :description => "\t\t", :candidate_names => ["Apple", "Orange", "Banana", "Pineapple"]
+    assert_create_quickvote_fails election
+  end
+  def test_create_quickvote_candidates_nil
+    election = ElectionStruct.new :name => "foobar", :description => "valid", :candidate_names => nil
+    assert_create_quickvote_fails election
+  end
+  def test_create_quickvote_insufficient_candidates
+    election = ElectionStruct.new :name => "foobar", :description => "valid", :candidate_names => ["Apple"]
+    assert_create_quickvote_fails election
+  end
+  def test_create_quickvote_candidates_whitespace
+    election = ElectionStruct.new :name => "foobar", :description => "valid", :candidate_names => [" ", "   ", "       ", "         "]
+    assert_create_quickvote_fails election
+  end
+  def test_create_quickvote_dupe_candidates
+    election = ElectionStruct.new :name => "foobar", :description => "valid", :candidate_names => ["Apple", "Apple", "Apple", "Apple"]
+    assert_create_quickvote_fails election
+
+    # Previous may pass coincidentally if a uniq! then a sizecheck reveals too few unique names
+    # We don't want this to happen. Dupe canidates should fail regardless of how many are left.
+
+    election = ElectionStruct.new :name => "foobar", :description => "valid", :candidate_names => ["Apple", "Apple", "Orange", "Orange", "Pineapple" ,  "Pineapple"]
+    assert_create_quickvote_fails election
+  end
+  def test_create_quickvote_candidates_nil_mixed
+    election = ElectionStruct.new :name => "foobar", :description => "valid", :candidate_names => ["Apple", nil ]
+    assert_create_quickvote_fails election
+  end
+  def test_create_quickvote_description_xmlescape
+    # Will an embedded XML element bork the table?
+    election = ElectionStruct.new :name => "foobar", :description => "test </string>", :candidate_names => ["Apple", "Orange", "Banana", "Pineapple"]
+    assert_create_quickvote_succeeds election
+  end
+  def test_create_quickvote_unprintable_description
+    election =  ElectionStruct.new :name => "foobar", :description => "test \x01\x02\x03\x04\x05\x06\x07\x08", :candidate_names => ["Apple", "Orange", "Banana", "Pineapple"]
+    assert_create_quickvote_succeeds election
+  end
+  private
+  def assert_create_quickvote_succeeds(election)
+    # Checks if a created quickvote is identical when retrieved
+    old_len=invoke_delegated(:vote,:list_quickvotes).length
+    result = invoke_delegated :vote, :create_quickvote, election
+    assert_equal result, ""
+    reflection = invoke_delegated :vote, :get_quickvote, election.name
+    assert_equal election.description, reflection.description
+    assert_equal 0, election.name.casecmp(reflection.name)
+    assert_equal election.candidate_names, reflection.candidate_names
+    assert_equal(invoke_delegated(:vote,:list_quickvotes).length, old_len+1)
+  end
+  def assert_create_quickvote_fails(election)
+    # Helper function to check that creating this quickvote fails
+    old_len=invoke_delegated(:vote,:list_quickvotes).length
+    result = invoke_delegated :vote, :create_quickvote, election
+    assert_instance_of String, result
+    assert_not_equal result.length, 0
+    assert_equal(invoke_delegated(:vote,:list_quickvotes).length, old_len)
+  end
+end
diff --git a/test/unit/vote_test.rb b/test/unit/vote_test.rb
deleted file mode 100644 (file)
index 1baaa1b..0000000
+++ /dev/null
@@ -1,10 +0,0 @@
-require File.dirname(__FILE__) + '/../test_helper'
-
-class VotesTest < Test::Unit::TestCase
-  fixtures :votes
-
-  # Replace this with your real tests.
-  def test_truth
-    assert_kind_of Votes, votes(:first)
-  end
-end
diff --git a/test/unit/voter_notify_test.rb b/test/unit/voter_notify_test.rb
deleted file mode 100644 (file)
index 6e5f802..0000000
+++ /dev/null
@@ -1,27 +0,0 @@
-require File.dirname(__FILE__) + '/../test_helper'
-require 'voter_notify'
-
-class VoterNotifyTest < Test::Unit::TestCase
-  FIXTURES_PATH = File.dirname(__FILE__) + '/../fixtures'
-  CHARSET = "utf-8"
-
-  include ActionMailer::Quoting
-
-  def setup
-    ActionMailer::Base.delivery_method = :test
-    ActionMailer::Base.perform_deliveries = true
-    ActionMailer::Base.deliveries = []
-
-    @expected = TMail::Mail.new
-    @expected.set_content_type "text", "plain", { "charset" => CHARSET }
-  end
-
-  private
-    def read_fixture(action)
-      IO.readlines("#{FIXTURES_PATH}/voter_notify/#{action}")
-    end
-
-    def encode(subject)
-      quoted_printable(subject, CHARSET)
-    end
-end
diff --git a/vendor/plugins/geokit/MIT-LICENSE b/vendor/plugins/geokit/MIT-LICENSE
new file mode 100644 (file)
index 0000000..97d81c8
--- /dev/null
@@ -0,0 +1,20 @@
+Copyright (c) 2007 Bill Eisenhauer & Andre Lewis
+
+Permission is hereby granted, free of charge, to any person obtaining
+a copy of this software and associated documentation files (the
+"Software"), to deal in the Software without restriction, including
+without limitation the rights to use, copy, modify, merge, publish,
+distribute, sublicense, and/or sell copies of the Software, and to
+permit persons to whom the Software is furnished to do so, subject to
+the following conditions:
+
+The above copyright notice and this permission notice shall be
+included in all copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
\ No newline at end of file
diff --git a/vendor/plugins/geokit/README b/vendor/plugins/geokit/README
new file mode 100644 (file)
index 0000000..3e72859
--- /dev/null
@@ -0,0 +1,445 @@
+## FEATURE SUMMARY
+
+This plugin provides key functionality for location-oriented Rails applications:
+
+- Distance calculations, for both flat and spherical environments. For example, 
+  given the location of two points on the earth, you can calculate the miles/KM 
+  between them.
+- ActiveRecord distance-based finders. For example, you can find all the points 
+  in your database within a 50-mile radius.
+- Geocoding from multiple providers. It currently supports Google, Yahoo, 
+  Geocoder.us, and Geocoder.ca geocoders, and it provides a uniform response 
+  structure from all of them. It also provides a fail-over mechanism, in case 
+  your input fails to geocode in one service.
+- IP-based location lookup utilizing hostip.info. Provide an IP address, and get
+  city name and latitude/longitude in return
+- A before_filter helper to geocoder the user's location based on IP address, 
+  and retain the location in a cookie.
+  
+The goal of this plugin is to provide the common functionality for location-oriented 
+applications (geocoding, location lookup, distance calculation) in an easy-to-use 
+package.
+
+## A NOTE ON TERMINOLOGY
+
+Throughout the code and API of this, latitude and longitude are referred to as lat 
+and lng.  We've found over the long term the abbreviation saves lots of typing time.
+
+## DISTANCE CALCULATIONS AND QUERIES
+
+If you want only distance calculation services, you need only mix in the Mappable 
+module like so:
+
+    class Location
+       include GeoKit::Mappable
+    end
+
+After doing so, you can do things like:
+
+    Location.distance_between(from, to) 
+
+with optional parameters :units and :formula.  Values for :units can be :miles or 
+:kms with :miles as the default.  Values for :formula can be :sphere or :flat with
+:sphere as the default.  :sphere gives you Haversine calculations, while :flat 
+gives the Pythagoreum Theory.  These defaults persist through out the plug-in.
+
+You can also do:
+
+    location.distance_to(other)
+
+The real power and utility of the plug-in is in its query support.  This is 
+achieved through mixing into an ActiveRecord model object:
+
+    class Location < ActiveRecord::Base
+       acts_as_mappable
+    end
+
+The plug-in uses the above-mentioned defaults, but can be modified to use 
+different units and a different formulae.  This is done through the :default_units
+and :default_formula keys which accept the same values as mentioned above.
+
+The plug-in creates a calculated column and potentially a calculated condition.  
+By default, these are known as "distance" but this can be changed through the
+:distance_field_name key.  
+
+So, an alternative invocation would look as below:
+
+    class Location < ActiveRecord::Base
+       acts_as_mappable :default_units => :kms, 
+                        :default_formula => :flat, 
+                        :distance_field_name => :distance
+    end
+
+You can also define alternative column names for latitude and longitude using
+the :lat_column_name and :lng_column_name keys.  The defaults are 'lat' and
+'lng' respectively.
+
+Thereafter, a set of finder methods are made available.  Below are the 
+different combinations:
+
+Origin as a two-element array of latititude/longitude:
+
+               find(:all, :origin => [37.792,-122.393])
+
+Origin as a geocodeable string:
+
+               find(:all, :origin => '100 Spear st, San Francisco, CA')
+
+Origin as an object which responds to lat and lng methods, 
+or latitude and longitude methods, or whatever methods you have 
+specified for lng_column_name and lat_column_name:
+
+               find(:all, :origin=>my_store) # my_store.lat and my_store.lng methods exist
+
+Often you will need to find within a certain distance. The prefered syntax is:
+
+    find(:all, :origin => @somewhere, :within => 5)
+    
+. . . however these syntaxes will also work:
+
+    find_within(5, :origin => @somewhere)
+    find(:all, :origin => @somewhere, :conditions => "distance < 5")
+    
+Note however that the third form should be avoided. With either of the first two,
+GeoKit automatically adds a bounding box to speed up the radial query in the database.
+With the third form, it does not.
+
+If you need to combine distance conditions with other conditions, you should do
+so like this:
+
+    find(:all, :origin => @somewhere, :within => 5, :conditions=>['state=?',state])
+
+If :origin is not provided in the finder call, the find method 
+works as normal.  Further, the key is removed
+from the :options hash prior to invoking the superclass behavior.
+
+Other convenience methods work intuitively and are as follows:
+
+    find_within(distance, :origin => @somewhere)
+    find_beyond(distance, :origin => @somewhere)
+    find_closest(:origin => @somewhere)
+    find_farthest(:origin => @somewhere)
+
+where the options respect the defaults, but can be overridden if 
+desired.  
+
+Lastly, if all that is desired is the raw SQL for distance 
+calculations, you can use the following:
+
+    distance_sql(origin, units=default_units, formula=default_formula)
+
+Thereafter, you are free to use it in find_by_sql as you wish.
+
+There are methods available to enable you to get the count based upon
+the find condition that you have provided.  These all work similarly to
+the finders.  So for instance:
+
+    count(:origin, :conditions => "distance < 5")
+    count_within(distance, :origin => @somewhere)
+    count_beyond(distance, :origin => @somewhere)
+
+## FINDING WITHIN A BOUNDING BOX
+If you are displaying points on a map, you probably need to query for whatever falls within the rectangular bounds of the map:
+
+    Store.find :all, :bounds=>[sw_point,ne_point]
+
+The input to :bounds can be array with the two points or a Bounds object. However you provide them, the order should always be the southwest corner, northeast corner of the rectangle. Typically, you will be getting the sw_point and ne_point from a map that is displayed on a web page.
+
+If you need to calculate the bounding box from a point and radius, you can do that:
+
+    bounds=Bounds.from_point_and_radius(home,5)
+    Store.find :all, :bounds=>bounds
+
+## USING INCLUDES
+
+You can use includes along with your distance finders:
+
+    stores=Store.find :all, :origin=>home, :include=>[:reviews,:cities] :within=>5, :order=>'distance'
+
+*However*, ActiveRecord drops the calculated distance column when you use include. So, if you need to
+use the distance column, you'll have to re-calculate it post-query in Ruby:
+
+    stores.sort_by_distance_from(home)
+
+In this case, you may want to just use the bounding box
+condition alone in your SQL (there's no use calculating the distance twice):
+
+    bounds=Bounds.from_point_and_radius(home,5)
+    stores=Store.find :all, :include=>[:reviews,:cities] :bounds=>bounds
+    stores.sort_by_distance_from(home)
+
+## IP GEOCODING
+
+You can obtain the location for an IP at any time using the geocoder
+as in the following example:
+
+    location = IpGeocoder.geocode('12.215.42.19')
+
+where Location is a GeoLoc instance containing the latitude, 
+longitude, city, state, and country code.  Also, the success 
+value is true.
+
+If the IP cannot be geocoded, a GeoLoc instance is returned with a
+success value of false.  
+
+It should be noted that the IP address needs to be visible to the
+Rails application.  In other words, you need to ensure that the 
+requesting IP address is forwarded by any front-end servers that
+are out in front of the Rails app.  Otherwise, the IP will always
+be that of the front-end server.
+
+## IP GEOCODING HELPER
+
+A class method called geocode_ip_address has been mixed into the 
+ActionController::Base.  This enables before_filter style lookup of
+the IP address.  Since it is a filter, it can accept any of the 
+available filter options.
+
+Usage is as below:
+
+    class LocationAwareController < ActionController::Base
+      geocode_ip_address
+    end
+
+A first-time lookup will result in the GeoLoc class being stored
+in the session as :geo_location as well as in a cookie called
+:geo_session.  Subsequent lookups will use the session value if it
+exists or the cookie value if it doesn't exist.  The last resort is
+to make a call to the web service.  Clients are free to manage the
+cookie as they wish.
+
+The intent of this feature is to be able to provide a good guess as
+to a new visitor's location.
+
+## INTEGRATED FIND AND GEOCODING
+
+Geocoding has been integrated with the finders enabling you to pass
+a physical address or an IP address.  This would look the following:
+
+    Location.find_farthest(:origin => '217.15.10.9')
+    Location.find_farthest(:origin => 'Irving, TX')
+
+where the IP or physical address would be geocoded to a location and
+then the resulting latitude and longitude coordinates would be used 
+in the find.  This is not expected to be common usage, but it can be
+done nevertheless.
+
+## ADDRESS GEOCODING
+
+GeoKit can geocode addresses using multiple geocodeing web services.
+Currently, GeoKit supports Google, Yahoo, and Geocoder.us geocoding 
+services. 
+
+These geocoder services are made available through three classes: 
+GoogleGeocoder, YahooGeocoder, and UsGeocoder.  Further, an additional
+geocoder class called MultiGeocoder incorporates an ordered failover
+sequence to increase the probability of successful geocoding.
+
+All classes are called using the following signature:
+
+    include GeoKit::Geocoders
+    location = XxxGeocoder.geocode(address)
+
+where you replace Xxx Geocoder with the appropriate class.  A GeoLoc
+instance is the result of the call.  This class has a "success"
+attribute which will be true if a successful geocoding occurred.  
+If successful, the lat and lng properties will be populated.
+
+Geocoders are named with the naming convention NameGeocoder.  This
+naming convention enables Geocoder to auto-detect its sub-classes
+in order to create methods called name_geocoder(address) so that
+all geocoders are called through the base class.  This is done 
+purely for convenience; the individual geocoder classes are expected
+to be used independently.
+
+The MultiGeocoder class requires the configuration of a provider
+order which dictates what order to use the various geocoders.  Ordering
+is done through the PROVIDER_ORDER constant found in environment.rb.
+
+On installation, this plugin appends a template for your API keys to 
+your environment.rb. 
+
+Make sure your failover configuration matches the usage characteristics 
+of your application -- for example, if you routinely get bogus input to 
+geocode, your code will be much slower if you have to failover among 
+multiple geocoders before determining that the input was in fact bogus. 
+
+The Geocoder.geocode method returns a GeoLoc object. Basic usage:
+
+    loc=Geocoder.geocode('100 Spear St, San Francisco, CA')
+    if loc.success
+      puts loc.lat
+      puts loc.lng
+      puts loc.full_address
+    end
+
+## INTEGRATED FIND WITH ADDRESS GEOCODING
+
+Just has you can pass an IP address directly into an ActiveRecord finder
+as the origin, you can also pass a physical address as the origin:
+
+    Location.find_closest(:origin => '100 Spear st, San Francisco, CA')
+
+where the physical address would be geocoded to a location and then the 
+resulting latitude and longitude coordinates would be used in the 
+find. 
+
+Note that if the address fails to geocode, the find method will raise an 
+ActiveRecord::GeocodeError you must be prepared to catch. Alternatively,
+You can geocoder the address beforehand, and pass the resulting lat/lng
+into the finder if successful.
+
+## Auto Geocoding
+
+If your geocoding needs are simple, you can tell your model to automatically
+geocode itself on create:
+
+    class Store < ActiveRecord::Base
+      acts_as_mappable :auto_geocode=>true
+    end
+
+It takes two optional params:
+
+    class Store < ActiveRecord::Base
+      acts_as_mappable :auto_geocode=>{:field=>:address, :error_message=>'Could not geocode address'}
+    end
+
+. . . which is equivilent to:
+
+    class Store << ActiveRecord::Base
+      acts_as_mappable
+      before_validation_on_create :geocode_address
+
+      private
+      def geocode_address
+        geo=GeoKit::Geocoders::MultiGeocoder.geocode (address)
+        errors.add(:address, "Could not Geocode address") if !geo.success
+        self.lat, self.lng = geo.lat,geo.lng if geo.success
+      end
+    end
+    
+If you need any more complicated geocoding behavior for your model, you should roll your own 
+before_validate callback.
+
+
+## Distances, headings, endpoints, and midpoints
+
+    distance=home.distance_from(work, :units=>:miles)
+    heading=home.heading_to(work) # result is in degrees, 0 is north
+    endpoint=home.endpoint(90,2)  # two miles due east
+    midpoing=home.midpoint_to(work)
+
+## Cool stuff you can do with bounds
+    
+    bounds=Bounds.new(sw_point,ne_point)
+    bounds.contains?(home)
+    puts bounds.center
+    
+
+HOW TO . . .
+=================================================================================
+
+## How to install the GeoKit plugin 
+    cd [APP_ROOT]
+    ruby script/plugin install svn://rubyforge.org/var/svn/geokit/trunk
+      or, to install as an external (your project must be version controlled):
+    ruby script/plugin install -x svn://rubyforge.org/var/svn/geokit/trunk
+
+## How to find all stores within a 10-mile radius of a given lat/lng
+1. ensure your stores table has lat and lng columns with numeric or float 
+   datatypes to store your latitude/longitude
+
+3. use acts_as_mappable on your store model:
+    class Store < ActiveRecord::Base
+       acts_as_mappable
+       ...
+    end
+3. finders now have extra capabilities:
+    Store.find(:all, :origin =>[32.951613,-96.958444], :within=>10)
+
+## How to geocode an address
+
+1. configure your geocoder key(s) in environment.rb
+
+2. also in environment.rb, make sure that PROVIDER_ORDER reflects the 
+   geocoder(s). If you only want to use one geocoder, there should
+   be only one symbol in the array. For example:
+    PROVIDER_ORDER=[:google]
+   
+3. Test it out in script/console
+    include GeoKit::Geocoders
+    res = MultiGeocoder.geocode('100 Spear St, San Francisco, CA')
+    puts res.lat
+    puts res.lng
+    puts res.full_address 
+    ... etc. The return type is GeoLoc, see the API for 
+    all the methods you can call on it.
+
+## How to find all stores within 10 miles of a given address
+
+1. as above, ensure your table has the lat/lng columns, and you've
+   applied acts_as_mappable to the Store model.
+
+2. configure and test out your geocoder, as above
+
+3. pass the address in under the :origin key
+               Store.find(:all, :origin=>'100 Spear st, San Francisco, CA', 
+                          :within=>10)
+
+4. you can also use a zipcode, or anything else that's geocodable:
+               Store.find(:all, :origin=>'94117', 
+                          :conditions=>'distance<10')
+
+## How to sort a query by distance from an origin
+
+You now have access to a 'distance' column, and you can use it
+as you would any other column. For example:
+               Store.find(:all, :origin=>'94117', :order=>'distance')
+
+## How to elements of an array according to distance from a common point
+
+Usually, you can do your sorting in the database as part of your find call.
+If you need to sort things post-query, you can do so:
+
+    stores=Store.find :all
+    stores.sort_by_distance_from(home)
+    puts stores.first.distance
+    
+Obviously, each of the items in the array must have a latitude/longitude so
+they can be sorted by distance.
+
+
+HIGH-LEVEL NOTES ON WHAT'S WHERE
+=================================================================================
+
+acts_as_mappable.rb, as you'd expect, contains the ActsAsMappable
+module which gets mixed into your models to provide the 
+location-based finder goodness.
+
+mappable.rb contains the Mappable module, which provides basic
+distance calculation methods, i.e., calculating the distance
+between two points. 
+
+mappable.rb also contains LatLng, GeoLoc, and Bounds.
+LatLng is a simple container for latitude and longitude, but 
+it's made more powerful by mixing in the above-mentioned Mappable
+module -- therefore, you can calculate easily the distance between two
+LatLng ojbects with distance = first.distance_to(other)
+
+GeoLoc (also in mappable.rb) represents an address or location which
+has been geocoded. You can get the city, zipcode, street address, etc.
+from a GeoLoc object. GeoLoc extends LatLng, so you also get lat/lng
+AND the Mappable modeule goodness for free.
+
+geocoders.rb contains the geocoder classes.
+
+ip_geocode_lookup.rb contains the before_filter helper method which
+enables auto lookup of the requesting IP address.
+
+## IMPORTANT NOTE: We have appended to your environment.rb file
+
+Installation of this plugin has appended an API key template 
+to your environment.rb file. You *must* add your own keys for the various
+geocoding services if you want to use geocoding. If you need to refer to the original
+template again, see the api_keys_template file in the root of the plugin.
diff --git a/vendor/plugins/geokit/Rakefile b/vendor/plugins/geokit/Rakefile
new file mode 100644 (file)
index 0000000..82e289e
--- /dev/null
@@ -0,0 +1,22 @@
+require 'rake'
+require 'rake/testtask'
+require 'rake/rdoctask'
+
+desc 'Default: run unit tests.'
+task :default => :test
+
+desc 'Test the GeoKit plugin.'
+Rake::TestTask.new(:test) do |t|
+  t.libs << 'lib'
+  t.pattern = 'test/**/*_test.rb'
+  t.verbose = true
+end
+
+desc 'Generate documentation for the GeoKit plugin.'
+Rake::RDocTask.new(:rdoc) do |rdoc|
+  rdoc.rdoc_dir = 'rdoc'
+  rdoc.title    = 'GeoKit'
+  rdoc.options << '--line-numbers' << '--inline-source'
+  rdoc.rdoc_files.include('README')
+  rdoc.rdoc_files.include('lib/**/*.rb')
+end
\ No newline at end of file
diff --git a/vendor/plugins/geokit/about.yml b/vendor/plugins/geokit/about.yml
new file mode 100644 (file)
index 0000000..7f759fd
--- /dev/null
@@ -0,0 +1,9 @@
+author:
+  name_1: Bill Eisenhauer
+  homepage_1: http://blog.billeisenhauer.com
+  name_2: Andre Lewis
+  homepage_2: http://www.earthcode.com
+summary: Geo distance calculations, distance calculation query support, geocoding for physical and ip addresses.
+version: 1.0
+rails_version: 1.0+
+license: MIT
\ No newline at end of file
diff --git a/vendor/plugins/geokit/assets/api_keys_template b/vendor/plugins/geokit/assets/api_keys_template
new file mode 100644 (file)
index 0000000..6367a1a
--- /dev/null
@@ -0,0 +1,50 @@
+# These defaults are used in GeoKit::Mappable.distance_to and in acts_as_mappable
+GeoKit::default_units = :miles
+GeoKit::default_formula = :sphere
+
+# This is the timeout value in seconds to be used for calls to the geocoder web
+# services.  For no timeout at all, comment out the setting.  The timeout unit
+# is in seconds. 
+GeoKit::Geocoders::timeout = 3
+
+# These settings are used if web service calls must be routed through a proxy.
+# These setting can be nil if not needed, otherwise, addr and port must be 
+# filled in at a minimum.  If the proxy requires authentication, the username
+# and password can be provided as well.
+GeoKit::Geocoders::proxy_addr = nil
+GeoKit::Geocoders::proxy_port = nil
+GeoKit::Geocoders::proxy_user = nil
+GeoKit::Geocoders::proxy_pass = nil
+
+# This is your yahoo application key for the Yahoo Geocoder.
+# See http://developer.yahoo.com/faq/index.html#appid
+# and http://developer.yahoo.com/maps/rest/V1/geocode.html
+GeoKit::Geocoders::yahoo = 'REPLACE_WITH_YOUR_YAHOO_KEY'
+    
+# This is your Google Maps geocoder key. 
+# See http://www.google.com/apis/maps/signup.html
+# and http://www.google.com/apis/maps/documentation/#Geocoding_Examples
+GeoKit::Geocoders::google = 'REPLACE_WITH_YOUR_GOOGLE_KEY'
+    
+# This is your username and password for geocoder.us.
+# To use the free service, the value can be set to nil or false.  For 
+# usage tied to an account, the value should be set to username:password.
+# See http://geocoder.us
+# and http://geocoder.us/user/signup
+GeoKit::Geocoders::geocoder_us = false 
+
+# This is your authorization key for geocoder.ca.
+# To use the free service, the value can be set to nil or false.  For 
+# usage tied to an account, set the value to the key obtained from
+# Geocoder.ca.
+# See http://geocoder.ca
+# and http://geocoder.ca/?register=1
+GeoKit::Geocoders::geocoder_ca = false
+
+# This is the order in which the geocoders are called in a failover scenario
+# If you only want to use a single geocoder, put a single symbol in the array.
+# Valid symbols are :google, :yahoo, :us, and :ca.
+# Be aware that there are Terms of Use restrictions on how you can use the 
+# various geocoders.  Make sure you read up on relevant Terms of Use for each
+# geocoder you are going to use.
+GeoKit::Geocoders::provider_order = [:google,:us]
\ No newline at end of file
diff --git a/vendor/plugins/geokit/init.rb b/vendor/plugins/geokit/init.rb
new file mode 100644 (file)
index 0000000..d36503e
--- /dev/null
@@ -0,0 +1,13 @@
+# Load modules and classes needed to automatically mix in ActiveRecord and 
+# ActionController helpers.  All other functionality must be explicitly 
+# required.
+require 'geo_kit/defaults'
+require 'geo_kit/mappable'
+require 'geo_kit/acts_as_mappable'
+require 'geo_kit/ip_geocode_lookup'
+
+# Automatically mix in distance finder support into ActiveRecord classes.
+ActiveRecord::Base.send :include, GeoKit::ActsAsMappable
+
+# Automatically mix in ip geocoding helpers into ActionController classes.
+ActionController::Base.send :include, GeoKit::IpGeocodeLookup
diff --git a/vendor/plugins/geokit/install.rb b/vendor/plugins/geokit/install.rb
new file mode 100644 (file)
index 0000000..8263e22
--- /dev/null
@@ -0,0 +1,7 @@
+# Display to the console the contents of the README file.\r
+puts IO.read(File.join(File.dirname(__FILE__), 'README'))\r
+\r
+# Append the contents of api_keys_template to the application's environment.rb file\r
+environment_rb = File.open(File.expand_path(File.join(File.dirname(__FILE__), '../../../config/environment.rb')), "a")\r
+environment_rb.puts IO.read(File.join(File.dirname(__FILE__), '/assets/api_keys_template'))\r
+environment_rb.close\r
diff --git a/vendor/plugins/geokit/lib/geo_kit/acts_as_mappable.rb b/vendor/plugins/geokit/lib/geo_kit/acts_as_mappable.rb
new file mode 100644 (file)
index 0000000..386b05e
--- /dev/null
@@ -0,0 +1,436 @@
+module GeoKit
+  # Contains the class method acts_as_mappable targeted to be mixed into ActiveRecord.
+  # When mixed in, augments find services such that they provide distance calculation
+  # query services.  The find method accepts additional options:
+  #
+  # * :origin - can be 
+  #   1. a two-element array of latititude/longitude -- :origin=>[37.792,-122.393]
+  #   2. a geocodeable string -- :origin=>'100 Spear st, San Francisco, CA'
+  #   3. an object which responds to lat and lng methods, or latitude and longitude methods,
+  #      or whatever methods you have specified for lng_column_name and lat_column_name
+  #
+  # Other finder methods are provided for specific queries.  These are:
+  #
+  # * find_within (alias: find_inside)
+  # * find_beyond (alias: find_outside)
+  # * find_closest (alias: find_nearest)
+  # * find_farthest
+  #
+  # Counter methods are available and work similarly to finders.  
+  #
+  # If raw SQL is desired, the distance_sql method can be used to obtain SQL appropriate
+  # to use in a find_by_sql call.
+  module ActsAsMappable 
+    # Mix below class methods into ActiveRecord.
+    def self.included(base) # :nodoc:
+      base.extend ClassMethods
+    end
+    
+    # Class method to mix into active record.
+    module ClassMethods # :nodoc:
+      # Class method to bring distance query support into ActiveRecord models.  By default
+      # uses :miles for distance units and performs calculations based upon the Haversine
+      # (sphere) formula.  These can be changed by setting GeoKit::default_units and
+      # GeoKit::default_formula.  Also, by default, uses lat, lng, and distance for respective
+      # column names.  All of these can be overridden using the :default_units, :default_formula,
+      # :lat_column_name, :lng_column_name, and :distance_column_name hash keys.
+      # 
+      # Can also use to auto-geocode a specific column on create. Syntax;
+      #   
+      #   acts_as_mappable :auto_geocode=>true
+      # 
+      # By default, it tries to geocode the "address" field. Or, for more customized behavior:
+      #   
+      #   acts_as_mappable :auto_geocode=>{:field=>:address,:error_message=>'bad address'}
+      #   
+      # In both cases, it creates a before_validation_on_create callback to geocode the given column.
+      # For anything more customized, we recommend you forgo the auto_geocode option
+      # and create your own AR callback to handle geocoding.
+      def acts_as_mappable(options = {})
+        # Mix in the module, but ensure to do so just once.
+        return if self.included_modules.include?(GeoKit::ActsAsMappable::InstanceMethods)
+        send :include, GeoKit::ActsAsMappable::InstanceMethods
+        # include the Mappable module.
+        send :include, Mappable
+        
+        # Handle class variables.
+        cattr_accessor :distance_column_name, :default_units, :default_formula, :lat_column_name, :lng_column_name, :qualified_lat_column_name, :qualified_lng_column_name
+        self.distance_column_name = options[:distance_column_name]  || 'distance'
+        self.default_units = options[:default_units] || GeoKit::default_units
+        self.default_formula = options[:default_formula] || GeoKit::default_formula
+        self.lat_column_name = options[:lat_column_name] || 'lat'
+        self.lng_column_name = options[:lng_column_name] || 'lng'
+        self.qualified_lat_column_name = "#{table_name}.#{lat_column_name}"
+        self.qualified_lng_column_name = "#{table_name}.#{lng_column_name}"
+        if options.include?(:auto_geocode) && options[:auto_geocode]
+          # if the form auto_geocode=>true is used, let the defaults take over by suppling an empty hash
+          options[:auto_geocode] = {} if options[:auto_geocode] == true 
+          cattr_accessor :auto_geocode_field, :auto_geocode_error_message
+          self.auto_geocode_field = options[:auto_geocode][:field] || 'address'
+          self.auto_geocode_error_message = options[:auto_geocode][:error_message] || 'could not locate address'
+          
+          # set the actual callback here
+          before_validation_on_create :auto_geocode_address        
+        end
+      end
+    end
+    
+    # this is the callback for auto_geocoding
+    def auto_geocode_address
+      address=self.send(auto_geocode_field)
+      geo=GeoKit::Geocoders::MultiGeocoder.geocode(address)
+  
+      if geo.success
+        self.send("#{lat_column_name}=", geo.lat)
+        self.send("#{lng_column_name}=", geo.lng)
+      else
+        errors.add(auto_geocode_field, auto_geocode_error_message) 
+      end
+      
+      geo.success
+    end
+    
+    # Instance methods to mix into ActiveRecord.
+    module InstanceMethods #:nodoc:    
+      # Mix class methods into module.
+      def self.included(base) # :nodoc:
+        base.extend SingletonMethods
+      end
+      
+      # Class singleton methods to mix into ActiveRecord.
+      module SingletonMethods # :nodoc:
+        # Extends the existing find method in potentially two ways:
+        # - If a mappable instance exists in the options, adds a distance column.
+        # - If a mappable instance exists in the options and the distance column exists in the
+        #   conditions, substitutes the distance sql for the distance column -- this saves
+        #   having to write the gory SQL.
+        def find(*args)
+          prepare_for_find_or_count(:find, args)
+          super(*args)
+        end     
+        
+        # Extends the existing count method by:
+        # - If a mappable instance exists in the options and the distance column exists in the
+        #   conditions, substitutes the distance sql for the distance column -- this saves
+        #   having to write the gory SQL.
+        def count(*args)
+          prepare_for_find_or_count(:count, args)
+          super(*args)
+        end
+        
+        # Finds within a distance radius.
+        def find_within(distance, options={})
+          options[:within] = distance
+          find(:all, options)
+        end
+        alias find_inside find_within
+                
+        # Finds beyond a distance radius.
+        def find_beyond(distance, options={})
+          options[:beyond] = distance
+          find(:all, options)
+        end
+        alias find_outside find_beyond
+        
+        # Finds according to a range.  Accepts inclusive or exclusive ranges.
+        def find_by_range(range, options={})
+          options[:range] = range
+          find(:all, options)
+        end
+        
+        # Finds the closest to the origin.
+        def find_closest(options={})
+          find(:nearest, options)
+        end
+        alias find_nearest find_closest
+        
+        # Finds the farthest from the origin.
+        def find_farthest(options={})
+          find(:farthest, options)
+        end
+
+        # Finds within rectangular bounds (sw,ne).
+        def find_within_bounds(bounds, options={})
+          options[:bounds] = bounds
+          find(:all, options)
+        end
+        
+        # counts within a distance radius.
+        def count_within(distance, options={})
+          options[:within] = distance
+          count(options)
+        end
+        alias count_inside count_within
+
+        # Counts beyond a distance radius.
+        def count_beyond(distance, options={})
+          options[:beyond] = distance
+          count(options)
+        end
+        alias count_outside count_beyond
+        
+        # Counts according to a range.  Accepts inclusive or exclusive ranges.
+        def count_by_range(range, options={})
+          options[:range] = range
+          count(options)
+        end
+
+        # Finds within rectangular bounds (sw,ne).
+        def count_within_bounds(bounds, options={})
+          options[:bounds] = bounds
+          count(options)
+        end
+                
+        # Returns the distance calculation to be used as a display column or a condition.  This
+        # is provide for anyone wanting access to the raw SQL.
+        def distance_sql(origin, units=default_units, formula=default_formula)
+          case formula
+          when :sphere
+            sql = sphere_distance_sql(origin, units)
+          when :flat
+            sql = flat_distance_sql(origin, units)
+          end
+          sql
+        end   
+
+        private
+        
+        # Prepares either a find or a count action by parsing through the options and
+        # conditionally adding to the select clause for finders.
+        def prepare_for_find_or_count(action, args)
+          options = extract_options_from_args!(args)
+          # Obtain items affecting distance condition.
+          origin = extract_origin_from_options(options)
+          units = extract_units_from_options(options)
+          formula = extract_formula_from_options(options)
+          bounds = extract_bounds_from_options(options)
+          # if no explicit bounds were given, try formulating them from the point and distance given
+          bounds = formulate_bounds_from_distance(options, origin, units) unless bounds
+          # Apply select adjustments based upon action.
+          add_distance_to_select(options, origin, units, formula) if origin && action == :find
+          # Apply the conditions for a bounding rectangle if applicable
+          apply_bounds_conditions(options,bounds) if bounds
+          # Apply distance scoping and perform substitutions.
+          apply_distance_scope(options)
+          substitute_distance_in_conditions(options, origin, units, formula) if origin && options.has_key?(:conditions)
+          # Order by scoping for find action.
+          apply_find_scope(args, options) if action == :find
+          # Unfortunatley, we need to do extra work if you use an :include. See the method for more info.
+          handle_order_with_include(options,origin,units,formula) if options.include?(:include) && options.include?(:order) && origin
+          # Restore options minus the extra options that we used for the
+          # GeoKit API.
+          args.push(options)   
+        end
+        
+        # If we're here, it means that 1) an origin argument, 2) an :include, 3) an :order clause were supplied.
+        # Now we have to sub some SQL into the :order clause. The reason is that when you do an :include,
+        # ActiveRecord drops the psuedo-column (specificically, distance) which we supplied for :select. 
+        # So, the 'distance' column isn't available for the :order clause to reference when we use :include.
+        def handle_order_with_include(options, origin, units, formula)
+          # replace the distance_column_name with the distance sql in order clause
+          options[:order].sub!(distance_column_name, distance_sql(origin, units, formula))
+        end
+        
+        # Looks for mapping-specific tokens and makes appropriate translations so that the 
+        # original finder has its expected arguments.  Resets the the scope argument to 
+        # :first and ensures the limit is set to one.
+        def apply_find_scope(args, options)
+          case args.first
+            when :nearest
+              args[0] = :first
+              options[:limit] = 1
+              options[:order] = "#{distance_column_name} ASC"
+            when :farthest
+              args[0] = :first
+              options[:limit] = 1
+              options[:order] = "#{distance_column_name} DESC"
+          end
+        end
+        
+        # If it's a :within query, add a bounding box to improve performance.
+        # This only gets called if a :bounds argument is not otherwise supplied. 
+        def formulate_bounds_from_distance(options, origin, units)
+          distance = options[:within] if options.has_key?(:within)
+          distance = options[:range].last-(options[:range].exclude_end?? 1 : 0) if options.has_key?(:range)
+          if distance
+            res=GeoKit::Bounds.from_point_and_radius(origin,distance,:units=>units)
+          else 
+            nil
+          end
+        end
+        
+        # Replace :within, :beyond and :range distance tokens with the appropriate distance 
+        # where clauses.  Removes these tokens from the options hash.
+        def apply_distance_scope(options)
+          distance_condition = "#{distance_column_name} <= #{options[:within]}" if options.has_key?(:within)
+          distance_condition = "#{distance_column_name} > #{options[:beyond]}" if options.has_key?(:beyond)
+          distance_condition = "#{distance_column_name} >= #{options[:range].first} AND #{distance_column_name} <#{'=' unless options[:range].exclude_end?} #{options[:range].last}" if options.has_key?(:range)
+          [:within, :beyond, :range].each { |option| options.delete(option) } if distance_condition
+          
+          options[:conditions]=augment_conditions(options[:conditions],distance_condition) if distance_condition
+        end
+
+        # This method lets you transparently add a new condition to a query without
+        # worrying about whether it currently has conditions, or what kind of conditions they are
+        # (string or array).
+        # 
+        # Takes the current conditions (which can be an array or a string, or can be nil/false), 
+        # and a SQL string. It inserts the sql into the existing conditions, and returns new conditions
+        # (which can be a string or an array
+        def augment_conditions(current_conditions,sql)
+          if current_conditions && current_conditions.is_a?(String)
+            res="#{current_conditions} AND #{sql}"  
+          elsif current_conditions && current_conditions.is_a?(Array)
+            current_conditions[0]="#{current_conditions[0]} AND #{sql}"
+            res=current_conditions
+          else
+            res=sql
+          end
+          res
+        end
+
+        # Alters the conditions to include rectangular bounds conditions.
+        def apply_bounds_conditions(options,bounds)
+          sw,ne=bounds.sw,bounds.ne
+          lng_sql= bounds.crosses_meridian? ? "#{qualified_lng_column_name}<#{sw.lng} OR #{qualified_lng_column_name}>#{ne.lng}" : "#{qualified_lng_column_name}>#{sw.lng} AND #{qualified_lng_column_name}<#{ne.lng}"
+          bounds_sql="#{qualified_lat_column_name}>#{sw.lat} AND #{qualified_lat_column_name}<#{ne.lat} AND #{lng_sql}"
+          options[:conditions]=augment_conditions(options[:conditions],bounds_sql)          
+        end
+
+        # Extracts the origin instance out of the options if it exists and returns
+        # it.  If there is no origin, looks for latitude and longitude values to 
+        # create an origin.  The side-effect of the method is to remove these 
+        # option keys from the hash.
+        def extract_origin_from_options(options)
+          origin = options.delete(:origin)
+          res = normalize_point_to_lat_lng(origin) if origin
+          res
+        end
+        
+        # Extract the units out of the options if it exists and returns it.  If
+        # there is no :units key, it uses the default.  The side effect of the 
+        # method is to remove the :units key from the options hash.
+        def extract_units_from_options(options)
+          units = options[:units] || default_units
+          options.delete(:units)
+          units
+        end
+        
+        # Extract the formula out of the options if it exists and returns it.  If
+        # there is no :formula key, it uses the default.  The side effect of the 
+        # method is to remove the :formula key from the options hash.
+        def extract_formula_from_options(options)
+          formula = options[:formula] || default_formula
+          options.delete(:formula)
+          formula
+        end
+        
+        def extract_bounds_from_options(options)
+          bounds = options.delete(:bounds)
+          bounds = GeoKit::Bounds.normalize(bounds) if bounds
+        end
+       
+        # Geocode IP address.
+        def geocode_ip_address(origin)
+          geo_location = GeoKit::Geocoders::IpGeocoder.geocode(origin)
+          return geo_location if geo_location.success
+          raise GeoKit::Geocoders::GeocodeError
+        end
+        
+
+        # Given a point in a variety of (an address to geocode,
+        # an array of [lat,lng], or an object with appropriate lat/lng methods, an IP addres)
+        # this method will normalize it into a GeoKit::LatLng instance. The only thing this
+        # method adds on top of LatLng#normalize is handling of IP addresses
+        def normalize_point_to_lat_lng(point)
+          res = geocode_ip_address(point) if point.is_a?(String) && /^(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})?$/.match(point)
+          res = GeoKit::LatLng.normalize(point) unless res
+          res       
+        end
+
+        # Augments the select with the distance SQL.
+        def add_distance_to_select(options, origin, units=default_units, formula=default_formula)
+          if origin
+            distance_selector = distance_sql(origin, units, formula) + " AS #{distance_column_name}"
+            selector = options.has_key?(:select) && options[:select] ? options[:select] : "*"
+            options[:select] = "#{selector}, #{distance_selector}"  
+          end   
+        end
+
+        # Looks for the distance column and replaces it with the distance sql. If an origin was not 
+        # passed in and the distance column exists, we leave it to be flagged as bad SQL by the database.
+        # Conditions are either a string or an array.  In the case of an array, the first entry contains
+        # the condition.
+        def substitute_distance_in_conditions(options, origin, units=default_units, formula=default_formula)
+          original_conditions = options[:conditions]
+          condition = original_conditions.is_a?(String) ? original_conditions : original_conditions.first
+          pattern = Regexp.new("\s*#{distance_column_name}(\s<>=)*")
+          condition = condition.gsub(pattern, distance_sql(origin, units, formula))
+          original_conditions = condition if original_conditions.is_a?(String)
+          original_conditions[0] = condition if original_conditions.is_a?(Array)
+          options[:conditions] = original_conditions
+        end
+        
+        # Returns the distance SQL using the spherical world formula (Haversine).  The SQL is tuned
+        # to the database in use.
+        def sphere_distance_sql(origin, units)
+          lat = deg2rad(origin.lat)
+          lng = deg2rad(origin.lng)
+          multiplier = units_sphere_multiplier(units)
+          case connection.adapter_name.downcase
+          when "mysql"
+            sql=<<-SQL_END 
+                  (ACOS(COS(#{lat})*COS(#{lng})*COS(RADIANS(#{qualified_lat_column_name}))*COS(RADIANS(#{qualified_lng_column_name}))+
+                  COS(#{lat})*SIN(#{lng})*COS(RADIANS(#{qualified_lat_column_name}))*SIN(RADIANS(#{qualified_lng_column_name}))+
+                  SIN(#{lat})*SIN(RADIANS(#{qualified_lat_column_name})))*#{multiplier})
+                  SQL_END
+          when "postgresql"
+            sql=<<-SQL_END 
+                  (ACOS(COS(#{lat})*COS(#{lng})*COS(RADIANS(#{qualified_lat_column_name}))*COS(RADIANS(#{qualified_lng_column_name}))+
+                  COS(#{lat})*SIN(#{lng})*COS(RADIANS(#{qualified_lat_column_name}))*SIN(RADIANS(#{qualified_lng_column_name}))+
+                  SIN(#{lat})*SIN(RADIANS(#{qualified_lat_column_name})))*#{multiplier})
+                  SQL_END
+          else
+            sql = "unhandled #{connection.adapter_name.downcase} adapter"
+          end        
+        end
+        
+        # Returns the distance SQL using the flat-world formula (Phythagorean Theory).  The SQL is tuned
+        # to the database in use.
+        def flat_distance_sql(origin, units)
+          lat_degree_units = units_per_latitude_degree(units)
+          lng_degree_units = units_per_longitude_degree(origin.lat, units)
+          case connection.adapter_name.downcase
+          when "mysql"
+            sql=<<-SQL_END
+                  SQRT(POW(#{lat_degree_units}*(#{origin.lat}-#{qualified_lat_column_name}),2)+
+                  POW(#{lng_degree_units}*(#{origin.lng}-#{qualified_lng_column_name}),2))
+                  SQL_END
+          when "postgresql"
+            sql=<<-SQL_END
+                  SQRT(POW(#{lat_degree_units}*(#{origin.lat}-#{qualified_lat_column_name}),2)+
+                  POW(#{lng_degree_units}*(#{origin.lng}-#{qualified_lng_column_name}),2))
+                  SQL_END
+          else
+            sql = "unhandled #{connection.adapter_name.downcase} adapter"
+          end
+        end
+      end
+    end
+  end
+end
+
+# Extend Array with a sort_by_distance method.
+# This method creates a "distance" attribute on each object, 
+# calculates the distance from the passed origin,
+# and finally sorts the array by the resulting distance.
+class Array
+  def sort_by_distance_from(origin, opts={})
+    distance_attribute_name = opts.delete(:distance_attribute_name) || 'distance'    
+    self.each do |e|
+      e.class.send(:attr_accessor, distance_attribute_name) if !e.respond_to? "#{distance_attribute_name}="
+      e.send("#{distance_attribute_name}=", origin.distance_to(e,opts))
+    end
+    self.sort!{|a,b|a.send(distance_attribute_name) <=> b.send(distance_attribute_name)}
+  end
+end
\ No newline at end of file
diff --git a/vendor/plugins/geokit/lib/geo_kit/defaults.rb b/vendor/plugins/geokit/lib/geo_kit/defaults.rb
new file mode 100644 (file)
index 0000000..e9832c1
--- /dev/null
@@ -0,0 +1,21 @@
+module GeoKit
+  # These defaults are used in GeoKit::Mappable.distance_to and in acts_as_mappable
+  @@default_units = :miles
+  @@default_formula = :sphere
+
+  [:default_units, :default_formula].each do |sym|
+    class_eval <<-EOS, __FILE__, __LINE__
+      def self.#{sym}
+        if defined?(#{sym.to_s.upcase})
+          #{sym.to_s.upcase}
+        else
+          @@#{sym}
+        end
+      end
+
+      def self.#{sym}=(obj)
+        @@#{sym} = obj
+      end
+    EOS
+  end
+end
diff --git a/vendor/plugins/geokit/lib/geo_kit/geocoders.rb b/vendor/plugins/geokit/lib/geo_kit/geocoders.rb
new file mode 100644 (file)
index 0000000..ccf3ab4
--- /dev/null
@@ -0,0 +1,347 @@
+require 'net/http'
+require 'rexml/document'
+require 'yaml'
+require 'timeout'
+
+module GeoKit
+  # Contains a set of geocoders which can be used independently if desired.  The list contains:
+  # 
+  # * Google Geocoder - requires an API key.
+  # * Yahoo Geocoder - requires an API key.
+  # * Geocoder.us - may require authentication if performing more than the free request limit.
+  # * Geocoder.ca - for Canada; may require authentication as well.
+  # * IP Geocoder - geocodes an IP address using hostip.info's web service.
+  # * Multi Geocoder - provides failover for the physical location geocoders.
+  # 
+  # Some configuration is required for these geocoders and can be located in the environment
+  # configuration files.
+  module Geocoders
+    @@proxy_addr = nil
+    @@proxy_port = nil
+    @@proxy_user = nil
+    @@proxy_pass = nil
+    @@timeout = nil    
+    @@yahoo = 'REPLACE_WITH_YOUR_YAHOO_KEY'
+    @@google = 'REPLACE_WITH_YOUR_GOOGLE_KEY'
+    @@geocoder_us = false
+    @@geocoder_ca = false
+    @@provider_order = [:google,:us]
+    
+    [:yahoo, :google, :geocoder_us, :geocoder_ca, :provider_order, :timeout, 
+     :proxy_addr, :proxy_port, :proxy_user, :proxy_pass].each do |sym|
+      class_eval <<-EOS, __FILE__, __LINE__
+        def self.#{sym}
+          if defined?(#{sym.to_s.upcase})
+            #{sym.to_s.upcase}
+          else
+            @@#{sym}
+          end
+        end
+
+        def self.#{sym}=(obj)
+          @@#{sym} = obj
+        end
+      EOS
+    end
+    
+    # Error which is thrown in the event a geocoding error occurs.
+    class GeocodeError < StandardError; end
+    
+    # The Geocoder base class which defines the interface to be used by all
+    # other geocoders.
+    class Geocoder   
+      # Main method which calls the do_geocode template method which subclasses
+      # are responsible for implementing.  Returns a populated GeoLoc or an
+      # empty one with a failed success code.
+      def self.geocode(address)  
+        res = do_geocode(address)
+        return res.success ? res : GeoLoc.new
+      end  
+      
+      # Call the geocoder service using the timeout if configured.
+      def self.call_geocoder_service(url)
+        timeout(GeoKit::Geocoders::timeout) { return self.do_get(url) } if GeoKit::Geocoders::timeout        
+        return self.do_get(url)
+      rescue TimeoutError
+        return nil  
+      end
+
+      protected
+
+      def self.logger() RAILS_DEFAULT_LOGGER; end
+      
+      private
+      
+      # Wraps the geocoder call around a proxy if necessary.
+      def self.do_get(url)     
+        return Net::HTTP::Proxy(GeoKit::Geocoders::proxy_addr, GeoKit::Geocoders::proxy_port,
+            GeoKit::Geocoders::proxy_user, GeoKit::Geocoders::proxy_pass).get_response(URI.parse(url))          
+      end
+      
+      # Adds subclass' geocode method making it conveniently available through 
+      # the base class.
+      def self.inherited(clazz)
+        class_name = clazz.name.split('::').last
+        src = <<-END_SRC
+          def self.#{class_name.underscore}(address)
+            #{class_name}.geocode(address)
+          end
+        END_SRC
+        class_eval(src)
+      end
+    end
+    
+    # Geocoder CA geocoder implementation.  Requires the GeoKit::Geocoders::GEOCODER_CA variable to
+    # contain true or false based upon whether authentication is to occur.  Conforms to the 
+    # interface set by the Geocoder class.
+    #
+    # Returns a response like:
+    # <?xml version="1.0" encoding="UTF-8" ?>
+    # <geodata>
+    #   <latt>49.243086</latt>
+    #   <longt>-123.153684</longt>
+    # </geodata>
+    class CaGeocoder < Geocoder
+
+      private
+
+      # Template method which does the geocode lookup.
+      def self.do_geocode(address)
+        raise ArgumentError('Geocoder.ca requires a GeoLoc argument') unless address.is_a?(GeoLoc)
+        url = construct_request(address)
+        res = self.call_geocoder_service(url)
+        return GeoLoc.new if !res.is_a?(Net::HTTPSuccess)
+        xml = res.body
+        logger.debug "Geocoder.ca geocoding. Address: #{address}. Result: #{xml}"
+        # Parse the document.
+        doc = REXML::Document.new(xml)    
+        address.lat = doc.elements['//latt'].text
+        address.lng = doc.elements['//longt'].text
+        address.success = true
+        return address
+      rescue
+        logger.error "Caught an error during Geocoder.ca geocoding call: "+$!
+        return GeoLoc.new  
+      end  
+
+      # Formats the request in the format acceptable by the CA geocoder.
+      def self.construct_request(location)
+        url = ""
+        url += add_ampersand(url) + "stno=#{location.street_number}" if location.street_address
+        url += add_ampersand(url) + "addresst=#{CGI.escape(location.street_name)}" if location.street_address
+        url += add_ampersand(url) + "city=#{CGI.escape(location.city)}" if location.city
+        url += add_ampersand(url) + "prov=#{location.state}" if location.state
+        url += add_ampersand(url) + "postal=#{location.zip}" if location.zip
+        url += add_ampersand(url) + "auth=#{GeoKit::Geocoders::geocoder_ca}" if GeoKit::Geocoders::geocoder_ca
+        url += add_ampersand(url) + "geoit=xml"
+        'http://geocoder.ca/?' + url
+      end
+
+      def self.add_ampersand(url)
+        url && url.length > 0 ? "&" : ""
+      end
+    end    
+    
+    # Google geocoder implementation.  Requires the GeoKit::Geocoders::GOOGLE variable to
+    # contain a Google API key.  Conforms to the interface set by the Geocoder class.
+    class GoogleGeocoder < Geocoder
+
+      private 
+
+      # Template method which does the geocode lookup.
+      def self.do_geocode(address)
+        address_str = address.is_a?(GeoLoc) ? address.to_geocodeable_s : address
+        res = self.call_geocoder_service("http://maps.google.com/maps/geo?q=#{CGI.escape(address_str)}&output=xml&key=#{GeoKit::Geocoders::google}&oe=utf-8")
+#        res = Net::HTTP.get_response(URI.parse("http://maps.google.com/maps/geo?q=#{CGI.escape(address_str)}&output=xml&key=#{GeoKit::Geocoders::google}&oe=utf-8"))
+        return GeoLoc.new if !res.is_a?(Net::HTTPSuccess)
+        xml=res.body
+        logger.debug "Google geocoding. Address: #{address}. Result: #{xml}"
+        doc=REXML::Document.new(xml)
+
+        if doc.elements['//kml/Response/Status/code'].text == '200'
+          res = GeoLoc.new
+          coordinates=doc.elements['//coordinates'].text.to_s.split(',')
+
+          #basics
+          res.lat=coordinates[1]
+          res.lng=coordinates[0]
+          res.country_code=doc.elements['//CountryNameCode'].text
+          res.provider='google'
+
+          #extended -- false if not not available
+          res.city = doc.elements['//LocalityName'].text if doc.elements['//LocalityName']
+          res.state = doc.elements['//AdministrativeAreaName'].text if doc.elements['//AdministrativeAreaName']
+          res.full_address = doc.elements['//address'].text if doc.elements['//address'] # google provides it
+          res.zip = doc.elements['//PostalCodeNumber'].text if doc.elements['//PostalCodeNumber']
+          res.street_address = doc.elements['//ThoroughfareName'].text if doc.elements['//ThoroughfareName']
+          # Translate accuracy into Yahoo-style token address, street, zip, zip+4, city, state, country
+          # For Google, 1=low accuracy, 8=high accuracy
+          address_details=doc.elements['//AddressDetails','urn:oasis:names:tc:ciq:xsdschema:xAL:2.0']
+          accuracy = address_details ? address_details.attributes['Accuracy'].to_i : 0
+          res.precision=%w{unknown country state state city zip zip+4 street address}[accuracy]
+          res.success=true
+          
+          return res
+        else 
+          logger.info "Google was unable to geocode address: "+address
+          return GeoLoc.new
+        end
+
+        rescue
+          logger.error "Caught an error during Google geocoding call: "+$!
+          return GeoLoc.new
+      end  
+    end
+    
+    # Provides geocoding based upon an IP address.  The underlying web service is a hostip.info
+    # which sources their data through a combination of publicly available information as well
+    # as community contributions.
+    class IpGeocoder < Geocoder 
+
+      private 
+
+      # Given an IP address, returns a GeoLoc instance which contains latitude,
+      # longitude, city, and country code.  Sets the success attribute to false if the ip 
+      # parameter does not match an ip address.  
+      def self.do_geocode(ip)
+        return GeoLoc.new unless /^(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})?$/.match(ip)
+        url = "http://api.hostip.info/get_html.php?ip=#{ip}&position=true"
+        response = self.call_geocoder_service(url)
+        response.is_a?(Net::HTTPSuccess) ? parse_body(response.body) : GeoLoc.new
+      rescue
+        logger.error "Caught an error during HostIp geocoding call: "+$!
+        return GeoLoc.new
+      end
+
+      # Converts the body to YAML since its in the form of:
+      #
+      # Country: UNITED STATES (US)
+      # City: Sugar Grove, IL
+      # Latitude: 41.7696
+      # Longitude: -88.4588
+      #
+      # then instantiates a GeoLoc instance to populate with location data.
+      def self.parse_body(body) # :nodoc:
+        yaml = YAML.load(body)
+        res = GeoLoc.new
+        res.provider = 'hostip'
+        res.city, res.state = yaml['City'].split(', ')
+        country, res.country_code = yaml['Country'].split(' (')
+        res.lat = yaml['Latitude'] 
+        res.lng = yaml['Longitude']
+        res.country_code.chop!
+        res.success = res.city != "(Private Address)"
+        res
+      end
+    end
+    
+    # Geocoder Us geocoder implementation.  Requires the GeoKit::Geocoders::GEOCODER_US variable to
+    # contain true or false based upon whether authentication is to occur.  Conforms to the 
+    # interface set by the Geocoder class.
+    class UsGeocoder < Geocoder
+
+      private
+
+      # For now, the geocoder_method will only geocode full addresses -- not zips or cities in isolation
+      def self.do_geocode(address)
+        address_str = address.is_a?(GeoLoc) ? address.to_geocodeable_s : address
+        url = "http://"+(GeoKit::Geocoders::geocoder_us || '')+"geocoder.us/service/csv/geocode?address=#{CGI.escape(address_str)}"
+        res = self.call_geocoder_service(url)
+        return GeoLoc.new if !res.is_a?(Net::HTTPSuccess)
+        data = res.body
+        logger.debug "Geocoder.us geocoding. Address: #{address}. Result: #{data}"
+        array = data.chomp.split(',')
+
+        if array.length == 6  
+          res=GeoLoc.new
+          res.lat,res.lng,res.street_address,res.city,res.state,res.zip=array
+          res.country_code='US'
+          res.success=true 
+          return res
+        else 
+          logger.info "geocoder.us was unable to geocode address: "+address
+          return GeoLoc.new      
+        end
+        rescue 
+          logger.error "Caught an error during geocoder.us geocoding call: "+$!
+          return GeoLoc.new
+      end
+    end
+    
+    # Yahoo geocoder implementation.  Requires the GeoKit::Geocoders::YAHOO variable to
+    # contain a Yahoo API key.  Conforms to the interface set by the Geocoder class.
+    class YahooGeocoder < Geocoder
+
+      private 
+
+      # Template method which does the geocode lookup.
+      def self.do_geocode(address)
+        address_str = address.is_a?(GeoLoc) ? address.to_geocodeable_s : address
+        url="http://api.local.yahoo.com/MapsService/V1/geocode?appid=#{GeoKit::Geocoders::yahoo}&location=#{CGI.escape(address_str)}"
+        res = self.call_geocoder_service(url)
+        return GeoLoc.new if !res.is_a?(Net::HTTPSuccess)
+        xml = res.body
+        doc = REXML::Document.new(xml)
+        logger.debug "Yahoo geocoding. Address: #{address}. Result: #{xml}"
+
+        if doc.elements['//ResultSet']
+          res=GeoLoc.new
+
+          #basic      
+          res.lat=doc.elements['//Latitude'].text
+          res.lng=doc.elements['//Longitude'].text
+          res.country_code=doc.elements['//Country'].text
+          res.provider='yahoo'  
+
+          #extended - false if not available
+          res.city=doc.elements['//City'].text if doc.elements['//City'] && doc.elements['//City'].text != nil
+          res.state=doc.elements['//State'].text if doc.elements['//State'] && doc.elements['//State'].text != nil
+          res.zip=doc.elements['//Zip'].text if doc.elements['//Zip'] && doc.elements['//Zip'].text != nil
+          res.street_address=doc.elements['//Address'].text if doc.elements['//Address'] && doc.elements['//Address'].text != nil
+          res.precision=doc.elements['//Result'].attributes['precision'] if doc.elements['//Result']
+          res.success=true
+          return res
+        else 
+          logger.info "Yahoo was unable to geocode address: "+address
+          return GeoLoc.new
+        end   
+
+        rescue 
+          logger.info "Caught an error during Yahoo geocoding call: "+$!
+          return GeoLoc.new
+      end
+    end
+    
+    # Provides methods to geocode with a variety of geocoding service providers, plus failover
+    # among providers in the order you configure.
+    # 
+    # Goal:
+    # - homogenize the results of multiple geocoders
+    # 
+    # Limitations:
+    # - currently only provides the first result. Sometimes geocoders will return multiple results.
+    # - currently discards the "accuracy" component of the geocoding calls
+    class MultiGeocoder < Geocoder 
+      private
+
+      # This method will call one or more geocoders in the order specified in the 
+      # configuration until one of the geocoders work.
+      # 
+      # The failover approach is crucial for production-grade apps, but is rarely used.
+      # 98% of your geocoding calls will be successful with the first call  
+      def self.do_geocode(address)
+        GeoKit::Geocoders::provider_order.each do |provider|
+          begin
+            klass = GeoKit::Geocoders.const_get "#{provider.to_s.capitalize}Geocoder"
+            res = klass.send :geocode, address
+            return res if res.success
+          rescue
+            logger.error("Something has gone very wrong during geocoding, OR you have configured an invalid class name in GeoKit::Geocoders::provider_order. Address: #{address}. Provider: #{provider}")
+          end
+        end
+        # If we get here, we failed completely.
+        GeoLoc.new
+      end
+    end   
+  end
+end
\ No newline at end of file
diff --git a/vendor/plugins/geokit/lib/geo_kit/ip_geocode_lookup.rb b/vendor/plugins/geokit/lib/geo_kit/ip_geocode_lookup.rb
new file mode 100644 (file)
index 0000000..f43edf4
--- /dev/null
@@ -0,0 +1,46 @@
+require 'yaml'
+
+module GeoKit 
+  # Contains a class method geocode_ip_address which can be used to enable automatic geocoding
+  # for request IP addresses.  The geocoded information is stored in a cookie and in the 
+  # session to minimize web service calls.  The point of the helper is to enable location-based
+  # websites to have a best-guess for new visitors.
+  module IpGeocodeLookup
+    # Mix below class methods into ActionController.
+    def self.included(base) # :nodoc:
+      base.extend ClassMethods
+    end
+    
+    # Class method to mix into active record.
+    module ClassMethods # :nodoc:
+      def geocode_ip_address(filter_options = {})
+        before_filter :store_ip_location
+      end
+    end
+    private   
+         
+    # Places the IP address' geocode location into the session if it 
+    # can be found.  Otherwise, looks for a geo location cookie and
+    # uses that value.  The last resort is to call the web service to
+    # get the value.
+    def store_ip_location
+      session[:geo_location] ||= retrieve_location_from_cookie_or_service
+      cookies[:geo_location] = { :value => session[:geo_location].to_yaml, :expires => 30.days.from_now } if session[:geo_location]
+    end    
+    
+    # Uses the stored location value from the cookie if it exists.  If
+    # no cookie exists, calls out to the web service to get the location. 
+    def retrieve_location_from_cookie_or_service
+      return YAML.load(cookies[:geo_location]) if cookies[:geo_location]
+      location = Geocoders::IpGeocoder.geocode(get_ip_address)
+      return location.success ? location : nil
+    end
+    
+    # Returns the real ip address, though this could be the localhost ip
+    # address.  No special handling here anymore.
+    def get_ip_address
+      request.remote_ip
+    end
+  end
+end
\ No newline at end of file
diff --git a/vendor/plugins/geokit/lib/geo_kit/mappable.rb b/vendor/plugins/geokit/lib/geo_kit/mappable.rb
new file mode 100644 (file)
index 0000000..a7a1030
--- /dev/null
@@ -0,0 +1,431 @@
+require 'geo_kit/defaults'
+
+module GeoKit
+  # Contains class and instance methods providing distance calcuation services.  This
+  # module is meant to be mixed into classes containing lat and lng attributes where
+  # distance calculation is desired.  
+  # 
+  # At present, two forms of distance calculations are provided:
+  # 
+  # * Pythagorean Theory (flat Earth) - which assumes the world is flat and loses accuracy over long distances.
+  # * Haversine (sphere) - which is fairly accurate, but at a performance cost.
+  # 
+  # Distance units supported are :miles and :kms.
+  module Mappable
+    PI_DIV_RAD = 0.0174
+    KMS_PER_MILE = 1.609
+    EARTH_RADIUS_IN_MILES = 3963.19
+    EARTH_RADIUS_IN_KMS = EARTH_RADIUS_IN_MILES * KMS_PER_MILE
+    MILES_PER_LATITUDE_DEGREE = 69.1
+    KMS_PER_LATITUDE_DEGREE = MILES_PER_LATITUDE_DEGREE * KMS_PER_MILE
+    LATITUDE_DEGREES = EARTH_RADIUS_IN_MILES / MILES_PER_LATITUDE_DEGREE  
+    
+    # Mix below class methods into the includer.
+    def self.included(receiver) # :nodoc:
+      receiver.extend ClassMethods
+    end   
+    
+    module ClassMethods #:nodoc:
+      # Returns the distance between two points.  The from and to parameters are
+      # required to have lat and lng attributes.  Valid options are:
+      # :units - valid values are :miles or :kms (GeoKit::default_units is the default)
+      # :formula - valid values are :flat or :sphere (GeoKit::default_formula is the default)
+      def distance_between(from, to, options={})
+        from=GeoKit::LatLng.normalize(from)
+        to=GeoKit::LatLng.normalize(to)
+        units = options[:units] || GeoKit::default_units
+        formula = options[:formula] || GeoKit::default_formula
+        case formula
+        when :sphere          
+          units_sphere_multiplier(units) * 
+              Math.acos( Math.sin(deg2rad(from.lat)) * Math.sin(deg2rad(to.lat)) + 
+              Math.cos(deg2rad(from.lat)) * Math.cos(deg2rad(to.lat)) * 
+              Math.cos(deg2rad(to.lng) - deg2rad(from.lng)))   
+        when :flat
+          Math.sqrt((units_per_latitude_degree(units)*(from.lat-to.lat))**2 + 
+              (units_per_longitude_degree(from.lat, units)*(from.lng-to.lng))**2)
+        end
+      end
+
+      # Returns heading in degrees (0 is north, 90 is east, 180 is south, etc)
+      # from the first point to the second point. Typicaly, the instance methods will be used 
+      # instead of this method.
+      def heading_between(from,to)
+        from=GeoKit::LatLng.normalize(from)
+        to=GeoKit::LatLng.normalize(to)
+
+        d_lng=deg2rad(to.lng-from.lng)
+        from_lat=deg2rad(from.lat)
+        to_lat=deg2rad(to.lat) 
+        y=Math.sin(d_lng) * Math.cos(to_lat)
+        x=Math.cos(from_lat)*Math.sin(to_lat)-Math.sin(from_lat)*Math.cos(to_lat)*Math.cos(d_lng)
+        heading=to_heading(Math.atan2(y,x))
+      end
+  
+      # Given a start point, distance, and heading (in degrees), provides
+      # an endpoint. Returns a LatLng instance. Typically, the instance method
+      # will be used instead of this method.
+      def endpoint(start,heading, distance, options={})
+        units = options[:units] || GeoKit::default_units
+        radius = units == :miles ? EARTH_RADIUS_IN_MILES : EARTH_RADIUS_IN_KMS
+        start=GeoKit::LatLng.normalize(start)        
+        lat=deg2rad(start.lat)
+        lng=deg2rad(start.lng)
+        heading=deg2rad(heading)
+        distance=distance.to_f
+        
+        end_lat=Math.asin(Math.sin(lat)*Math.cos(distance/radius) +
+                          Math.cos(lat)*Math.sin(distance/radius)*Math.cos(heading))
+
+        end_lng=lng+Math.atan2(Math.sin(heading)*Math.sin(distance/radius)*Math.cos(lat),
+                               Math.cos(distance/radius)-Math.sin(lat)*Math.sin(end_lat))
+
+        LatLng.new(rad2deg(end_lat),rad2deg(end_lng))
+      end
+
+      # Returns the midpoint, given two points. Returns a LatLng. 
+      # Typically, the instance method will be used instead of this method.
+      # Valid option:
+      #   :units - valid values are :miles or :kms (:miles is the default)
+      def midpoint_between(from,to,options={})
+        from=GeoKit::LatLng.normalize(from)
+
+        units = options[:units] || GeoKit::default_units
+        
+        heading=from.heading_to(to)
+        distance=from.distance_to(to,options)
+        midpoint=from.endpoint(heading,distance/2,options)
+      end
+  
+      # Geocodes a location using the multi geocoder.
+      def geocode(location)
+        res = Geocoders::MultiGeocoder.geocode(location)
+        return res if res.success
+        raise GeoKit::Geocoders::GeocodeError      
+      end
+    
+      protected
+    
+      def deg2rad(degrees)
+        degrees.to_f / 180.0 * Math::PI
+      end
+      
+      def rad2deg(rad)
+        rad.to_f * 180.0 / Math::PI 
+      end
+      
+      def to_heading(rad)
+        (rad2deg(rad)+360)%360
+      end
+
+      # Returns the multiplier used to obtain the correct distance units.
+      def units_sphere_multiplier(units)
+        units == :miles ? EARTH_RADIUS_IN_MILES : EARTH_RADIUS_IN_KMS
+      end
+
+      # Returns the number of units per latitude degree.
+      def units_per_latitude_degree(units)
+        units == :miles ? MILES_PER_LATITUDE_DEGREE : KMS_PER_LATITUDE_DEGREE
+      end
+    
+      # Returns the number units per longitude degree.
+      def units_per_longitude_degree(lat, units)
+        miles_per_longitude_degree = (LATITUDE_DEGREES * Math.cos(lat * PI_DIV_RAD)).abs
+        units == :miles ? miles_per_longitude_degree : miles_per_longitude_degree * KMS_PER_MILE
+      end  
+    end
+  
+    # -----------------------------------------------------------------------------------------------
+    # Instance methods below here
+    # -----------------------------------------------------------------------------------------------
+  
+    # Extracts a LatLng instance. Use with models that are acts_as_mappable
+    def to_lat_lng
+      return self if instance_of?(GeoKit::LatLng) || instance_of?(GeoKit::GeoLoc)
+      return LatLng.new(send(self.class.lat_column_name),send(self.class.lng_column_name)) if self.class.respond_to?(:acts_as_mappable)
+      return nil
+    end
+
+    # Returns the distance from another point.  The other point parameter is
+    # required to have lat and lng attributes.  Valid options are:
+    # :units - valid values are :miles or :kms (:miles is the default)
+    # :formula - valid values are :flat or :sphere (:sphere is the default)
+    def distance_to(other, options={})
+      self.class.distance_between(self, other, options)
+    end  
+    alias distance_from distance_to
+
+    # Returns heading in degrees (0 is north, 90 is east, 180 is south, etc)
+    # to the given point. The given point can be a LatLng or a string to be Geocoded 
+    def heading_to(other)
+      self.class.heading_between(self,other)
+    end
+
+    # Returns heading in degrees (0 is north, 90 is east, 180 is south, etc)
+    # FROM the given point. The given point can be a LatLng or a string to be Geocoded 
+    def heading_from(other)
+      self.class.heading_between(other,self)
+    end
+    # Returns the endpoint, given a heading (in degrees) and distance.  
+    # Valid option:
+    # :units - valid values are :miles or :kms (:miles is the default)
+    def endpoint(heading,distance,options={})
+      self.class.endpoint(self,heading,distance,options)  
+    end
+
+    # Returns the midpoint, given another point on the map.  
+    # Valid option:
+    # :units - valid values are :miles or :kms (:miles is the default)    
+    def midpoint_to(other, options={})
+      self.class.midpoint_between(self,other,options)
+    end
+    
+  end
+
+  class LatLng 
+    include Mappable
+
+    attr_accessor :lat, :lng
+
+    # Accepts latitude and longitude or instantiates an empty instance
+    # if lat and lng are not provided. Converted to floats if provided
+    def initialize(lat=nil, lng=nil)
+      lat = lat.to_f if lat && !lat.is_a?(Numeric)
+      lng = lng.to_f if lng && !lng.is_a?(Numeric)
+      @lat = lat
+      @lng = lng
+    end 
+
+    # Latitude attribute setter; stored as a float.
+    def lat=(lat)
+      @lat = lat.to_f if lat
+    end
+
+    # Longitude attribute setter; stored as a float;
+    def lng=(lng)
+      @lng=lng.to_f if lng
+    end  
+
+    # Returns the lat and lng attributes as a comma-separated string.
+    def ll
+      "#{lat},#{lng}"
+    end
+    
+    #returns a string with comma-separated lat,lng values
+    def to_s
+      ll
+    end
+  
+    #returns a two-element array
+    def to_a
+      [lat,lng]
+    end
+    # Returns true if the candidate object is logically equal.  Logical equivalence
+    # is true if the lat and lng attributes are the same for both objects.
+    def ==(other)
+      other.is_a?(LatLng) ? self.lat == other.lat && self.lng == other.lng : false
+    end
+    
+    # A *class* method to take anything which can be inferred as a point and generate
+    # a LatLng from it. You should use this anything you're not sure what the input is,
+    # and want to deal with it as a LatLng if at all possible. Can take:
+    #  1) two arguments (lat,lng)
+    #  2) a string in the format "37.1234,-129.1234" or "37.1234 -129.1234"
+    #  3) a string which can be geocoded on the fly
+    #  4) an array in the format [37.1234,-129.1234]
+    #  5) a LatLng or GeoLoc (which is just passed through as-is)
+    #  6) anything which acts_as_mappable -- a LatLng will be extracted from it
+    def self.normalize(thing,other=nil)
+      # if an 'other' thing is supplied, normalize the input by creating an array of two elements
+      thing=[thing,other] if other
+      
+      if thing.is_a?(String)
+        thing.strip!
+        if match=thing.match(/(\-?\d+\.?\d*)[, ] ?(\-?\d+\.?\d*)$/)
+          return GeoKit::LatLng.new(match[1],match[2])
+        else
+          res = GeoKit::Geocoders::MultiGeocoder.geocode(thing)
+          return res if res.success
+          raise GeoKit::Geocoders::GeocodeError  
+        end
+      elsif thing.is_a?(Array) && thing.size==2
+        return GeoKit::LatLng.new(thing[0],thing[1])
+      elsif thing.is_a?(LatLng) # will also be true for GeoLocs
+        return thing
+      elsif thing.class.respond_to?(:acts_as_mappable) && thing.class.respond_to?(:distance_column_name)
+        return thing.to_lat_lng
+      end
+      
+      throw ArgumentError.new("#{thing} (#{thing.class}) cannot be normalized to a LatLng. We tried interpreting it as an array, string, Mappable, etc., but no dice.")
+    end
+    
+  end
+
+  # This class encapsulates the result of a geocoding call
+  # It's primary purpose is to homogenize the results of multiple
+  # geocoding providers. It also provides some additional functionality, such as 
+  # the "full address" method for geocoders that do not provide a 
+  # full address in their results (for example, Yahoo), and the "is_us" method.
+  class GeoLoc < LatLng
+    # Location attributes.  Full address is a concatenation of all values.  For example:
+    # 100 Spear St, San Francisco, CA, 94101, US
+    attr_accessor :street_address, :city, :state, :zip, :country_code, :full_address
+    # Attributes set upon return from geocoding.  Success will be true for successful
+    # geocode lookups.  The provider will be set to the name of the providing geocoder.
+    # Finally, precision is an indicator of the accuracy of the geocoding.
+    attr_accessor :success, :provider, :precision
+    # Street number and street name are extracted from the street address attribute.
+    attr_reader :street_number, :street_name
+
+    # Constructor expects a hash of symbols to correspond with attributes.
+    def initialize(h={})
+      @street_address=h[:street_address] 
+      @city=h[:city] 
+      @state=h[:state] 
+      @zip=h[:zip] 
+      @country_code=h[:country_code] 
+      @success=false
+      @precision='unknown'
+      super(h[:lat],h[:lng])
+    end
+
+    # Returns true if geocoded to the United States.
+    def is_us?
+      country_code == 'US'
+    end
+
+    # full_address is provided by google but not by yahoo. It is intended that the google
+    # geocoding method will provide the full address, whereas for yahoo it will be derived
+    # from the parts of the address we do have.
+    def full_address
+      @full_address ? @full_address : to_geocodeable_s
+    end
+
+    # Extracts the street number from the street address if the street address
+    # has a value.
+    def street_number
+      street_address[/(\d*)/] if street_address
+    end
+
+    # Returns the street name portion of the street address.
+    def street_name
+       street_address[street_number.length, street_address.length].strip if street_address
+    end
+
+    # gives you all the important fields as key-value pairs
+    def hash
+      res={}
+      [:success,:lat,:lng,:country_code,:city,:state,:zip,:street_address,:provider,:full_address,:is_us?,:ll,:precision].each { |s| res[s] = self.send(s.to_s) }
+      res
+    end
+    alias to_hash hash
+
+    # Sets the city after capitalizing each word within the city name.
+    def city=(city)
+      @city = city.titleize if city
+    end
+
+    # Sets the street address after capitalizing each word within the street address.
+    def street_address=(address)
+      @street_address = address.titleize if address
+    end  
+
+    # Returns a comma-delimited string consisting of the street address, city, state,
+    # zip, and country code.  Only includes those attributes that are non-blank.
+    def to_geocodeable_s
+      a=[street_address, city, state, zip, country_code].compact
+      a.delete_if { |e| !e || e == '' }
+      a.join(', ')      
+    end
+
+    # Returns a string representation of the instance.
+    def to_s
+      "Provider: #{provider}\n Street: #{street_address}\nCity: #{city}\nState: #{state}\nZip: #{zip}\nLatitude: #{lat}\nLongitude: #{lng}\nCountry: #{country_code}\nSuccess: #{success}"
+    end
+  end
+  
+  # Bounds represents a rectangular bounds, defined by the SW and NE corners
+  class Bounds
+    # sw and ne are LatLng objects
+    attr_accessor :sw, :ne
+    
+    # provide sw and ne to instantiate a new Bounds instance
+    def initialize(sw,ne)
+      raise ArguementError if !(sw.is_a?(GeoKit::LatLng) && ne.is_a?(GeoKit::LatLng))
+      @sw,@ne=sw,ne
+    end
+    
+    #returns the a single point which is the center of the rectangular bounds
+    def center
+      @sw.midpoint_to(@ne)
+    end
+  
+    # a simple string representation:sw,ne
+    def to_s
+      "#{@sw.to_s},#{@ne.to_s}"   
+    end
+    
+    # a two-element array of two-element arrays: sw,ne
+    def to_a
+      [@sw.to_a, @ne.to_a]
+    end
+    
+    # Returns true if the bounds contain the passed point.
+    # allows for bounds which cross the meridian
+    def contains?(point)
+      point=GeoKit::LatLng.normalize(point)
+      res = point.lat > @sw.lat && point.lat < @ne.lat
+      if crosses_meridian?
+        res &= point.lng < @ne.lng || point.lng > @sw.lng
+      else
+        res &= point.lng < @ne.lng && point.lng > @sw.lng
+      end
+      res
+    end
+    
+    # returns true if the bounds crosses the international dateline
+    def crosses_meridian?
+      @sw.lng > @ne.lng 
+    end
+
+    # Returns true if the candidate object is logically equal.  Logical equivalence
+    # is true if the lat and lng attributes are the same for both objects.
+    def ==(other)
+      other.is_a?(Bounds) ? self.sw == other.sw && self.ne == other.ne : false
+    end
+    
+    class <<self
+      
+      # returns an instance of bounds which completely encompases the given circle
+      def from_point_and_radius(point,radius,options={})
+        point=LatLng.normalize(point)
+        p0=point.endpoint(0,radius,options)
+        p90=point.endpoint(90,radius,options)
+        p180=point.endpoint(180,radius,options)
+        p270=point.endpoint(270,radius,options)
+        sw=GeoKit::LatLng.new(p180.lat,p270.lng)
+        ne=GeoKit::LatLng.new(p0.lat,p90.lng)
+        GeoKit::Bounds.new(sw,ne)
+      end
+      
+      # Takes two main combinations of arguements to create a bounds:
+      # point,point   (this is the only one which takes two arguments
+      # [point,point]
+      # . . . where a point is anything LatLng#normalize can handle (which is quite a lot)
+      #
+      # NOTE: everything combination is assumed to pass points in the order sw, ne
+      def normalize (thing,other=nil)   
+        # maybe this will be simple -- an actual bounds object is passed, and we can all go home
+        return thing if thing.is_a? Bounds
+        
+        # no? OK, if there's no "other," the thing better be a two-element array        
+        thing,other=thing if !other && thing.is_a?(Array) && thing.size==2
+
+        # Now that we're set with a thing and another thing, let LatLng do the heavy lifting.
+        # Exceptions may be thrown
+        Bounds.new(GeoKit::LatLng.normalize(thing),GeoKit::LatLng.normalize(other))
+      end
+    end
+  end
+end
\ No newline at end of file
diff --git a/vendor/plugins/geokit/test/acts_as_mappable_test.rb b/vendor/plugins/geokit/test/acts_as_mappable_test.rb
new file mode 100644 (file)
index 0000000..58991eb
--- /dev/null
@@ -0,0 +1,481 @@
+require 'rubygems'
+require 'mocha'
+require File.join(File.dirname(__FILE__), 'test_helper')
+
+GeoKit::Geocoders::provider_order=[:google,:us]
+
+# Uses defaults
+class Company < ActiveRecord::Base #:nodoc: all
+  has_many :locations
+end
+
+# Configures everything.
+class Location < ActiveRecord::Base #:nodoc: all
+  belongs_to :company
+  acts_as_mappable
+end
+
+# for auto_geocode
+class Store < ActiveRecord::Base
+  acts_as_mappable :auto_geocode=>true
+end
+
+# Uses deviations from conventions.
+class CustomLocation < ActiveRecord::Base #:nodoc: all
+  belongs_to :company
+  acts_as_mappable :distance_column_name => 'dist', 
+                   :default_units => :kms, 
+                   :default_formula => :flat, 
+                   :lat_column_name => 'latitude', 
+                   :lng_column_name => 'longitude'
+                   
+  def to_s
+    "lat: #{latitude} lng: #{longitude} dist: #{dist}"
+  end
+end
+
+class ActsAsMappableTest < Test::Unit::TestCase #:nodoc: all
+    
+  LOCATION_A_IP = "217.10.83.5"  
+    
+  #self.fixture_path = File.dirname(__FILE__) + '/fixtures'  
+  #self.fixture_path = RAILS_ROOT + '/test/fixtures/'
+  #puts "Rails Path #{RAILS_ROOT}"
+  #puts "Fixture Path: #{self.fixture_path}"
+  #self.fixture_path = ' /Users/bill_eisenhauer/Projects/geokit_test/test/fixtures/'
+  fixtures :companies, :locations, :custom_locations, :stores
+
+  def setup
+    @location_a = GeoKit::GeoLoc.new
+    @location_a.lat = 32.918593
+    @location_a.lng = -96.958444
+    @location_a.city = "Irving"
+    @location_a.state = "TX"
+    @location_a.country_code = "US"
+    @location_a.success = true
+    
+    @sw = GeoKit::LatLng.new(32.91663,-96.982841)
+    @ne = GeoKit::LatLng.new(32.96302,-96.919495)
+    @bounds_center=GeoKit::LatLng.new((@sw.lat+@ne.lat)/2,(@sw.lng+@ne.lng)/2)
+    
+    @starbucks = companies(:starbucks)
+    @loc_a = locations(:a)
+    @custom_loc_a = custom_locations(:a)
+    @loc_e = locations(:e)
+    @custom_loc_e = custom_locations(:e)    
+  end
+  
+  def test_override_default_units_the_hard_way
+    Location.default_units = :kms
+    locations = Location.find(:all, :origin => @loc_a, :conditions => "distance < 3.97")
+    assert_equal 5, locations.size   
+    locations = Location.count(:origin => @loc_a, :conditions => "distance < 3.97")
+    assert_equal 5, locations
+    Location.default_units = :miles
+  end
+  
+  def test_include
+    locations = Location.find(:all, :origin => @loc_a, :include => :company, :conditions => "company_id = 1")
+    assert !locations.empty?
+    assert_equal 1, locations[0].company.id
+    assert_equal 'Starbucks', locations[0].company.name
+  end
+  
+  def test_distance_between_geocoded
+    GeoKit::Geocoders::MultiGeocoder.expects(:geocode).with("Irving, TX").returns(@location_a)
+    GeoKit::Geocoders::MultiGeocoder.expects(:geocode).with("San Francisco, CA").returns(@location_a)
+    assert_equal 0, Location.distance_between("Irving, TX", "San Francisco, CA") 
+  end
+  
+  def test_distance_to_geocoded
+    GeoKit::Geocoders::MultiGeocoder.expects(:geocode).with("Irving, TX").returns(@location_a)
+    assert_equal 0, @custom_loc_a.distance_to("Irving, TX") 
+  end
+  
+  def test_distance_to_geocoded_error
+    GeoKit::Geocoders::MultiGeocoder.expects(:geocode).with("Irving, TX").returns(GeoKit::GeoLoc.new)
+    assert_raise(GeoKit::Geocoders::GeocodeError) { @custom_loc_a.distance_to("Irving, TX")  }
+  end
+  
+  def test_custom_attributes_distance_calculations
+    assert_equal 0, @custom_loc_a.distance_to(@loc_a)
+    assert_equal 0, CustomLocation.distance_between(@custom_loc_a, @loc_a)
+  end
+  
+  def test_distance_column_in_select
+    locations = Location.find(:all, :origin => @loc_a, :order => "distance ASC")
+    assert_equal 6, locations.size
+    assert_equal 0, @loc_a.distance_to(locations.first)
+    assert_in_delta 3.97, @loc_a.distance_to(locations.last, :units => :miles, :formula => :sphere), 0.01
+  end
+  
+  def test_find_with_distance_condition
+    locations = Location.find(:all, :origin => @loc_a, :conditions => "distance < 3.97")
+    assert_equal 5, locations.size
+    locations = Location.count(:origin => @loc_a, :conditions => "distance < 3.97")
+    assert_equal 5, locations
+  end 
+  
+  def test_find_with_distance_condition_with_units_override
+    locations = Location.find(:all, :origin => @loc_a, :units => :kms, :conditions => "distance < 6.387")
+    assert_equal 5, locations.size
+    locations = Location.count(:origin => @loc_a, :units => :kms, :conditions => "distance < 6.387")
+    assert_equal 5, locations
+  end
+  
+  def test_find_with_distance_condition_with_formula_override
+    locations = Location.find(:all, :origin => @loc_a, :formula => :flat, :conditions => "distance < 6.387")
+    assert_equal 6, locations.size
+    locations = Location.count(:origin => @loc_a, :formula => :flat, :conditions => "distance < 6.387")
+    assert_equal 6, locations
+  end
+  
+  def test_find_within
+    locations = Location.find_within(3.97, :origin => @loc_a)
+    assert_equal 5, locations.size 
+    locations = Location.count_within(3.97, :origin => @loc_a)
+    assert_equal 5, locations   
+  end
+  
+  def test_find_within_with_token
+    locations = Location.find(:all, :within => 3.97, :origin => @loc_a)
+    assert_equal 5, locations.size    
+    locations = Location.count(:within => 3.97, :origin => @loc_a)
+    assert_equal 5, locations
+  end
+  
+  def test_find_within_with_coordinates
+    locations = Location.find_within(3.97, :origin =>[@loc_a.lat,@loc_a.lng])
+    assert_equal 5, locations.size    
+    locations = Location.count_within(3.97, :origin =>[@loc_a.lat,@loc_a.lng])
+    assert_equal 5, locations
+  end
+  
+  def test_find_with_compound_condition
+    locations = Location.find(:all, :origin => @loc_a, :conditions => "distance < 5 and city = 'Coppell'")
+    assert_equal 2, locations.size
+    locations = Location.count(:origin => @loc_a, :conditions => "distance < 5 and city = 'Coppell'")
+    assert_equal 2, locations
+  end
+  
+  def test_find_with_secure_compound_condition
+    locations = Location.find(:all, :origin => @loc_a, :conditions => ["distance < ? and city = ?", 5, 'Coppell'])
+    assert_equal 2, locations.size
+    locations = Location.count(:origin => @loc_a, :conditions => ["distance < ? and city = ?", 5, 'Coppell'])
+    assert_equal 2, locations
+  end
+  
+  def test_find_beyond
+    locations = Location.find_beyond(3.95, :origin => @loc_a)
+    assert_equal 1, locations.size    
+    locations = Location.count_beyond(3.95, :origin => @loc_a)
+    assert_equal 1, locations
+  end
+  
+  def test_find_beyond_with_token
+    locations = Location.find(:all, :beyond => 3.95, :origin => @loc_a)
+    assert_equal 1, locations.size    
+    locations = Location.count(:beyond => 3.95, :origin => @loc_a)
+    assert_equal 1, locations
+  end
+  
+  def test_find_beyond_with_coordinates
+    locations = Location.find_beyond(3.95, :origin =>[@loc_a.lat, @loc_a.lng])
+    assert_equal 1, locations.size    
+    locations = Location.count_beyond(3.95, :origin =>[@loc_a.lat, @loc_a.lng])
+    assert_equal 1, locations
+  end
+  
+  def test_find_range_with_token
+    locations = Location.find(:all, :range => 0..10, :origin => @loc_a)
+    assert_equal 6, locations.size
+    locations = Location.count(:range => 0..10, :origin => @loc_a)
+    assert_equal 6, locations
+  end
+  
+  def test_find_range_with_token_with_conditions
+    locations = Location.find(:all, :origin => @loc_a, :range => 0..10, :conditions => ["city = ?", 'Coppell'])
+    assert_equal 2, locations.size
+    locations = Location.count(:origin => @loc_a, :range => 0..10, :conditions => ["city = ?", 'Coppell'])
+    assert_equal 2, locations
+  end
+  
+  def test_find_range_with_token_excluding_end
+    locations = Location.find(:all, :range => 0...10, :origin => @loc_a)
+    assert_equal 6, locations.size
+    locations = Location.count(:range => 0...10, :origin => @loc_a)
+    assert_equal 6, locations
+  end
+  
+  def test_find_nearest
+    assert_equal @loc_a, Location.find_nearest(:origin => @loc_a)
+  end
+  
+  def test_find_nearest_through_find
+     assert_equal @loc_a, Location.find(:nearest, :origin => @loc_a)
+  end
+  
+  def test_find_nearest_with_coordinates
+    assert_equal @loc_a, Location.find_nearest(:origin =>[@loc_a.lat, @loc_a.lng])
+  end
+  
+  def test_find_farthest
+    assert_equal @loc_e, Location.find_farthest(:origin => @loc_a)
+  end
+  
+  def test_find_farthest_through_find
+    assert_equal @loc_e, Location.find(:farthest, :origin => @loc_a)
+  end
+  
+  def test_find_farthest_with_coordinates
+    assert_equal @loc_e, Location.find_farthest(:origin =>[@loc_a.lat, @loc_a.lng])
+  end
+  
+  def test_scoped_distance_column_in_select
+    locations = @starbucks.locations.find(:all, :origin => @loc_a, :order => "distance ASC")
+    assert_equal 5, locations.size
+    assert_equal 0, @loc_a.distance_to(locations.first)
+    assert_in_delta 3.97, @loc_a.distance_to(locations.last, :units => :miles, :formula => :sphere), 0.01
+  end
+  
+  def test_scoped_find_with_distance_condition
+    locations = @starbucks.locations.find(:all, :origin => @loc_a, :conditions => "distance < 3.97")
+    assert_equal 4, locations.size
+    locations = @starbucks.locations.count(:origin => @loc_a, :conditions => "distance < 3.97")
+    assert_equal 4, locations
+  end 
+  
+  def test_scoped_find_within
+    locations = @starbucks.locations.find_within(3.97, :origin => @loc_a)
+    assert_equal 4, locations.size    
+    locations = @starbucks.locations.count_within(3.97, :origin => @loc_a)
+    assert_equal 4, locations
+  end
+  
+  def test_scoped_find_with_compound_condition
+    locations = @starbucks.locations.find(:all, :origin => @loc_a, :conditions => "distance < 5 and city = 'Coppell'")
+    assert_equal 2, locations.size
+    locations = @starbucks.locations.count( :origin => @loc_a, :conditions => "distance < 5 and city = 'Coppell'")
+    assert_equal 2, locations
+  end
+  
+  def test_scoped_find_beyond
+    locations = @starbucks.locations.find_beyond(3.95, :origin => @loc_a)
+    assert_equal 1, locations.size 
+    locations = @starbucks.locations.count_beyond(3.95, :origin => @loc_a)
+    assert_equal 1, locations   
+  end
+  
+  def test_scoped_find_nearest
+    assert_equal @loc_a, @starbucks.locations.find_nearest(:origin => @loc_a)
+  end
+  
+  def test_scoped_find_farthest
+    assert_equal @loc_e, @starbucks.locations.find_farthest(:origin => @loc_a)
+  end  
+  
+  def test_ip_geocoded_distance_column_in_select
+    GeoKit::Geocoders::IpGeocoder.expects(:geocode).with(LOCATION_A_IP).returns(@location_a)
+    locations = Location.find(:all, :origin => LOCATION_A_IP, :order => "distance ASC")
+    assert_equal 6, locations.size
+    assert_equal 0, @loc_a.distance_to(locations.first)
+    assert_in_delta 3.97, @loc_a.distance_to(locations.last, :units => :miles, :formula => :sphere), 0.01
+  end
+  
+  def test_ip_geocoded_find_with_distance_condition
+    GeoKit::Geocoders::IpGeocoder.expects(:geocode).with(LOCATION_A_IP).returns(@location_a)
+    locations = Location.find(:all, :origin => LOCATION_A_IP, :conditions => "distance < 3.97")
+    assert_equal 5, locations.size
+    GeoKit::Geocoders::IpGeocoder.expects(:geocode).with(LOCATION_A_IP).returns(@location_a)
+    locations = Location.count(:origin => LOCATION_A_IP, :conditions => "distance < 3.97")
+    assert_equal 5, locations
+  end 
+  
+  def test_ip_geocoded_find_within
+    GeoKit::Geocoders::IpGeocoder.expects(:geocode).with(LOCATION_A_IP).returns(@location_a)
+    locations = Location.find_within(3.97, :origin => LOCATION_A_IP)
+    assert_equal 5, locations.size    
+    GeoKit::Geocoders::IpGeocoder.expects(:geocode).with(LOCATION_A_IP).returns(@location_a)
+    locations = Location.count_within(3.97, :origin => LOCATION_A_IP)
+    assert_equal 5, locations
+  end
+  
+  def test_ip_geocoded_find_with_compound_condition
+    GeoKit::Geocoders::IpGeocoder.expects(:geocode).with(LOCATION_A_IP).returns(@location_a)
+    locations = Location.find(:all, :origin => LOCATION_A_IP, :conditions => "distance < 5 and city = 'Coppell'")
+    assert_equal 2, locations.size
+    GeoKit::Geocoders::IpGeocoder.expects(:geocode).with(LOCATION_A_IP).returns(@location_a)
+    locations = Location.count(:origin => LOCATION_A_IP, :conditions => "distance < 5 and city = 'Coppell'")
+    assert_equal 2, locations
+  end
+  
+  def test_ip_geocoded_find_with_secure_compound_condition
+    GeoKit::Geocoders::IpGeocoder.expects(:geocode).with(LOCATION_A_IP).returns(@location_a)
+    locations = Location.find(:all, :origin => LOCATION_A_IP, :conditions => ["distance < ? and city = ?", 5, 'Coppell'])
+    assert_equal 2, locations.size
+    GeoKit::Geocoders::IpGeocoder.expects(:geocode).with(LOCATION_A_IP).returns(@location_a)
+    locations = Location.count(:origin => LOCATION_A_IP, :conditions => ["distance < ? and city = ?", 5, 'Coppell'])
+    assert_equal 2, locations
+  end
+  
+  def test_ip_geocoded_find_beyond
+    GeoKit::Geocoders::IpGeocoder.expects(:geocode).with(LOCATION_A_IP).returns(@location_a)
+    locations = Location.find_beyond(3.95, :origin => LOCATION_A_IP)
+    assert_equal 1, locations.size    
+    GeoKit::Geocoders::IpGeocoder.expects(:geocode).with(LOCATION_A_IP).returns(@location_a)
+    locations = Location.count_beyond(3.95, :origin => LOCATION_A_IP)
+    assert_equal 1, locations
+  end
+  
+  def test_ip_geocoded_find_nearest
+    GeoKit::Geocoders::IpGeocoder.expects(:geocode).with(LOCATION_A_IP).returns(@location_a)
+    assert_equal @loc_a, Location.find_nearest(:origin => LOCATION_A_IP)
+  end
+  
+  def test_ip_geocoded_find_farthest
+    GeoKit::Geocoders::IpGeocoder.expects(:geocode).with(LOCATION_A_IP).returns(@location_a)
+    assert_equal @loc_e, Location.find_farthest(:origin => LOCATION_A_IP)
+  end
+  
+  def test_ip_geocoder_exception
+    GeoKit::Geocoders::IpGeocoder.expects(:geocode).with('127.0.0.1').returns(GeoKit::GeoLoc.new)
+    assert_raises GeoKit::Geocoders::GeocodeError do
+      Location.find_farthest(:origin => '127.0.0.1')
+    end
+  end
+  
+  def test_address_geocode
+    GeoKit::Geocoders::MultiGeocoder.expects(:geocode).with('Irving, TX').returns(@location_a)  
+    locations = Location.find(:all, :origin => 'Irving, TX', :conditions => ["distance < ? and city = ?", 5, 'Coppell'])
+    assert_equal 2, locations.size
+  end
+  
+  def test_find_with_custom_distance_condition
+    locations = CustomLocation.find(:all, :origin => @loc_a, :conditions => "dist < 3.97")
+    assert_equal 5, locations.size 
+    locations = CustomLocation.count(:origin => @loc_a, :conditions => "dist < 3.97")
+    assert_equal 5, locations
+  end  
+  
+  def test_find_with_custom_distance_condition_using_custom_origin
+    locations = CustomLocation.find(:all, :origin => @custom_loc_a, :conditions => "dist < 3.97")
+    assert_equal 5, locations.size 
+    locations = CustomLocation.count(:origin => @custom_loc_a, :conditions => "dist < 3.97")
+    assert_equal 5, locations
+  end
+  
+  def test_find_within_with_custom
+    locations = CustomLocation.find_within(3.97, :origin => @loc_a)
+    assert_equal 5, locations.size    
+    locations = CustomLocation.count_within(3.97, :origin => @loc_a)
+    assert_equal 5, locations
+  end
+  
+  def test_find_within_with_coordinates_with_custom
+    locations = CustomLocation.find_within(3.97, :origin =>[@loc_a.lat, @loc_a.lng])
+    assert_equal 5, locations.size    
+    locations = CustomLocation.count_within(3.97, :origin =>[@loc_a.lat, @loc_a.lng])
+    assert_equal 5, locations
+  end
+  
+  def test_find_with_compound_condition_with_custom
+    locations = CustomLocation.find(:all, :origin => @loc_a, :conditions => "dist < 5 and city = 'Coppell'")
+    assert_equal 1, locations.size
+    locations = CustomLocation.count(:origin => @loc_a, :conditions => "dist < 5 and city = 'Coppell'")
+    assert_equal 1, locations
+  end
+  
+  def test_find_with_secure_compound_condition_with_custom
+    locations = CustomLocation.find(:all, :origin => @loc_a, :conditions => ["dist < ? and city = ?", 5, 'Coppell'])
+    assert_equal 1, locations.size
+    locations = CustomLocation.count(:origin => @loc_a, :conditions => ["dist < ? and city = ?", 5, 'Coppell'])
+    assert_equal 1, locations
+  end
+  
+  def test_find_beyond_with_custom
+    locations = CustomLocation.find_beyond(3.95, :origin => @loc_a)
+    assert_equal 1, locations.size  
+    locations = CustomLocation.count_beyond(3.95, :origin => @loc_a)
+    assert_equal 1, locations  
+  end
+  
+  def test_find_beyond_with_coordinates_with_custom
+    locations = CustomLocation.find_beyond(3.95, :origin =>[@loc_a.lat, @loc_a.lng])
+    assert_equal 1, locations.size    
+    locations = CustomLocation.count_beyond(3.95, :origin =>[@loc_a.lat, @loc_a.lng])
+    assert_equal 1, locations
+  end
+  
+  def test_find_nearest_with_custom
+    assert_equal @custom_loc_a, CustomLocation.find_nearest(:origin => @loc_a)
+  end
+  
+  def test_find_nearest_with_coordinates_with_custom
+    assert_equal @custom_loc_a, CustomLocation.find_nearest(:origin =>[@loc_a.lat, @loc_a.lng])
+  end
+  
+  def test_find_farthest_with_custom
+    assert_equal @custom_loc_e, CustomLocation.find_farthest(:origin => @loc_a)
+  end
+  
+  def test_find_farthest_with_coordinates_with_custom
+    assert_equal @custom_loc_e, CustomLocation.find_farthest(:origin =>[@loc_a.lat, @loc_a.lng])
+  end
+  
+  def test_find_with_array_origin
+    locations = Location.find(:all, :origin =>[@loc_a.lat,@loc_a.lng], :conditions => "distance < 3.97")
+    assert_equal 5, locations.size
+    locations = Location.count(:origin =>[@loc_a.lat,@loc_a.lng], :conditions => "distance < 3.97")
+    assert_equal 5, locations
+  end
+
+
+  # Bounding box tests
+
+  def test_find_within_bounds
+    locations = Location.find_within_bounds([@sw,@ne])
+    assert_equal 2, locations.size
+    locations = Location.count_within_bounds([@sw,@ne])
+    assert_equal 2, locations
+  end
+
+  def test_find_within_bounds_ordered_by_distance
+    locations = Location.find_within_bounds([@sw,@ne], :origin=>@bounds_center, :order=>'distance asc')
+    assert_equal locations[0], locations(:d)
+    assert_equal locations[1], locations(:a)
+  end
+  
+  def test_find_within_bounds_with_token
+    locations = Location.find(:all, :bounds=>[@sw,@ne])
+    assert_equal 2, locations.size
+    locations = Location.count(:bounds=>[@sw,@ne])
+    assert_equal 2, locations  
+  end
+
+  def test_find_within_bounds_with_string_conditions
+    locations = Location.find(:all, :bounds=>[@sw,@ne], :conditions=>"id !=#{locations(:a).id}")
+    assert_equal 1, locations.size
+  end
+
+  def test_find_within_bounds_with_array_conditions
+    locations = Location.find(:all, :bounds=>[@sw,@ne], :conditions=>["id != ?", locations(:a).id])
+    assert_equal 1, locations.size
+  end
+
+  def test_auto_geocode
+    GeoKit::Geocoders::MultiGeocoder.expects(:geocode).with("Irving, TX").returns(@location_a)
+    store=Store.new(:address=>'Irving, TX')
+    store.save
+    assert_equal store.lat,@location_a.lat  
+    assert_equal store.lng,@location_a.lng
+    assert_equal 0, store.errors.size
+  end
+
+  def test_auto_geocode_failure
+    GeoKit::Geocoders::MultiGeocoder.expects(:geocode).with("BOGUS").returns(GeoKit::GeoLoc.new)
+    store=Store.new(:address=>'BOGUS')
+    store.save
+    assert store.new_record?
+    assert_equal 1, store.errors.size
+  end
+end
diff --git a/vendor/plugins/geokit/test/base_geocoder_test.rb b/vendor/plugins/geokit/test/base_geocoder_test.rb
new file mode 100644 (file)
index 0000000..b51a739
--- /dev/null
@@ -0,0 +1,57 @@
+require 'test/unit'
+require 'net/http'
+require 'rubygems'
+require 'mocha'
+require File.join(File.dirname(__FILE__), '../../../../config/environment')
+
+
+class MockSuccess < Net::HTTPSuccess #:nodoc: all
+  def initialize
+  end
+end
+
+class MockFailure < Net::HTTPServiceUnavailable #:nodoc: all
+  def initialize
+  end
+end
+
+# Base class for testing geocoders.
+class BaseGeocoderTest < Test::Unit::TestCase #:nodoc: all
+
+  # Defines common test fixtures.
+  def setup
+    @address = 'San Francisco, CA'    
+    @full_address = '100 Spear St, San Francisco, CA, 94105-1522, US'   
+    @full_address_short_zip = '100 Spear St, San Francisco, CA, 94105, US' 
+    
+    @success = GeoKit::GeoLoc.new({:city=>"SAN FRANCISCO", :state=>"CA", :country_code=>"US", :lat=>37.7742, :lng=>-122.417068})
+    @success.success = true    
+  end  
+  
+  def test_timeout_call_web_service
+    GeoKit::Geocoders::Geocoder.class_eval do
+      def self.do_get(url)
+        sleep(2)
+      end
+    end
+    url = "http://www.anything.com"
+    GeoKit::Geocoders::timeout = 1
+    assert_nil GeoKit::Geocoders::Geocoder.call_geocoder_service(url)    
+  end
+  
+  def test_successful_call_web_service
+    url = "http://www.anything.com"
+    GeoKit::Geocoders::Geocoder.expects(:do_get).with(url).returns("SUCCESS")
+    assert_equal "SUCCESS", GeoKit::Geocoders::Geocoder.call_geocoder_service(url)
+  end
+  
+  def test_find_geocoder_methods
+    public_methods = GeoKit::Geocoders::Geocoder.public_methods
+    assert public_methods.include?("yahoo_geocoder")
+    assert public_methods.include?("google_geocoder")
+    assert public_methods.include?("ca_geocoder")
+    assert public_methods.include?("us_geocoder")
+    assert public_methods.include?("multi_geocoder")
+    assert public_methods.include?("ip_geocoder")
+  end
+end
\ No newline at end of file
diff --git a/vendor/plugins/geokit/test/bounds_test.rb b/vendor/plugins/geokit/test/bounds_test.rb
new file mode 100644 (file)
index 0000000..4cabfde
--- /dev/null
@@ -0,0 +1,75 @@
+$LOAD_PATH.unshift File.join('..', 'lib')
+require 'geo_kit/mappable'
+require 'test/unit'
+
+class BoundsTest < Test::Unit::TestCase #:nodoc: all
+  
+  def setup
+    # This is the area in Texas
+    @sw = GeoKit::LatLng.new(32.91663,-96.982841)
+    @ne = GeoKit::LatLng.new(32.96302,-96.919495)
+    @bounds=GeoKit::Bounds.new(@sw,@ne) 
+    @loc_a=GeoKit::LatLng.new(32.918593,-96.958444) # inside bounds    
+    @loc_b=GeoKit::LatLng.new(32.914144,-96.958444) # outside bouds
+    
+    # this is a cross-meridan area
+    @cross_meridian=GeoKit::Bounds.normalize([30,170],[40,-170])
+    @inside_cm=GeoKit::LatLng.new(35,175)
+    @inside_cm_2=GeoKit::LatLng.new(35,-175)
+    @east_of_cm=GeoKit::LatLng.new(35,-165)
+    @west_of_cm=GeoKit::LatLng.new(35,165)
+
+  end  
+
+  def test_equality
+    assert_equal GeoKit::Bounds.new(@sw,@ne), GeoKit::Bounds.new(@sw,@ne)
+  end  
+  
+  def test_normalize
+    res=GeoKit::Bounds.normalize(@sw,@ne)
+    assert_equal res,GeoKit::Bounds.new(@sw,@ne)     
+    res=GeoKit::Bounds.normalize([@sw,@ne])
+    assert_equal res,GeoKit::Bounds.new(@sw,@ne)
+    res=GeoKit::Bounds.normalize([@sw.lat,@sw.lng],[@ne.lat,@ne.lng])
+    assert_equal res,GeoKit::Bounds.new(@sw,@ne)
+    res=GeoKit::Bounds.normalize([[@sw.lat,@sw.lng],[@ne.lat,@ne.lng]])
+    assert_equal res,GeoKit::Bounds.new(@sw,@ne)
+  end
+  
+  def test_point_inside_bounds
+    assert @bounds.contains?(@loc_a)
+  end
+
+  def test_point_outside_bounds
+    assert !@bounds.contains?(@loc_b) 
+  end  
+
+  def test_point_inside_bounds_cross_meridian
+    assert @cross_meridian.contains?(@inside_cm)
+    assert @cross_meridian.contains?(@inside_cm_2)
+  end
+
+  def test_point_outside_bounds_cross_meridian
+    assert !@cross_meridian.contains?(@east_of_cm)
+    assert !@cross_meridian.contains?(@west_of_cm)
+  end    
+  
+  def test_center
+    assert_in_delta 32.939828,@bounds.center.lat,0.00005
+    assert_in_delta -96.9511763,@bounds.center.lng,0.00005
+  end
+
+  def test_center_cross_meridian
+    assert_in_delta 35.41160, @cross_meridian.center.lat,0.00005
+    assert_in_delta 179.38112, @cross_meridian.center.lng,0.00005
+  end  
+  
+  def test_creation_from_circle
+    bounds=GeoKit::Bounds.from_point_and_radius([32.939829, -96.951176],2.5)
+    inside=GeoKit::LatLng.new 32.9695270000,-96.9901590000
+    outside=GeoKit::LatLng.new 32.8951550000,-96.9584440000
+    assert bounds.contains?(inside)
+    assert !bounds.contains?(outside)
+  end
+  
+end
\ No newline at end of file
diff --git a/vendor/plugins/geokit/test/ca_geocoder_test.rb b/vendor/plugins/geokit/test/ca_geocoder_test.rb
new file mode 100644 (file)
index 0000000..9d797ce
--- /dev/null
@@ -0,0 +1,41 @@
+require File.join(File.dirname(__FILE__), 'base_geocoder_test')
+
+GeoKit::Geocoders::geocoder_ca = "SOMEKEYVALUE"
+
+class CaGeocoderTest < BaseGeocoderTest #:nodoc: all
+  
+  CA_SUCCESS=<<-EOF
+  <?xml version="1.0" encoding="UTF-8" ?>
+  <geodata><latt>49.243086</latt><longt>-123.153684</longt></geodata>  
+  EOF
+  
+  def setup
+    @ca_full_hash = {:street_address=>"2105 West 32nd Avenue",:city=>"Vancouver", :state=>"BC"}
+    @ca_full_loc = GeoKit::GeoLoc.new(@ca_full_hash)
+  end  
+  
+  def test_geocoder_with_geo_loc_with_account
+    response = MockSuccess.new
+    response.expects(:body).returns(CA_SUCCESS)
+    url = "http://geocoder.ca/?stno=2105&addresst=West+32nd+Avenue&city=Vancouver&prov=BC&auth=SOMEKEYVALUE&geoit=xml"
+    GeoKit::Geocoders::CaGeocoder.expects(:call_geocoder_service).with(url).returns(response)
+    verify(GeoKit::Geocoders::CaGeocoder.geocode(@ca_full_loc))    
+  end
+  
+  def test_service_unavailable
+    response = MockFailure.new
+    #Net::HTTP.expects(:get_response).with(URI.parse("http://geocoder.ca/?stno=2105&addresst=West+32nd+Avenue&city=Vancouver&prov=BC&auth=SOMEKEYVALUE&geoit=xml")).returns(response)  
+    url = "http://geocoder.ca/?stno=2105&addresst=West+32nd+Avenue&city=Vancouver&prov=BC&auth=SOMEKEYVALUE&geoit=xml" 
+    GeoKit::Geocoders::CaGeocoder.expects(:call_geocoder_service).with(url).returns(response)
+    assert !GeoKit::Geocoders::CaGeocoder.geocode(@ca_full_loc).success   
+  end  
+  
+  private
+  
+  def verify(location)
+    assert_equal "BC", location.state
+    assert_equal "Vancouver", location.city 
+    assert_equal "49.243086,-123.153684", location.ll 
+    assert !location.is_us? 
+  end
+end
\ No newline at end of file
diff --git a/vendor/plugins/geokit/test/fixtures/companies.yml b/vendor/plugins/geokit/test/fixtures/companies.yml
new file mode 100644 (file)
index 0000000..d48a2e8
--- /dev/null
@@ -0,0 +1,7 @@
+starbucks:
+  id: 1
+  name: Starbucks
+
+barnes_and_noble:
+  id: 2
+  name: Barnes & Noble
\ No newline at end of file
diff --git a/vendor/plugins/geokit/test/fixtures/custom_locations.yml b/vendor/plugins/geokit/test/fixtures/custom_locations.yml
new file mode 100644 (file)
index 0000000..f5a1e92
--- /dev/null
@@ -0,0 +1,54 @@
+a:
+  id: 1
+  company_id: 1
+  street: 7979 N MacArthur Blvd
+  city: Irving
+  state: TX
+  postal_code: 75063
+  latitude: 32.918593
+  longitude: -96.958444
+b:
+  id: 2
+  company_id: 1
+  street: 7750 N Macarthur Blvd # 160
+  city: Irving
+  state: TX
+  postal_code: 75063
+  latitude: 32.914144
+  longitude: -96.958444
+c:
+  id: 3
+  company_id: 1
+  street: 5904 N Macarthur Blvd # 160
+  city: Irving
+  state: TX
+  postal_code: 75039
+  latitude: 32.895155
+  longitude: -96.958444
+d:
+  id: 4
+  company_id: 1
+  street: 817 S Macarthur Blvd # 145
+  city: Coppell
+  state: TX
+  postal_code: 75019
+  latitude: 32.951613
+  longitude: -96.958444
+e:
+  id: 5
+  company_id: 1
+  street: 106 N Denton Tap Rd # 350
+  city: Coppell
+  state: TX
+  postal_code: 75019
+  latitude: 32.969527
+  longitude: -96.990159
+f:
+  id: 6
+  company_id: 2
+  street: 5904 N Macarthur Blvd # 160
+  city: Irving
+  state: TX
+  postal_code: 75039
+  latitude: 32.895155
+  longitude: -96.958444
\ No newline at end of file
diff --git a/vendor/plugins/geokit/test/fixtures/locations.yml b/vendor/plugins/geokit/test/fixtures/locations.yml
new file mode 100644 (file)
index 0000000..779faba
--- /dev/null
@@ -0,0 +1,54 @@
+a:
+  id: 1
+  company_id: 1
+  street: 7979 N MacArthur Blvd
+  city: Irving
+  state: TX
+  postal_code: 75063
+  lat: 32.918593
+  lng: -96.958444
+b:
+  id: 2
+  company_id: 1
+  street: 7750 N Macarthur Blvd # 160
+  city: Irving
+  state: TX
+  postal_code: 75063
+  lat: 32.914144
+  lng: -96.958444
+c:
+  id: 3
+  company_id: 1
+  street: 5904 N Macarthur Blvd # 160
+  city: Irving
+  state: TX
+  postal_code: 75039
+  lat: 32.895155
+  lng: -96.958444
+d:
+  id: 4
+  company_id: 1
+  street: 817 S Macarthur Blvd # 145
+  city: Coppell
+  state: TX
+  postal_code: 75019
+  lat: 32.951613
+  lng: -96.958444
+e:
+  id: 5
+  company_id: 1
+  street: 106 N Denton Tap Rd # 350
+  city: Coppell
+  state: TX
+  postal_code: 75019
+  lat: 32.969527
+  lng: -96.990159
+f:
+  id: 6
+  company_id: 2
+  street: 5904 N Macarthur Blvd # 160
+  city: Irving
+  state: TX
+  postal_code: 75039
+  lat: 32.895155
+  lng: -96.958444
\ No newline at end of file
diff --git a/vendor/plugins/geokit/test/fixtures/stores.yml b/vendor/plugins/geokit/test/fixtures/stores.yml
new file mode 100644 (file)
index 0000000..e69de29
diff --git a/vendor/plugins/geokit/test/geoloc_test.rb b/vendor/plugins/geokit/test/geoloc_test.rb
new file mode 100644 (file)
index 0000000..5cf6411
--- /dev/null
@@ -0,0 +1,49 @@
+require 'test/unit'
+require File.join(File.dirname(__FILE__), '../../../../config/environment')
+
+class GeoLocTest < Test::Unit::TestCase #:nodoc: all
+  
+  def setup
+    @loc = GeoKit::GeoLoc.new
+  end
+  
+  def test_is_us
+    assert !@loc.is_us?
+    @loc.country_code = 'US'
+    assert @loc.is_us?
+  end
+  
+  def test_street_number
+    @loc.street_address = '123 Spear St.'
+    assert_equal '123', @loc.street_number
+  end
+  
+  def test_street_name
+    @loc.street_address = '123 Spear St.'
+    assert_equal 'Spear St.', @loc.street_name
+  end
+  
+  def test_city
+    @loc.city = "san francisco"
+    assert_equal 'San Francisco', @loc.city
+  end
+  
+  def test_full_address
+    @loc.city = 'San Francisco'
+    @loc.state = 'CA'
+    @loc.zip = '94105'
+    @loc.country_code = 'US'
+    assert_equal 'San Francisco, CA, 94105, US', @loc.full_address
+    @loc.full_address = 'Irving, TX, 75063, US'
+    assert_equal 'Irving, TX, 75063, US', @loc.full_address
+  end
+  
+  def test_hash
+    @loc.city = 'San Francisco'
+    @loc.state = 'CA'
+    @loc.zip = '94105'
+    @loc.country_code = 'US'
+    @another = GeoKit::GeoLoc.new @loc.to_hash    
+    assert_equal @loc, @another
+  end
+end
\ No newline at end of file
diff --git a/vendor/plugins/geokit/test/google_geocoder_test.rb b/vendor/plugins/geokit/test/google_geocoder_test.rb
new file mode 100644 (file)
index 0000000..dfa8a0c
--- /dev/null
@@ -0,0 +1,88 @@
+require File.join(File.dirname(__FILE__), 'base_geocoder_test')
+
+GeoKit::Geocoders::google = 'Google'
+
+class GoogleGeocoderTest < BaseGeocoderTest #:nodoc: all
+  
+  GOOGLE_FULL=<<-EOF.strip
+  <?xml version="1.0" encoding="UTF-8"?><kml xmlns="http://earth.google.com/kml/2.0"><Response><name>100 spear st, san francisco, ca</name><Status><code>200</code><request>geocode</request></Status><Placemark><address>100 Spear St, San Francisco, CA 94105, USA</address><AddressDetails Accuracy="8" xmlns="urn:oasis:names:tc:ciq:xsdschema:xAL:2.0"><Country><CountryNameCode>US</CountryNameCode><AdministrativeArea><AdministrativeAreaName>CA</AdministrativeAreaName><SubAdministrativeArea><SubAdministrativeAreaName>San Francisco</SubAdministrativeAreaName><Locality><LocalityName>San Francisco</LocalityName><Thoroughfare><ThoroughfareName>100 Spear St</ThoroughfareName></Thoroughfare><PostalCode><PostalCodeNumber>94105</PostalCodeNumber></PostalCode></Locality></SubAdministrativeArea></AdministrativeArea></Country></AddressDetails><Point><coordinates>-122.393985,37.792501,0</coordinates></Point></Placemark></Response></kml>
+  EOF
+
+  GOOGLE_CITY=<<-EOF.strip
+  <?xml version="1.0" encoding="UTF-8"?><kml xmlns="http://earth.google.com/kml/2.0"><Response><name>San Francisco</name><Status><code>200</code><request>geocode</request></Status><Placemark><address>San Francisco, CA, USA</address><AddressDetails Accuracy="4" xmlns="urn:oasis:names:tc:ciq:xsdschema:xAL:2.0"><Country><CountryNameCode>US</CountryNameCode><AdministrativeArea><AdministrativeAreaName>CA</AdministrativeAreaName><Locality><LocalityName>San Francisco</LocalityName></Locality></AdministrativeArea></Country></AddressDetails><Point><coordinates>-122.418333,37.775000,0</coordinates></Point></Placemark></Response></kml>
+  EOF
+  
+  def setup
+    super
+    @google_full_hash = {:street_address=>"100 Spear St", :city=>"San Francisco", :state=>"CA", :zip=>"94105", :country_code=>"US"}
+    @google_city_hash = {:city=>"San Francisco", :state=>"CA"}
+
+    @google_full_loc = GeoKit::GeoLoc.new(@google_full_hash)
+    @google_city_loc = GeoKit::GeoLoc.new(@google_city_hash)
+  end  
+
+  def test_google_full_address
+    response = MockSuccess.new
+    response.expects(:body).returns(GOOGLE_FULL)
+    url = "http://maps.google.com/maps/geo?q=#{CGI.escape(@address)}&output=xml&key=Google&oe=utf-8"
+    GeoKit::Geocoders::GoogleGeocoder.expects(:call_geocoder_service).with(url).returns(response)
+    res=GeoKit::Geocoders::GoogleGeocoder.geocode(@address)
+    assert_equal "CA", res.state
+    assert_equal "San Francisco", res.city 
+    assert_equal "37.792501,-122.393985", res.ll # slightly dif from yahoo
+    assert res.is_us?
+    assert_equal "100 Spear St, San Francisco, CA 94105, USA", res.full_address #slightly different from yahoo
+    assert_equal "google", res.provider
+  end
+  
+  def test_google_full_address_with_geo_loc
+    response = MockSuccess.new
+    response.expects(:body).returns(GOOGLE_FULL)
+    url = "http://maps.google.com/maps/geo?q=#{CGI.escape(@full_address_short_zip)}&output=xml&key=Google&oe=utf-8"
+    GeoKit::Geocoders::GoogleGeocoder.expects(:call_geocoder_service).with(url).returns(response)
+    res=GeoKit::Geocoders::GoogleGeocoder.geocode(@google_full_loc)
+    assert_equal "CA", res.state
+    assert_equal "San Francisco", res.city 
+    assert_equal "37.792501,-122.393985", res.ll # slightly dif from yahoo
+    assert res.is_us?
+    assert_equal "100 Spear St, San Francisco, CA 94105, USA", res.full_address #slightly different from yahoo
+    assert_equal "google", res.provider
+  end  
+
+  def test_google_city
+    response = MockSuccess.new
+    response.expects(:body).returns(GOOGLE_CITY)
+    url = "http://maps.google.com/maps/geo?q=#{CGI.escape(@address)}&output=xml&key=Google&oe=utf-8"
+    GeoKit::Geocoders::GoogleGeocoder.expects(:call_geocoder_service).with(url).returns(response)
+    res=GeoKit::Geocoders::GoogleGeocoder.geocode(@address)
+    assert_equal "CA", res.state
+    assert_equal "San Francisco", res.city
+    assert_equal "37.775,-122.418333", res.ll
+    assert res.is_us?
+    assert_equal "San Francisco, CA, USA", res.full_address
+    assert_nil res.street_address
+    assert_equal "google", res.provider
+  end  
+  
+  def test_google_city_with_geo_loc
+    response = MockSuccess.new
+    response.expects(:body).returns(GOOGLE_CITY)
+    url = "http://maps.google.com/maps/geo?q=#{CGI.escape(@address)}&output=xml&key=Google&oe=utf-8"
+    GeoKit::Geocoders::GoogleGeocoder.expects(:call_geocoder_service).with(url).returns(response)
+    res=GeoKit::Geocoders::GoogleGeocoder.geocode(@google_city_loc)
+    assert_equal "CA", res.state
+    assert_equal "San Francisco", res.city
+    assert_equal "37.775,-122.418333", res.ll
+    assert res.is_us?
+    assert_equal "San Francisco, CA, USA", res.full_address
+    assert_nil res.street_address
+    assert_equal "google", res.provider
+  end  
+  
+  def test_service_unavailable
+    response = MockFailure.new
+    url = "http://maps.google.com/maps/geo?q=#{CGI.escape(@address)}&output=xml&key=Google&oe=utf-8"
+    GeoKit::Geocoders::GoogleGeocoder.expects(:call_geocoder_service).with(url).returns(response)
+    assert !GeoKit::Geocoders::GoogleGeocoder.geocode(@google_city_loc).success
+  end 
+end
\ No newline at end of file
diff --git a/vendor/plugins/geokit/test/ip_geocode_lookup_test.rb b/vendor/plugins/geokit/test/ip_geocode_lookup_test.rb
new file mode 100644 (file)
index 0000000..31f3582
--- /dev/null
@@ -0,0 +1,84 @@
+require File.join(File.dirname(__FILE__), '../../../../config/environment')
+require 'action_controller/test_process'
+require 'test/unit'
+require 'rubygems'
+require 'mocha'
+
+
+class LocationAwareController < ActionController::Base #:nodoc: all
+  geocode_ip_address
+  
+  def index
+    render :nothing => true
+  end
+end
+
+class ActionController::TestRequest #:nodoc: all
+  attr_accessor :remote_ip
+end
+
+# Re-raise errors caught by the controller.
+class LocationAwareController #:nodoc: all
+  def rescue_action(e) raise e end; 
+end
+
+class IpGeocodeLookupTest < Test::Unit::TestCase #:nodoc: all
+  
+  def setup
+    @success = GeoKit::GeoLoc.new
+    @success.provider = "hostip"
+    @success.lat = 41.7696
+    @success.lng = -88.4588
+    @success.city = "Sugar Grove"
+    @success.state = "IL"
+    @success.country_code = "US"
+    @success.success = true
+    
+    @failure = GeoKit::GeoLoc.new
+    @failure.provider = "hostip"
+    @failure.city = "(Private Address)"
+    @failure.success = false
+    
+    @controller = LocationAwareController.new
+    @request = ActionController::TestRequest.new
+    @response = ActionController::TestResponse.new
+  end
+
+  def test_no_location_in_cookie_or_session
+    GeoKit::Geocoders::IpGeocoder.expects(:geocode).with("good ip").returns(@success)
+    @request.remote_ip = "good ip"
+    get :index
+    verify
+  end
+  
+  def test_location_in_cookie
+    @request.remote_ip = "good ip"
+    @request.cookies['geo_location'] = CGI::Cookie.new('geo_location', @success.to_yaml)
+    get :index
+    verify
+  end
+  
+  def test_location_in_session
+    @request.remote_ip = "good ip"
+    @request.session[:geo_location] = @success
+    @request.cookies['geo_location'] = CGI::Cookie.new('geo_location', @success.to_yaml)
+    get :index
+    verify
+  end
+  
+  def test_ip_not_located
+    GeoKit::Geocoders::IpGeocoder.expects(:geocode).with("bad ip").returns(@failure)
+    @request.remote_ip = "bad ip"
+    get :index
+    assert_nil @request.session[:geo_location]
+  end
+  
+  private
+  
+  def verify
+    assert_response :success    
+    assert_equal @success, @request.session[:geo_location]
+    assert_not_nil cookies['geo_location']
+    assert_equal @success, YAML.load(cookies['geo_location'].join)
+  end
+end
\ No newline at end of file
diff --git a/vendor/plugins/geokit/test/ipgeocoder_test.rb b/vendor/plugins/geokit/test/ipgeocoder_test.rb
new file mode 100644 (file)
index 0000000..4d2b6a0
--- /dev/null
@@ -0,0 +1,87 @@
+require File.join(File.dirname(__FILE__), 'base_geocoder_test')
+
+class IpGeocoderTest < BaseGeocoderTest #:nodoc: all
+    
+  IP_FAILURE=<<-EOF
+    Country: (Private Address) (XX)
+    City: (Private Address)
+    Latitude: 
+    Longitude:
+    EOF
+    
+  IP_SUCCESS=<<-EOF
+    Country: UNITED STATES (US)
+    City: Sugar Grove, IL
+    Latitude: 41.7696
+    Longitude: -88.4588
+    EOF
+    
+  IP_UNICODED=<<-EOF
+    Country: SWEDEN (SE)
+    City: BorÃ¥s
+    Latitude: 57.7167
+    Longitude: 12.9167
+    EOF
+    
+    def setup
+      super
+      @success.provider = "hostip"
+    end    
+  
+  def test_successful_lookup
+    success = MockSuccess.new
+    success.expects(:body).returns(IP_SUCCESS)
+    url = 'http://api.hostip.info/get_html.php?ip=12.215.42.19&position=true'
+    GeoKit::Geocoders::IpGeocoder.expects(:call_geocoder_service).with(url).returns(success)
+    location = GeoKit::Geocoders::IpGeocoder.geocode('12.215.42.19')
+    assert_not_nil location
+    assert_equal 41.7696, location.lat
+    assert_equal -88.4588, location.lng
+    assert_equal "Sugar Grove", location.city
+    assert_equal "IL", location.state
+    assert_equal "US", location.country_code
+    assert_equal "hostip", location.provider
+    assert location.success
+  end
+  
+  def test_unicoded_lookup
+    success = MockSuccess.new
+    success.expects(:body).returns(IP_UNICODED)
+    url = 'http://api.hostip.info/get_html.php?ip=12.215.42.19&position=true'
+    GeoKit::Geocoders::IpGeocoder.expects(:call_geocoder_service).with(url).returns(success)
+    location = GeoKit::Geocoders::IpGeocoder.geocode('12.215.42.19')
+    assert_not_nil location
+    assert_equal 57.7167, location.lat
+    assert_equal 12.9167, location.lng
+    assert_equal "BorÃ¥s", location.city
+    assert_nil location.state
+    assert_equal "SE", location.country_code
+    assert_equal "hostip", location.provider
+    assert location.success
+  end
+  
+  def test_failed_lookup
+    failure = MockSuccess.new
+    failure.expects(:body).returns(IP_FAILURE)
+    url = 'http://api.hostip.info/get_html.php?ip=0.0.0.0&position=true'
+    GeoKit::Geocoders::IpGeocoder.expects(:call_geocoder_service).with(url).returns(failure)
+    location = GeoKit::Geocoders::IpGeocoder.geocode("0.0.0.0")
+    assert_not_nil location
+    assert !location.success
+  end
+  
+  def test_invalid_ip
+    location = GeoKit::Geocoders::IpGeocoder.geocode("blah")
+    assert_not_nil location
+    assert !location.success
+  end
+  
+  def test_service_unavailable
+    failure = MockFailure.new
+    url = 'http://api.hostip.info/get_html.php?ip=0.0.0.0&position=true'
+    GeoKit::Geocoders::IpGeocoder.expects(:call_geocoder_service).with(url).returns(failure)
+    location = GeoKit::Geocoders::IpGeocoder.geocode("0.0.0.0")
+    assert_not_nil location
+    assert !location.success
+  end  
+end
\ No newline at end of file
diff --git a/vendor/plugins/geokit/test/latlng_test.rb b/vendor/plugins/geokit/test/latlng_test.rb
new file mode 100644 (file)
index 0000000..993d2be
--- /dev/null
@@ -0,0 +1,112 @@
+$LOAD_PATH.unshift File.join('..', 'lib')
+require 'geo_kit/mappable'
+require 'test/unit'
+
+class LatLngTest < Test::Unit::TestCase #:nodoc: all
+  
+  def setup
+    @loc_a = GeoKit::LatLng.new(32.918593,-96.958444)
+    @loc_e = GeoKit::LatLng.new(32.969527,-96.990159)
+    @point = GeoKit::LatLng.new(@loc_a.lat, @loc_a.lng)
+  end
+  
+  def test_distance_between_same_using_defaults
+    assert_equal 0, GeoKit::LatLng.distance_between(@loc_a, @loc_a)
+    assert_equal 0, @loc_a.distance_to(@loc_a)
+  end
+  
+  def test_distance_between_same_with_miles_and_flat
+    assert_equal 0, GeoKit::LatLng.distance_between(@loc_a, @loc_a, :units => :miles, :formula => :flat)
+    assert_equal 0, @loc_a.distance_to(@loc_a, :units => :miles, :formula => :flat)
+  end
+
+  def test_distance_between_same_with_kms_and_flat
+    assert_equal 0, GeoKit::LatLng.distance_between(@loc_a, @loc_a, :units => :kms, :formula => :flat)
+    assert_equal 0, @loc_a.distance_to(@loc_a, :units => :kms, :formula => :flat)
+  end
+  
+  def test_distance_between_same_with_miles_and_sphere
+    assert_equal 0, GeoKit::LatLng.distance_between(@loc_a, @loc_a, :units => :miles, :formula => :sphere)
+    assert_equal 0, @loc_a.distance_to(@loc_a, :units => :miles, :formula => :sphere)
+  end
+  
+  def test_distance_between_same_with_kms_and_sphere
+    assert_equal 0, GeoKit::LatLng.distance_between(@loc_a, @loc_a, :units => :kms, :formula => :sphere)
+    assert_equal 0, @loc_a.distance_to(@loc_a, :units => :kms, :formula => :sphere)
+  end
+  
+  def test_distance_between_diff_using_defaults
+    assert_in_delta 3.97, GeoKit::LatLng.distance_between(@loc_a, @loc_e), 0.01
+    assert_in_delta 3.97, @loc_a.distance_to(@loc_e), 0.01
+  end
+  
+  def test_distance_between_diff_with_miles_and_flat
+    assert_in_delta 3.97, GeoKit::LatLng.distance_between(@loc_a, @loc_e, :units => :miles, :formula => :flat), 0.2
+    assert_in_delta 3.97, @loc_a.distance_to(@loc_e, :units => :miles, :formula => :flat), 0.2
+  end
+
+  def test_distance_between_diff_with_kms_and_flat
+    assert_in_delta 6.39, GeoKit::LatLng.distance_between(@loc_a, @loc_e, :units => :kms, :formula => :flat), 0.4
+    assert_in_delta 6.39, @loc_a.distance_to(@loc_e, :units => :kms, :formula => :flat), 0.4
+  end
+  
+  def test_distance_between_diff_with_miles_and_sphere
+    assert_in_delta 3.97, GeoKit::LatLng.distance_between(@loc_a, @loc_e, :units => :miles, :formula => :sphere), 0.01
+    assert_in_delta 3.97, @loc_a.distance_to(@loc_e, :units => :miles, :formula => :sphere), 0.01
+  end
+  
+  def test_distance_between_diff_with_kms_and_sphere
+    assert_in_delta 6.39, GeoKit::LatLng.distance_between(@loc_a, @loc_e, :units => :kms, :formula => :sphere), 0.01
+    assert_in_delta 6.39, @loc_a.distance_to(@loc_e, :units => :kms, :formula => :sphere), 0.01
+  end
+  
+  def test_manually_mixed_in
+    assert_equal 0, GeoKit::LatLng.distance_between(@point, @point)
+    assert_equal 0, @point.distance_to(@point)
+    assert_equal 0, @point.distance_to(@loc_a)
+    assert_in_delta 3.97, @point.distance_to(@loc_e, :units => :miles, :formula => :flat), 0.2
+    assert_in_delta 6.39, @point.distance_to(@loc_e, :units => :kms, :formula => :flat), 0.4
+  end
+  
+  def test_heading_between
+    assert_in_delta 332, GeoKit::LatLng.heading_between(@loc_a,@loc_e), 0.5
+  end
+
+  def test_heading_to
+    assert_in_delta 332, @loc_a.heading_to(@loc_e), 0.5
+  end  
+  
+  def test_class_endpoint
+    endpoint=GeoKit::LatLng.endpoint(@loc_a, 332, 3.97)
+    assert_in_delta @loc_e.lat, endpoint.lat, 0.0005
+    assert_in_delta @loc_e.lng, endpoint.lng, 0.0005
+  end
+
+  def test_instance_endpoint
+    endpoint=@loc_a.endpoint(332, 3.97)
+    assert_in_delta @loc_e.lat, endpoint.lat, 0.0005
+    assert_in_delta @loc_e.lng, endpoint.lng, 0.0005
+  end  
+  
+  def test_midpoint
+    midpoint=@loc_a.midpoint_to(@loc_e)
+    assert_in_delta 32.944061, midpoint.lat, 0.0005
+    assert_in_delta -96.974296, midpoint.lng, 0.0005    
+  end  
+  
+  def test_normalize
+    lat=37.7690
+    lng=-122.443
+    res=GeoKit::LatLng.normalize(lat,lng)
+    assert_equal res,GeoKit::LatLng.new(lat,lng) 
+    res=GeoKit::LatLng.normalize("#{lat}, #{lng}")
+    assert_equal res,GeoKit::LatLng.new(lat,lng) 
+    res=GeoKit::LatLng.normalize("#{lat} #{lng}")
+    assert_equal res,GeoKit::LatLng.new(lat,lng)
+    res=GeoKit::LatLng.normalize("#{lat.to_i} #{lng.to_i}")
+    assert_equal res,GeoKit::LatLng.new(lat.to_i,lng.to_i)    
+    res=GeoKit::LatLng.normalize([lat,lng])
+    assert_equal res,GeoKit::LatLng.new(lat,lng)
+  end
+    
+end
\ No newline at end of file
diff --git a/vendor/plugins/geokit/test/multi_geocoder_test.rb b/vendor/plugins/geokit/test/multi_geocoder_test.rb
new file mode 100644 (file)
index 0000000..57f326c
--- /dev/null
@@ -0,0 +1,44 @@
+require File.join(File.dirname(__FILE__), 'base_geocoder_test')
+
+GeoKit::Geocoders::provider_order=[:google,:yahoo,:us]
+
+class MultiGeocoderTest < BaseGeocoderTest #:nodoc: all
+  
+  def setup
+    super
+    @failure = GeoKit::GeoLoc.new
+  end
+  
+  def test_successful_first
+    GeoKit::Geocoders::GoogleGeocoder.expects(:geocode).with(@address).returns(@success)
+    assert_equal @success, GeoKit::Geocoders::MultiGeocoder.geocode(@address)
+  end
+  
+  def test_failover
+    GeoKit::Geocoders::GoogleGeocoder.expects(:geocode).with(@address).returns(@failure)
+    GeoKit::Geocoders::YahooGeocoder.expects(:geocode).with(@address).returns(@success)
+    assert_equal @success, GeoKit::Geocoders::MultiGeocoder.geocode(@address)    
+  end
+  
+  def test_double_failover
+    GeoKit::Geocoders::GoogleGeocoder.expects(:geocode).with(@address).returns(@failure)
+    GeoKit::Geocoders::YahooGeocoder.expects(:geocode).with(@address).returns(@failure)
+    GeoKit::Geocoders::UsGeocoder.expects(:geocode).with(@address).returns(@success)
+    assert_equal @success, GeoKit::Geocoders::MultiGeocoder.geocode(@address)    
+  end
+  
+  def test_failure
+    GeoKit::Geocoders::GoogleGeocoder.expects(:geocode).with(@address).returns(@failure)
+    GeoKit::Geocoders::YahooGeocoder.expects(:geocode).with(@address).returns(@failure)
+    GeoKit::Geocoders::UsGeocoder.expects(:geocode).with(@address).returns(@failure)
+    assert_equal @failure, GeoKit::Geocoders::MultiGeocoder.geocode(@address)    
+  end
+
+  def test_invalid_provider
+    temp = GeoKit::Geocoders::provider_order
+    GeoKit::Geocoders.provider_order = [:bogus]
+    assert_equal @failure, GeoKit::Geocoders::MultiGeocoder.geocode(@address)    
+    GeoKit::Geocoders.provider_order = temp
+  end
+
+end
\ No newline at end of file
diff --git a/vendor/plugins/geokit/test/schema.rb b/vendor/plugins/geokit/test/schema.rb
new file mode 100644 (file)
index 0000000..ad69e08
--- /dev/null
@@ -0,0 +1,31 @@
+ActiveRecord::Schema.define(:version => 0) do
+  create_table :companies, :force => true do |t|
+    t.column :name, :string
+  end  
+  
+  create_table :locations, :force => true do |t|
+    t.column :company_id,  :integer, :default => 0,  :null => false
+    t.column :street,      :string,  :limit => 60
+    t.column :city,        :string,  :limit => 60
+    t.column :state,       :string,  :limit => 2
+    t.column :postal_code, :string,  :limit => 16
+    t.column :lat,         :decimal, :precision => 15, :scale => 10
+    t.column :lng,         :decimal, :precision => 15, :scale => 10
+  end
+  
+  create_table :custom_locations, :force => true do |t|
+    t.column :company_id,  :integer, :default => 0,  :null => false
+    t.column :street,      :string,  :limit => 60
+    t.column :city,        :string,  :limit => 60
+    t.column :state,       :string,  :limit => 2
+    t.column :postal_code, :string,  :limit => 16
+    t.column :latitude,    :decimal, :precision => 15, :scale => 10
+    t.column :longitude,   :decimal, :precision => 15, :scale => 10
+  end
+  
+  create_table :stores, :force=> true do |t|
+    t.column :address,     :string
+    t.column :lat,         :decimal, :precision => 15, :scale => 10
+    t.column :lng,         :decimal, :precision => 15, :scale => 10
+  end
+end
\ No newline at end of file
diff --git a/vendor/plugins/geokit/test/test_helper.rb b/vendor/plugins/geokit/test/test_helper.rb
new file mode 100644 (file)
index 0000000..5cd8f92
--- /dev/null
@@ -0,0 +1,18 @@
+require 'test/unit'
+
+plugin_test_dir = File.dirname(__FILE__)
+
+# Load the Rails environment
+require File.join(plugin_test_dir, '../../../../config/environment')
+require 'active_record/fixtures'
+databases = YAML::load(IO.read(plugin_test_dir + '/database.yml'))
+ActiveRecord::Base.logger = Logger.new(plugin_test_dir + "/debug.log")
+
+# A specific database can be used by setting the DB environment variable
+ActiveRecord::Base.establish_connection(databases[ENV['DB'] || 'mysql'])
+
+# Load the test schema into the database
+load(File.join(plugin_test_dir, 'schema.rb'))
+
+# Load fixtures from the plugin
+Test::Unit::TestCase.fixture_path = File.join(plugin_test_dir, 'fixtures/')
\ No newline at end of file
diff --git a/vendor/plugins/geokit/test/us_geocoder_test.rb b/vendor/plugins/geokit/test/us_geocoder_test.rb
new file mode 100644 (file)
index 0000000..4457803
--- /dev/null
@@ -0,0 +1,47 @@
+require File.join(File.dirname(__FILE__), 'base_geocoder_test')
+
+GeoKit::Geocoders::geocoder_us = nil
+
+class UsGeocoderTest < BaseGeocoderTest #:nodoc: all
+  
+  GEOCODER_US_FULL='37.792528,-122.393981,100 Spear St,San Francisco,CA,94105'  
+  
+  def setup
+    super
+    @us_full_hash = {:city=>"San Francisco", :state=>"CA"}
+    @us_full_loc = GeoKit::GeoLoc.new(@us_full_hash)
+  end  
+  
+  def test_geocoder_us
+    response = MockSuccess.new
+    response.expects(:body).returns(GEOCODER_US_FULL)
+    url = "http://geocoder.us/service/csv/geocode?address=#{CGI.escape(@address)}"
+    GeoKit::Geocoders::UsGeocoder.expects(:call_geocoder_service).with(url).returns(response)
+    verify(GeoKit::Geocoders::UsGeocoder.geocode(@address))
+  end
+  
+  def test_geocoder_with_geo_loc
+    response = MockSuccess.new
+    response.expects(:body).returns(GEOCODER_US_FULL)
+    url = "http://geocoder.us/service/csv/geocode?address=#{CGI.escape(@address)}"
+    GeoKit::Geocoders::UsGeocoder.expects(:call_geocoder_service).with(url).returns(response)
+    verify(GeoKit::Geocoders::UsGeocoder.geocode(@us_full_loc))    
+  end
+  
+  def test_service_unavailable
+    response = MockFailure.new
+    url = "http://geocoder.us/service/csv/geocode?address=#{CGI.escape(@address)}"
+    GeoKit::Geocoders::UsGeocoder.expects(:call_geocoder_service).with(url).returns(response)
+    assert !GeoKit::Geocoders::UsGeocoder.geocode(@us_full_loc).success   
+  end  
+  
+  private
+  
+  def verify(location)
+    assert_equal "CA", location.state
+    assert_equal "San Francisco", location.city 
+    assert_equal "37.792528,-122.393981", location.ll 
+    assert location.is_us?
+    assert_equal "100 Spear St, San Francisco, CA, 94105, US", location.full_address  #slightly different from yahoo    
+  end
+end
\ No newline at end of file
diff --git a/vendor/plugins/geokit/test/yahoo_geocoder_test.rb b/vendor/plugins/geokit/test/yahoo_geocoder_test.rb
new file mode 100644 (file)
index 0000000..abf9a4e
--- /dev/null
@@ -0,0 +1,87 @@
+require File.join(File.dirname(__FILE__), 'base_geocoder_test')
+
+GeoKit::Geocoders::yahoo = 'Yahoo'
+
+class YahooGeocoderTest < BaseGeocoderTest #:nodoc: all
+    YAHOO_FULL=<<-EOF.strip
+  <?xml version="1.0"?>
+  <ResultSet xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="urn:yahoo:maps" xsi:schemaLocation="urn:yahoo:maps http://api.local.yahoo.com/MapsService/V1/GeocodeResponse.xsd"><Result precision="address"><Latitude>37.792406</Latitude><Longitude>-122.39411</Longitude><Address>100 SPEAR ST</Address><City>SAN FRANCISCO</City><State>CA</State><Zip>94105-1522</Zip><Country>US</Country></Result></ResultSet>
+  <!-- ws01.search.scd.yahoo.com uncompressed/chunked Mon Jan 29 16:23:43 PST 2007 -->
+    EOF
+
+    YAHOO_CITY=<<-EOF.strip
+  <?xml version="1.0"?>
+  <ResultSet xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="urn:yahoo:maps" xsi:schemaLocation="urn:yahoo:maps http://api.local.yahoo.com/MapsService/V1/GeocodeResponse.xsd"><Result precision="city"><Latitude>37.7742</Latitude><Longitude>-122.417068</Longitude><Address></Address><City>SAN FRANCISCO</City><State>CA</State><Zip></Zip><Country>US</Country></Result></ResultSet>
+  <!-- ws02.search.scd.yahoo.com uncompressed/chunked Mon Jan 29 18:00:28 PST 2007 -->
+    EOF
+    
+  def setup
+    super
+    @yahoo_full_hash = {:street_address=>"100 Spear St", :city=>"San Francisco", :state=>"CA", :zip=>"94105-1522", :country_code=>"US"}
+    @yahoo_city_hash = {:city=>"San Francisco", :state=>"CA"}
+    @yahoo_full_loc = GeoKit::GeoLoc.new(@yahoo_full_hash)
+    @yahoo_city_loc = GeoKit::GeoLoc.new(@yahoo_city_hash)
+  end
+  
+  # the testing methods themselves
+  def test_yahoo_full_address
+    response = MockSuccess.new
+    response.expects(:body).returns(YAHOO_FULL)
+    url = "http://api.local.yahoo.com/MapsService/V1/geocode?appid=Yahoo&location=#{CGI.escape(@address)}"
+    GeoKit::Geocoders::YahooGeocoder.expects(:call_geocoder_service).with(url).returns(response)
+    do_full_address_assertions(GeoKit::Geocoders::YahooGeocoder.geocode(@address))
+  end 
+  
+  def test_yahoo_full_address_with_geo_loc
+    response = MockSuccess.new
+    response.expects(:body).returns(YAHOO_FULL)
+    url = "http://api.local.yahoo.com/MapsService/V1/geocode?appid=Yahoo&location=#{CGI.escape(@full_address)}"
+    GeoKit::Geocoders::YahooGeocoder.expects(:call_geocoder_service).with(url).returns(response)
+    do_full_address_assertions(GeoKit::Geocoders::YahooGeocoder.geocode(@yahoo_full_loc))
+  end  
+
+  def test_yahoo_city
+    response = MockSuccess.new
+    response.expects(:body).returns(YAHOO_CITY)
+    url = "http://api.local.yahoo.com/MapsService/V1/geocode?appid=Yahoo&location=#{CGI.escape(@address)}"
+    GeoKit::Geocoders::YahooGeocoder.expects(:call_geocoder_service).with(url).returns(response)
+    do_city_assertions(GeoKit::Geocoders::YahooGeocoder.geocode(@address))
+  end
+  
+  def test_yahoo_city_with_geo_loc
+    response = MockSuccess.new
+    response.expects(:body).returns(YAHOO_CITY)
+    url = "http://api.local.yahoo.com/MapsService/V1/geocode?appid=Yahoo&location=#{CGI.escape(@address)}"  
+    GeoKit::Geocoders::YahooGeocoder.expects(:call_geocoder_service).with(url).returns(response)
+    do_city_assertions(GeoKit::Geocoders::YahooGeocoder.geocode(@yahoo_city_loc))
+  end  
+  
+  def test_service_unavailable
+    response = MockFailure.new
+    url = "http://api.local.yahoo.com/MapsService/V1/geocode?appid=Yahoo&location=#{CGI.escape(@address)}"
+    GeoKit::Geocoders::YahooGeocoder.expects(:call_geocoder_service).with(url).returns(response)
+    assert !GeoKit::Geocoders::YahooGeocoder.geocode(@yahoo_city_loc).success
+  end  
+
+  private
+
+  # next two methods do the assertions for both address-level and city-level lookups
+  def do_full_address_assertions(res)
+    assert_equal "CA", res.state
+    assert_equal "San Francisco", res.city
+    assert_equal "37.792406,-122.39411", res.ll
+    assert res.is_us?
+    assert_equal "100 Spear St, San Francisco, CA, 94105-1522, US", res.full_address
+    assert_equal "yahoo", res.provider
+  end
+  
+  def do_city_assertions(res)
+    assert_equal "CA", res.state
+    assert_equal "San Francisco", res.city 
+    assert_equal "37.7742,-122.417068", res.ll
+    assert res.is_us?
+    assert_equal "San Francisco, CA, US", res.full_address 
+    assert_nil res.street_address
+    assert_equal "yahoo", res.provider
+  end  
+end
\ No newline at end of file
diff --git a/vendor/plugins/ym4r_gm/README b/vendor/plugins/ym4r_gm/README
new file mode 100644 (file)
index 0000000..b1f0248
--- /dev/null
@@ -0,0 +1,391 @@
+=YM4R/GM plugin for Rails
+
+This is the latest version of the YM4R/GM plugin for Rails (YM4RGMP4R?). Its aim is to facilitate the use of Google Maps from Rails application. It includes and enhances all the web application-related functionalities found in the YM4R gem as of version 0.4.1.
+
+==Getting Started
+I present here the most common operations you would want to do with YM4R/GM. Read the rest of the documents if you want more details.
+
+In your controller, here is a typical initialization sequence in action +index+:
+       def index
+         @map = GMap.new("map_div")
+         @map.control_init(:large_map => true,:map_type => true)
+         @map.center_zoom_init([75.5,-42.56],4)
+         @map.overlay_init(GMarker.new([75.6,-42.467],:title => "Hello", :info_window => "Info! Info!"))
+       end
+
+Here I create a GMap (which will be placed inside a DIV of id +map_div+), add controls (large zoom slider and pan cross + map type selector), set the center and the zoom and add a marker. Of these 4 steps only the creation of the map and the setting of the center and the zoom are absolutely necessary.
+
+In your view, here is what you would have:
+       <html><head><title>Test</title>
+       <%= GMap.header %>
+       <%= @map.to_html %>
+       </head><body>
+       <%= @map.div(:width => 600, :height => 400) %>
+       </body></html>
+
+First you must output the header, used by all the maps of the page: It includes the Google Maps API JS code and the JS helper functions of YM4R/GM. Then we initialize the map by calling <tt>@map.to_html</tt>. In the body, we need a DIV whose +id+ is the same as the one passed to the GMap constructor in the controller. The call to <tt>@map.div</tt> outputs such a DIV. We pass to it options to set the width and height of the map in the style attribute of the DIV. 
+
+<b>Note that you need to set a size for the map DIV element at some point or the map will not be displayed.</b> You have a few ways to do this:
+- You define it yourself, wherever you want. Usually as part of the layout definition in an external CSS.
+- In the head of the document, through a CSS instruction output by <tt>@map.header_width_height</tt>, to which you pass 2 arguments (width and height).
+- When outputting the DIV with <tt>@map.div</tt>, you can also pass an option hash, with keys <tt>:width</tt> and <tt>:height</tt> and a style attribute for the DIV element will be output.
+
+You can update the map trough RJS. Here is an action you can call from a <tt>link_remote_tag</tt> which would do this:
+       def update
+         @map = Variable.new("map")
+         @marker = GMarker.new([75.89,-42.767],:title => "Update", :info_window => "I have been placed through RJS")
+       end
+
+Here, I first bind the Ruby <tt>@map</tt> variable to the JS variable <tt>map</tt>, which already exists in the client browser. +map+ is by default the name given to a map created from YM4R/GM (this could be overriden by passing a second argument to the GMap constructor). Then I create a marker.
+
+And you would have inside the RJS template for the action:
+       page << @map.clear_overlays
+       page << @map.add_overlay(@marker)
+
+Here I first clear the map of all overlays. Then I add the marker. Note that the +overlay_init+ is not used anymore since, as its name indicates, this method is only for the initialization of the map.
+
+==Relation between the YM4R gem and the YM4R/GM plugin
+They are completely independent from each other.
+
+With the plugin, you don't need the YM4R gem anymore, unless you want to use the tilers or the Ruby helpers for the Yahoo! Maps Building Block API's and the Google Maps geocoding API. Please refer to the documentation of the YM4R gem to know more about the functionalities in it.
+
+Conversely, the YM4R gem does not need the plugin to work.
+
+==Installation
+Install like any other Rails plugin:
+       ruby script/plugin install svn://rubyforge.org/var/svn/ym4r/Plugins/GM/trunk/ym4r_gm
+
+As part of the installation procedure, the JavaScript files found in the <tt>PLUGIN_ROOT/javascript</tt> directory will be copied to the <tt>RAILS_ROOT/public/javascripts/</tt> directory. 
+
+Moreover a <tt>gmaps_api_key.yml</tt> file will also be created in the <tt>RAILS_ROOT/config/</tt> folder. If this file already exists (installed for example by a previous version of the plugin), nothing will be done to it, so you can keep your configuration data even after updating the plugin. This file is a YAML representation of a hash, similar to the <tt>database.yml</tt> file in that the primary keys in the file are the different environments (development, test, production), since you will probably need to have different Google Maps API keys depending on that criteria (for example: a key for localhost for development and test; a key for your host for production). If you don't have any special need, there will be only one key associated with each environment. If however, you need to have multiple keys (for example if your app will be accessible from multiple URLs, for which you need different keys), you can also associate a hash to the environment, whose keys will be the different hosts. In this case, you will need to pass a value to the <tt>:host</tt> key when calling the method <tt>GMap.header</tt> (usually <tt>@request.host</tt>).
+
+==Migration from the YM4R gem versions <= 0.4.1
+Apart from the installation of the plugin detailed above, you will also need to delete the instructions to require the file and include the Ym4r::GoogleMaps module in your controllers:
+       require 'ym4r'
+       include Ym4r::GoogleMaps
+This lines are now not needed since the plugin is loaded as part of the normal Rails loading procedure and the module is included when the plugin is loaded.
+
+==Operations
+You can use the library to display Google maps easily from Rails. The version of the API used is v2. The library is engineered so updates to the map through RJS/Ajax are possible. I have made available 2 in-depth tutorials to show some of the functionalities of the library and how it can be integrated with GeoRuby and the Spatial Adapter for Rails:
+- http://thepochisuperstarmegashow.com/2006/06/02/ym4r-georuby-spatial-adapter-demo/
+- http://thepochisuperstarmegashow.com/2006/06/03/google-maps-yahoo-traffic-mash-up/
+Following is some notes about manipulating Google Maps with the library:
+
+===Naming conventions
+The names of the Ruby class follow the ones in the JavaScript Google Maps API v2, except for GMap2, which in Ruby code is called simply GMap. To know what is possible to do with each class, you should refer to the documentation available on Google website.
+
+On top of that, you have some convenience methods for initializing the map (in the GMap class). Also, the constructors of some classes accept different types of arguments to be converted later in the correct JavaScript format. For example, the +GMarker+ aclass accepts an array of 2 floats as parameter, in addition of a GLatLng object, to indicate its position. It also facilitates the attribution of an HTML info window, displayed when the user clicks on it, since you can pass to the constructor an options hash with the <tt>:info_window</tt> key and the text to display as the value, instead of having to wire the response to a click event yourself.
+
+===Binding JavaScript and Ruby
+Since the Google Maps API uses JavaScript to create and manipulate a map, most of what the library does is outputting JavaScript, although some convenience methods are provided to simplify some common operations at initialization time. When you create a YM4R mapping object (a Ruby object which includes the MappingObject module) and call methods on it, these calls are converted by the library into JavaScript code. At initialization time, you can pass arbitrary JavaScript code to the <tt>GMap#record_init</tt> and <tt>GMap#record_global_init</tt>.Then, at update time, if you use Ruby-on-Rails as your web framework, you can update your map through RJS by passing the result of the method calls to the <tt>page << </tt> method to have it then interpreted by the browser.
+
+For example, here is a typical initialization sequence for a map
+       @map = GMap.new("map_div")
+       @map.control_init(:large_map => true,:map_type => true)
+       @map.center_zoom_init([35.12313,-110.567],12)
+       @map.overlay_init GMarker.new([35.12878, -110.578],:title => "Hello!")
+       @map.record_init @map.add_overlay(GMarker.new([35.12878, -110.578],:title => "Hello!"))
+
+While +center_zoom_init+, +control_init+ or +overlay_init+ (and generally all the GMap methods which end in +init+) are one of the rare convenience methods that do not output JavaScript, the +add_overlay+ does. Actually, if you look at the code of the GMap class, you won't find any +add_overlay+ method, although in the documentation of the GMap2 class from the Google Maps API documentation, you will find something about the +addOverlay+ JavaScript method. In fact, when you call on a mapping object an unknow method, it is converted to a javascriptified version of it, along with its arguments, and a string of JavaScript code is output. So the <tt>@map.add_overlay...</tt> above is converted to <tt>"map.addOverlay(new GMarker(GLatLng.new(35.12878, -110.578),{title:\"Hello!\"}))"</tt>, which is then passed to the +record_init+ method of a Ruby GMap object to be later output along with the rest of the initialization code. Any arbitrary JavaScript code can be passed to the +record_init+ method. Note that 2 last lines of the previous code sample are strictly equivalent and since the +overlay_init+ version is a bit simpler, it should be preferred.
+
+===Initialization of the map
+The map is represented by a GMap object. You need to pass to the constructor the id of a DIV that will contain the map. You have to place this DIV yourself in your HTML template. You can also optionnally pass to the constructor the JavaScript name of the variable that will reference the map, which by default will be global in JavaScript. You have convenience methods to setup the controls, the center, the zoom, overlays, the interface configuration (continuous zoom, double click zoom, dragging), map types and the icons (which are also global). You can also pass arbitrary JavaScript to +record_init+ and +record_global_init+. Since, by default, the initialization of the map is performed in a callback function, if you want to have a globally accessible variable, you need to use the +global+ version.
+
+You can also have multiple maps. Just make sure you give them different DIV id's, as well as different global variable names, when constructing them:
+       @map1 = GMap("map1_div","map1")
+       @map2 = GMap("map2_div","map2")
+
+The other absolutely necessary initialization step in the controller is the setting of center and zoom:
+       @map1.center_zoom_init([49.12,-56.453],3)
+Withouth this code the map will display an empty grey rectangle with Google's logo. 
+
+Then in your template, you have 2 necessary calls:
+- The static <tt>GMap.header</tt>: Outputs the inclusion of the JavaScript file from Google to make use of the Google Maps API and by default a style declaration for VML objects, necessary to display polylines under IE. This default can be overriddent by passing <tt>:with_vml => false</tt> as option to the +header+ method. You can also pass to this method a <tt>:host</tt> option in order to select the correct key for the location where your app is currently deployed, in case the current environment has multiple possible keys. Usually, in this case, you should pass it <tt>@request.host</tt>. Finally you can override all the key settings in the configuration by passing a value to the <tt>:key</tt> key.
+- <tt>GMap#to_html</tt>: Outputs the initialization code of the map. By default, it outputs the +script+ tags and initializes the map in response to the onload event of the JavaScript window object. You can call +to_html+ on each one of your maps to have them all initialized. You can pass the option <tt>:full=>true</tt> to the method to setup a fullscreen map, which will also be resized when the window size changes.
+
+You can also use <tt>GMap#div</tt> to output the div element with the correct +id+. You can pass it options <tt>:height</Tt> and <tt>:width</tt> to set the size of the div (although, as indicated below, you have other ways to do that).
+
+So you should have something like the following:
+       <html><head><title>Hello</title>
+       <%= GMap.header %>
+       <%= @map.to_html %>
+       </head>
+       <body><%= @map.div(:width => 600,:height => 400) %></body>
+       </html>
+
+<b>Note that you need to set a size for the map DIV element at some point or the map will not be displayed.</b> You have a few ways to do this:
+- You define it yourself, wherever you want. Usually as part of the layout definition in an external CSS.
+- In the head of the document, through a CSS instruction output by <tt>@map.header_width_height</tt>, to which you pass 2 arguments (width and height).
+- When outputting the DIV with <tt>@map.div</tt>, you can also pass an option hash, with keys <tt>:width</tt> and <tt>:height</tt> and a style attribute for the DIV element will be output.
+
+===GMarkers
+GMarkers are point of interests on a map. You can give a position to a GMarker constructor either by passing it a 2D-array of coordinates, a GLatLng object, an object of type Variable (which evaluates to a GLatLng when interpreted in the browser) or an address, which will be geocoded when the marker is initialized by the map.
+
+You can pass options to the GMarker to customize the info window (<tt>:info_window</tt> or <tt>:info_window_tabs</tt> options), the tooltip (<tt>:title</tt> option) or the icon used (<tt>:icon</tt> option).
+
+For example:
+       GMarker.new([12.4,65.6],:info_window => "<b>I'm a Popup window</b>",:title => "Tooltip")
+       GMarker.new(GLatLng.new([12.3,45.6]))
+       GMarker.new("Rue Clovis Paris France", :title => "geocoded")
+       
+
+===Update of the map
+You are able to update the map through Ajax. In Ruby-on-Rails, you have something called RJS, which sends JavaScript created on the server as a response to an action, which is later interpreted by the browser. It is usually used for visual effects and replacing or adding elements. It can also accept arbitrary JavaScript and this is what YM4R uses.
+
+For example, if you want to add a marker to the map, you need to do a few things. First, you have to bind a Ruby mapping object to the global JavaScript map variable. By default its name is +map+, but you could have overriden that at initialization time. You need to do something like this:
+       @map = Variable.new("map")
++map+ in the Variable constructor is the name of the global JavaScript map variable. Then any method you call on <tt>@map</tt> will be converted in JavaScript to a method called on +map+. In your RJS code, you would do something like this to add a marker:
+       page << @map.add_overlay(GMarker.new([12.1,12.76],:title => "Hello again!"))
+What is sent to the browser will be the fllowing JavaScript code:
+       map.addOverlay(new GMarker(new GLatLng(123123.1,12313.76),{title:\"Hello again!\"}))
+
+
+===GPolyline
+GPolylines are colored lines on the map. The constructor takes as argument a list of GLatLng or a list of 2-element arrays, which will be transformed into GLatLng for you. It can also take the color (in the <tt>#rrggbb</tt> form), the weight (an integer) and the opacity. These arguments are optional though.
+
+For example:
+       GPolyline.new([[12.4,65.6],[4.5,61.2]],"#ff0000",3,1.0)
+
+Then you add it like any other overlay:
+       @map.overlay_init(polyline)
+
+===GPolygon
+GPolygons are colored areas on the map. As of 29/12, this feature is not documented in the official GMaps API, but thanks to Steven Talcott Smith (http://www.talcottsystems.com), it is possible to use it now in ym4r. 
+
+The constructor takes as argument a list of GLatLng or a list of 2-element arrays, which will be transformed into GLatLng for you. Note that for polygons, the last point must be equal to the first, in order to have a closed loop. It can also take the color (in the <tt>#rrggbb</tt> form) of the stroke, the weight of the stroke, the opacity of the stroke, as well as the color of the fill and the opacity. These arguments are optional though.
+
+For example:
+       GPolygon.new([[12.4,6.6],[4.5,1.2],[-5.6,-12.4],[12.4,6.6]],"#ff0000",3,1.0,"#00ff00",1.0)
+
+Then you add it like any other overlay:
+       @map.overlay_init(polygon)
+       
+===GMarkerGroup
+A new type of GOverlay is available, called GMarkerGroup. 
+
+<b>To use it you would have to include in your HTML template the JavaScript file <tt>markerGroup.js</tt> after the call to <tt>GMap.header</tt> (because it extends the GOverlay class).</b> You should have something like that in your template:
+       <%= javascript_include_tag("markerGroup") %>
+
+It is useful in 2 situations:
+- Display and undisplay a group of markers without referencing all of them. You just declare your marker group globally and call +activate+ and +deactivate+ on this group in response, for example, to clicks on links on your page.
+- Keeping an index of markers, for example, in order to show one of these markers in reponse to a click on a link (the way Google Local does with the results of the search).
+
+Here is how you would use it from your Ruby code:
+       @map = GMap.new("map_div")
+       marker1 = GMarker.new([123.55,123.988],:info_window => "Hello from 1!")
+       marker2 = GMarker.new([87.123,18.9],:info_window =>"Hello from 2!")
+       @map.overlay_global_init(GMarkerGroup.new(true,
+                                       1 => marker1,
+                                       2 => marker2),"myGroup")
+Here I have created an active (ie which is going to be displayed when the map is created) marker group called +myGroup+ with 2 markers, which I want to reference later. If I did not want to reference them later (I just want to be able to display and undisplay the marker group), I could have passed an array instead of the hash.
+
+Then in your template, you could have that:
+       <a href="#" onclick="myGroup.showMarker(1);return false;">Click here to display marker1</a>
+       <a href="#" onclick="myGroup.showMarker(2);return false;">Click here to display marker2</a>
+       <%= @map.div %>
+When you click on one of the links, the corresponding marker has its info window displayed.
+
+You can call +activate+ and +deactivate+ to display or undisplay a group of markers. You can add new markers with <tt>addMarker(marker,id)</tt>. Again if you don't care about referencing the marker, you don't need to pass an id. If the marker group is active, the newly added marker will be displayed immediately. Otherwise it will be displayed the next time the group is activated. Finally, since it is an overlay, the group will be removed when calling clearOverlays on the GMap object.
+
+You can center and zoom on all the markers in the group by calling <tt>GMarkerGroup#centerAndZoomOnMarkers()</tt> after the group has been added to a map. So for example, if you would want to do that at initalization time, you would do the following (assuming your marker group has been declared as +group+):
+       @map.record_init group.center_and_zoom_on_markers
+
+===GMarkerManager
+It is a recent (v2.67) GMaps API class that manages the efficient display of potentially thousands of markers. It is similar to the Clusterer (see below) since markers start appearing at specified zoom levels. The clustering behaviour has to be managed explicitly though by specifying the cluster for smaller zoom levels and specify the expanded cluster for larger zoom levels and so on. Note that it is not an overlay and is not added to the map through an overlay_init call.
+
+Here is an example of use:
+    @map = GMap.new("map_div")
+    @map.control_init(:large_map => true, :map_type => true)
+    @map.center_zoom_init([59.91106, 10.72223],3)
+    srand 1234
+    markers1 = []
+    1.upto(20) do  |i|
+      markers1 << GMarker.new([59.91106 + 6 * rand - 3, 10.72223 + 6 * rand - 3],:title => "OY-20-#{i}")
+    end
+    managed_markers1 = ManagedMarker.new(markers1,0,7)
+
+    markers2 = []
+    1.upto(200) do  |i|
+      markers2 << GMarker.new([59.91106 + 6 * rand - 3, 10.72223 + 6 * rand - 3],:title => "OY-200-#{i}")
+    end
+    managed_markers2 = ManagedMarker.new(markers2,8,9)
+
+    markers3 = []
+    1.upto(1000) do  |i|
+      markers3 << GMarker.new([59.91106 +  6 * rand - 3, 10.72223 + 6 * rand - 3],:title => "OY-300-#{i}")
+    end
+    managed_markers3= ManagedMarker.new(markers3,10)
+
+    mm = GMarkerManager.new(@map,:managed_markers => [managed_markers1,managed_markers2,managed_markers3])
+    @map.declare_init(mm,"mgr")
+
+===Clusterer
+A Clusterer is a type of overlay that contains a potentially very large group of markers. It is engineered so markers close to each other and undistinguishable from each other at some level of zoom, appear as only one marker on the map at that level of zoom. Therefore it is possible to have a very large number of markers on the map at the same time and not having the map crawl to a halt in order to display them. It has been slightly modified from Jef Poskanzer's original Clusterer2 code (see http://www.acme.com/javascript/ for the original version). The major difference with that version is that, in YM4R, the clusterer is a GOverlay and can therefore be added to the map with <tt>map.addOverlay(clusterer)</tt> and is cleared along with the rest of overlays when <tt>map.clearOverlays()</tt> is called.
+
+<b>In order to use a clusterer, you should include in your template page the clusterer.js file after the call to <tt>GMap.header</tt> (because it extends the GOverlay class).</b> You should have something like that in your template:
+       <%= javascript_include_tag("clusterer") %>
+
+To create a clusterer, you should first create an array of all the GMarkers that you want to include in the clusterer (you can still add more after the clusterer has been added to the map though). When GMarkers close together are grouped in one cluster (represented by another marker on the map) and the user clicks on the cluster marker, a list of markers in the cluster is displayed in the info windo with a description: By default it is equal to the +title+ of the markers (which is also displayed as a tooltip when hovering on the marker with the mouse). If you don't want that, you can also pass to the GMarker constructor a key-value pair with key <tt>:description</tt> to have a description different from the title. For example, here is how you would create a clusterer:
+       markers = [GMarker.new([37.8,-90.4819],:info_window => "Hello",:title => "HOYOYO"),
+                  GMarker.new([37.844,-90.47819],:info_window => "Namaste",:description => "Chopoto" , :title => "Ay"),
+                 GMarker.new([37.83,-90.456619],:info_window => "Bonjour",:title => "Third"),
+       ]
+       clusterer = Clusterer.new(markers,:max_visible_markers => 2)
+Of course, with only 3 markers, the whole clusterer thing is totally useless. Usually, using the clusterer starts being interesting with hundreds of markers. The options to pass the clusterer are:
+- <tt>:max_visible_markers</tt>: Below this number of markers, no clustering is performed. Defaults to 150.
+- <tt>:grid_size</tt>: The clusterer divides the visible area into a grid of this size. Defaults to 5.
+- <tt>:min_markers_per_cluster</tt>: Below this number of markers a cluster is not formed. Defaults to 5.
+- <tt>:max_lines_per_info_box</tt>: Number of lines to display in the info window displayed when a cluster is clicked on by the user. Defaults to 10.
+- <tt>:icon</tt>: Icon to be used to mark a cluster. Defaults to G_DEFAULT_ICON (the classic red marker).
+
+Then to add the clusterer to the map at initialization time, you proceed as with a classic overlay:
+       @map.overlay_init clusterer
+
+To add new markers in RJS (if the clusterer has been declared globally with overlay_global_init), you should do this:
+       page << clusterer.add_marker(marker,description)
+In this case, the <tt>:description</tt> passed to the GMarker contructor will not be taken into account. Only the +description+ passed in the call to +add_marker+ will.
+
+===GeoRss Overlay
+An group of markers taken from a Rss feed containing location information in the W3C basic geo (WGS83 lat/lon) vocabulary and in the Simple GeoRss format. See http://georss.org for more details. The support for GeoRss relies on the MGeoRSS library by Mikel Maron (http://brainoff.com/gmaps/mgeorss.html), although a bit modified, mostly to have the GeoRssOverlay respect the GOverlay API. It has also been enhanced by Andrew Turner who added support for the GeoRss Simple format.
+
+<b>Note that the <tt>geoRssOverlay.js</tt> file must be included in the HTML template in order to use this functionality.</b> You should have something like that in your template:
+       <%= javascript_include_tag("geoRssOverlay") %>
+
+Here is how you would use it. First create the overlay at initialization:
+       def index
+         @map = GMap.new("map_div")
+         @map.control_init(:large_map => true)
+         @map.center_zoom_init([38.134557,-95.537109],0)
+          @map.overlay_init(GeoRssOverlay.new(url_for(:action => "earthquake_rss"))
+       end
+Since it is not possible to make requests outside the domain where the current page comes from, there is a need for a proxy. With the GeoRssOverlay initialization above, the request will be made by the <tt>earthquake_rss</tt> action, where the address to find the RSS feed will be hardwired:
+       def earthquake_rss
+           result = Net::HTTP.get_response("earthquake.usgs.gov","/eqcenter/recenteqsww/catalogs/eqs7day-M5.xml")
+           render :xml => result.body
+       end
+If you don't want to hardwire the RSS feed location in an action, you can. But you will have to pass the <tt>:proxy</tt> option to the GeoRssOverlay constructor. When requesting the RSS feed, the browser will in fact call the proxy with the actual URL of the RSS feed in the +q+ parameter of the request. Here is how you would initialize the GeoRssOverlay that way:
+       @map.overlay_init(GeoRssOverlay.new("http://earthquake.usgs.gov/eqcenter/recenteqsww/catalogs/eqs7day-M5.xml",
+       :proxy => url_for(:action => "proxy")))
+And here is an example of <tt>proxy</tt> action:
+       def proxy
+           result = Net::HTTP.get_response(URI.parse(@params[:q]))
+           render :xml => result.body
+       end
+You should probably do some checks to ensure the proxy is not abused but it is of your responsibility.
+
+Another option can be passed to the GeoRssOverlay constructor to set an icon to be used by the markers of the overlay: <tt>:icon</tt>. By default it is equal to the default icon (the classic red one).
+
+In the view, you should have something like the following:
+       <html>
+       <head><title>Testing GeoRss</title>
+       <%= GMap.header(:with_vml => false) %>
+       <%= javascript_include_tag("geoRssOverlay") %>
+       <%= @map.header_width_height(600,400) %>
+       <%= @map.to_html %>
+       </head>
+       <body>
+       <%= @map.div %>
+       </body>
+       </html> 
+Note the inclusion of the <tt>geoRssOverlay.js</tt> file.
+
+Other options to pass to the GeoRssOverlay constructor are the following:
+- <tt>:list_div</tt>: In case you want to make a list of all the markers, with a link on which you can click in order to display the info on the marker, use this option to indicate the ID of the DIV (that you must place yourself on your page).
+- <tt>:list_item_class<tt>: class of the DIV containing each item of the list. Ignored if option <tt>:list_div</tt> is not set.
+- <tt>:limit</tt>: Maximum number of items to display on the map.
+- <tt>:content_div</tt>: Instead of having an info window appear, indicates the ID of the DIV where this info should be displayed.
+
+===Adding new map types
+It is now possible to easily add new map types, on top of the already existing ones, like G_SATELLITE_MAP or G_NORMAL_MAP. The imagery for these new map types can come from layers of the standard map types or can be taken either from a WMS server or from pretiled images on a server (that can be generated with a tool that comes with the YM4R gem: refer to the README of the gem to know more about it). 
+
+For exemple, here is how you would setup layers from a public WMS server of the DMAP team of the American Navy:
+       layer = WMSLayer.new("http://columbo.nrlssc.navy.mil/ogcwms/servlet/WMSServlet/AccuWeather_Maps.wms",
+       "20:3,6:3,0:27,0:29,6:19",
+       :copyright => {'prefix' => "Map Copyright 2006", 'copyright_texts'=> ["DMAP"]},
+       :use_geographic => true, :opacity => 0.8)
+This sets up a connection to a WMS service, requesting layers <tt>20:3,6:3,0:27,0:29,6:19</tt> (you would have to look at the GetCapabilities document of the service to know what the valid layers are). The copyright notice attributes the data to DMAP. The images will be 80% opaque. For the rest of the options, the default values are used: default styles (<tt>:style</tt> option), PNG format (<tt>:format</tt> option), valid for all zoom levels (<tt>:zoom_range</tt> option). The option <tt>:merc_proj</tt> is irrelevant here since the <tt>:use_geographic</tt> option is true.
+
+The arguments <tt>:use_geographic</tt> and <tt>:merc_proj</tt> warrant some explanation. The Google Maps are in the Simple Mercator projection in the WGS84 datum and currently do not support the display of data in projections other than that (at least if you want to display markers and lines on top of it). Unfortunately, different WMS servers do not identify this projection the same way. So you can give to the WMSLayer constructor your server type through the <tt>:merc_proj</tt> option  and it will figure out what is the correct identifier. Currently, this works only for <tt>:mapserver</tt> (EPSG:54004) and <tt>:geoserver</tt> (EPSG:41001). For others you can directly pass a number corresponding to the EPSG definition of the simple Mercator projection of your server. On top of that, some servers just don't support the Simple Mercator projection. This is why there is a <tt>:use_geographic</tt> option, that can be set to +true+. It is in order to tell the WMSLayer that it should request its tiles using LatLon coordinates in the WGS84 datum (which should be supported by any server in a consistant way). Unfortunately it is not perfect since the deformation is quite important for low zoom levels (< 5 for the US). Higher than that, the deformation is not that visible. However, if you control the WMS server, it is recommended that you don't use <tt>:use_geographic</tt> and instead use the <tt>:merc_proj</tt> option and setup the Mercator projection in your server if it is not done by default.
+
+<b>Note that you need to include the <tt>wms-gs.js</tt> javascript file in your HTML page in order to make use of the WMSLayer functionality.</b> You should have something like that in your template:
+       <%= javascript_include_tag("wms-gs") %>
+This file uses code by John Deck with the participation of others (read the top of the javascript file to know more).
+
+Here is how to define a pretiled layer:
+       layer = PreTiledLayer.new("http://localhost:3000/tiles",
+       :copyright => {'prefix' => "Map C 2006", 'copyright_texts' => ["Open Atlas"]},
+       :zoom_range => 13..13, :opacity => 0.7, :format => "gif")
+I tell the PreTiledLayer constructor where I can find the tiles, setup the Copyright string, the valid zooms for the map, the opacity and the format. Tiles must have standardized names: <tt>tile_#{zoom}_#{x_tile}_#{y_tile}.#{format}</tt> (here the format is "gif"). You can use tools found in the YM4R gem to generate tiles in this format either from local maps or from WMS servers (useful to create tiles from geographic data files without having to run a map server or to cache images from slow servers). Again refer to the documentation of the gem for more information on how to do this.
+
+Instead of having the tiles requested directly, you can also decide to have an action on the server which takes care of it. You can used the class PreTiledLayerFromAction for this. In this case, the first argument of the constructor is an url of an action. The arguments +x+, +y+ and +z+ will be passed to it.
+       layer = PreTiledLayerFromAction.new(url_for(:action => :get_tile),
+       :copyright => {'prefix' => "Map C 2006", 'copyright_texts' => ["Open Atlas"]},
+       :zoom_range => 13..14, :opacity => 0.7)
+The other constructor arguments have the same meaning as PreTiledLayer. Here is an uninteresting example of action that serves tiles:
+       def get_tile
+          x = @params[:x]
+         y = @params[:y]
+         z = @params[:z]
+         begin
+            send_file "#{RAILS_ROOT}/public/tiles/tile_#{z}_#{x}_#{y}.png" , 
+               :type => 'image/png', :disposition => 'inline'
+          rescue Exception
+            render :nothing => true
+          end
+        end
+
+You can add a layer to a new map type the following way:
+       map_type = GMapType.new(layer,"My WMS")
+This is actually the simplest configuration possible. Your map type has only one data layer and is called "My WMS". You can add more that one layer: Either one that you have created yourself or existing ones. For example:
+       map_type = GMapType.new([GMapType::G_SATELLITE_MAP.get_tile_layers[0],layer,GMapType::G_HYBRID_MAP.get_tile_layers[1]],
+       "Test WMS")
+Here for the "Test WMS" map type, we also take the first layer of the "Satellite" map type in the background and overlay the second layer of the "Hybrid" map type (roads, country boundaries, etc... transparently overlaid on top of the preceding layers) so when the "Test WMS" map type is selected in the interface, all three layers will be displayed.
+
+Finally to add a map type to a GMap:
+       @map.add_map_type_init(map_type)
+If you want to wipe out the existing map types (for example the 3 default ones), you can add a +false+ argument to the +add_map_type_init+ method and the +map_type+ will be the only one.
+
+If you want to setup the map as the default one when the map is initially displayed, you should first declare the map type then add it to the map as indicated above and finally setting it as the default map type:
+       @map.declare_init(map_type,"my_map_type")
+       @map.add_map_type_init(map_type)
+       @map.set_map_type_init(map_type)
+Future versions of the plugin may simplify that.
+
+===Google Geocoding
+A helper to perform geocoding on the server side (in Ruby) is included. Here is an example of request:
+       results = Geocoding::get("Rue Clovis Paris")
+You can also pass to the +get+ method an options hash to manage the various API key options (see the section on <tt>GMap.header</tt> for details). +results+ is an array of Geocoding::Placemark objects, with 2 additional attributes: +status+ and +name+. You should check if +status+ equals <tt>Geocoding::GEO_SUCCESS</tt> to know if the request has been successful. You can then access the various data elements.
+
+Here is an example that will display a marker on Paris:
+       results = Geocoding::get("Rue Clovis Paris")
+       if results.status == Geocoding::GEO_SUCCESS
+               coord = results[0].latlon
+               @map.overlay_init(GMarker.new(coord,:info_window => "Rue Clovis Paris"))
+       end
+
+You could also have performed the geocoding on the client side with the following code, which is functionnality equivalent to the code above:
+       GMarker.new("Rue Clovis Paris",:info_window => "Rue Clovis Paris")
+
+
+==Recent changes
+- GMarker can now be placed by address (in addition to coordinates). Some code to geocode the address when the marker is initialized is added
+- Addition of a +center_zoom_on_points_init+ to center and zoom on a group of pixel
+- In JS, addition of methods to GMap2 and GMarkerGroup to center and zoom on a group of points or markers (thanks to Glen Barnes)
+- Support for easy setup of fullscreen maps
+
+==TODO
+- Add support for easy manipulation of external Google Maps-related libraries: Advanced tooltip manipulation (PdMarker),...
+- Addition of all GeoRss vocabularies (with all features: polylines...) to the geoRssOverlay extension
+- Tutorials
+
+==Disclaimer
+This software is not endorsed in any way by Google.
+
+==Acknowledgement
+The YM4R/GM plugin bundles JavaScript libraries from John Deck (WMS layers on Google Maps), Jef Poskanzer (Clusterer on Google Maps) and Mikel Maron (GeoRss on Google Maps).
+
+==License
+The YM4R/GM plugin is released under the MIT license. The <tt>clusterer.js</tt> file is redistributed with a different license (but still compatible with the MIT license). Check the top of the file in <tt>PLUGIN_ROOT/javascript</tt> to know more.
+
+==Support
+Any questions, enhancement proposals, bug notifications or corrections can be sent to mailto:guilhem.vellut+ym4r@gmail.com.
diff --git a/vendor/plugins/ym4r_gm/gmaps_api_key.yml b/vendor/plugins/ym4r_gm/gmaps_api_key.yml
new file mode 100644 (file)
index 0000000..c9a004c
--- /dev/null
@@ -0,0 +1,7 @@
+#Fill here the Google Maps API keys for your application\r
+#In this sample:\r
+#For development and test, we have only one possible host (localhost:3000), so there is only a single key associated with the mode.\r
+#In production, the app can be accessed through 2 different hosts: thepochisuperstarmegashow.com and exmaple.com. There then needs a 2-key hash. If you deployed to one host, only the API key would be needed (as in development and test).\r
+\r
+development:\r
+ABQIAAAA479zRK1hoNqMcKLTMuBcTRScPKE_l4RVNk_lv74wWGSk9YyVlRQ16fPZdTl-PBiKfGdEjSpSL8gVtA\r
diff --git a/vendor/plugins/ym4r_gm/init.rb b/vendor/plugins/ym4r_gm/init.rb
new file mode 100644 (file)
index 0000000..7316aef
--- /dev/null
@@ -0,0 +1,3 @@
+require 'ym4r_gm'\r
+\r
+\r
diff --git a/vendor/plugins/ym4r_gm/install.rb b/vendor/plugins/ym4r_gm/install.rb
new file mode 100644 (file)
index 0000000..68c5e39
--- /dev/null
@@ -0,0 +1,10 @@
+require 'fileutils'
+
+#Copy the Javascript files
+FileUtils.copy(Dir[File.dirname(__FILE__) + '/javascript/*.js'], File.dirname(__FILE__) + '/../../../public/javascripts/')
+
+#copy the gmaps_api_key file
+gmaps_config = File.dirname(__FILE__) + '/../../../config/gmaps_api_key.yml'
+unless File.exist?(gmaps_config)
+  FileUtils.copy(File.dirname(__FILE__) + '/gmaps_api_key.yml.sample',gmaps_config)
+end
diff --git a/vendor/plugins/ym4r_gm/javascript/clusterer.js b/vendor/plugins/ym4r_gm/javascript/clusterer.js
new file mode 100644 (file)
index 0000000..eeb6dd9
--- /dev/null
@@ -0,0 +1,444 @@
+// Clusterer.js - marker clustering routines for Google Maps apps
+//
+// The original version of this code is available at:
+// http://www.acme.com/javascript/
+//
+// Copyright Â© 2005,2006 by Jef Poskanzer <jef@mail.acme.com>.
+// All rights reserved.
+//
+// Modified for inclusion into the YM4R library in accordance with the 
+// following license:
+//
+// Redistribution and use in source and binary forms, with or without
+// modification, are permitted provided that the following conditions
+// are met:
+// 1. Redistributions of source code must retain the above copyright
+//    notice, this list of conditions and the following disclaimer.
+// 2. Redistributions in binary form must reproduce the above copyright
+//    notice, this list of conditions and the following disclaimer in the
+//    documentation and/or other materials provided with the distribution.
+//
+// THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
+// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+// ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
+// FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+// DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+// OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+// HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+// LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+// OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+// SUCH DAMAGE.
+//
+// For commentary on this license please see http://www.acme.com/license.html
+
+
+// Constructor.
+Clusterer = function(markers,icon,maxVisibleMarkers,gridSize,minMarkersPerCluster,maxLinesPerInfoBox) {        
+    this.markers = [];
+    if(markers){
+       for(var i =0 ; i< markers.length ; i++){
+           this.addMarker(markers[i]);
+       }
+    }    
+    this.clusters = [];
+    this.timeout = null;
+        
+    this.maxVisibleMarkers = maxVisibleMarkers || 150;
+    this.gridSize = gridSize || 5;
+    this.minMarkersPerCluster = minMarkersPerCluster || 5;
+    this.maxLinesPerInfoBox = maxLinesPerInfoBox || 10;
+    
+    this.icon = icon || G_DEFAULT_ICON;
+}
+
+Clusterer.prototype = new GOverlay();
+
+Clusterer.prototype.initialize = function ( map ){
+    this.map = map;
+    this.currentZoomLevel = map.getZoom();
+   
+    GEvent.addListener( map, 'zoomend', Clusterer.makeCaller( Clusterer.display, this ) );
+    GEvent.addListener( map, 'moveend', Clusterer.makeCaller( Clusterer.display, this ) );
+    GEvent.addListener( map, 'infowindowclose', Clusterer.makeCaller( Clusterer.popDown, this ) );
+    //Set map for each marker
+    for(var i = 0,len = this.markers.length ; i < len ; i++){
+       this.markers[i].setMap( map );
+    }
+    this.displayLater();
+}
+
+Clusterer.prototype.remove = function(){
+     for ( var i = 0; i < this.markers.length; ++i ){
+        this.removeMarker(this.markers[i]);
+     }
+}
+
+Clusterer.prototype.copy = function(){
+    return new Clusterer(this.markers,this.icon,this.maxVisibleMarkers,this.gridSize,this.minMarkersPerCluster,this.maxLinesPerInfoBox);
+}
+
+Clusterer.prototype.redraw = function(force){
+    this.displayLater();
+}
+
+// Call this to change the cluster icon.
+Clusterer.prototype.setIcon = function ( icon ){
+    this.icon = icon;
+}
+
+// Call this to add a marker.
+Clusterer.prototype.addMarker = function ( marker, description){
+    marker.onMap = false;
+    this.markers.push( marker );
+    marker.description = marker.description || description;
+    if(this.map != null){
+       marker.setMap(this.map);
+       this.displayLater();
+    }
+};
+
+
+// Call this to remove a marker.
+Clusterer.prototype.removeMarker = function ( marker ){
+    for ( var i = 0; i < this.markers.length; ++i )
+       if ( this.markers[i] == marker ){
+           if ( marker.onMap )
+               this.map.removeOverlay( marker );
+           for ( var j = 0; j < this.clusters.length; ++j ){
+               var cluster = this.clusters[j];
+               if ( cluster != null ){
+                   for ( var k = 0; k < cluster.markers.length; ++k )
+                       if ( cluster.markers[k] == marker ){
+                           cluster.markers[k] = null;
+                           --cluster.markerCount;
+                           break;
+                       }
+                   if ( cluster.markerCount == 0 ){
+                       this.clearCluster( cluster );
+                       this.clusters[j] = null;
+                       }
+                   else if ( cluster == this.poppedUpCluster )
+                       Clusterer.rePop( this );
+                   }
+               }
+           this.markers[i] = null;
+           break;
+           }
+    this.displayLater();
+};
+
+Clusterer.prototype.displayLater = function (){
+    if ( this.timeout != null )
+       clearTimeout( this.timeout );
+    this.timeout = setTimeout( Clusterer.makeCaller( Clusterer.display, this ), 50 );
+};
+
+Clusterer.display = function ( clusterer ){
+    var i, j, marker, cluster, len, len2;
+
+    clearTimeout( clusterer.timeout );
+
+    var newZoomLevel = clusterer.map.getZoom();
+    if ( newZoomLevel != clusterer.currentZoomLevel ){
+       // When the zoom level changes, we have to remove all the clusters.
+       for ( i = 0 , len = clusterer.clusters.length; i < len; ++i ){
+           if ( clusterer.clusters[i] != null ){
+               clusterer.clearCluster( clusterer.clusters[i] );
+               clusterer.clusters[i] = null;
+           }
+       }
+       clusterer.clusters.length = 0;
+       clusterer.currentZoomLevel = newZoomLevel;
+    }
+
+    // Get the current bounds of the visible area.
+    var bounds = clusterer.map.getBounds();
+
+    // Expand the bounds a little, so things look smoother when scrolling
+    // by small amounts.
+    var sw = bounds.getSouthWest();
+    var ne = bounds.getNorthEast();
+    var dx = ne.lng() - sw.lng();
+    var dy = ne.lat() - sw.lat();
+    dx *= 0.10;
+    dy *= 0.10;
+    bounds = new GLatLngBounds(
+      new GLatLng( sw.lat() - dy, sw.lng() - dx ),
+      new GLatLng( ne.lat() + dy, ne.lng() + dx ) 
+    );
+
+    // Partition the markers into visible and non-visible lists.
+    var visibleMarkers = [];
+    var nonvisibleMarkers = [];
+    for ( i = 0, len = clusterer.markers.length ; i < len; ++i ){
+       marker = clusterer.markers[i];
+       if ( marker != null )
+           if ( bounds.contains( marker.getPoint() ) )
+               visibleMarkers.push( marker );
+           else
+               nonvisibleMarkers.push( marker );
+    }
+
+    // Take down the non-visible markers.
+    for ( i = 0, len = nonvisibleMarkers.length ; i < len; ++i ){
+       marker = nonvisibleMarkers[i];
+       if ( marker.onMap ){
+           clusterer.map.removeOverlay( marker );
+           marker.onMap = false;
+       }
+    }
+
+    // Take down the non-visible clusters.
+    for ( i = 0, len = clusterer.clusters.length ; i < len ; ++i ){
+       cluster = clusterer.clusters[i];
+       if ( cluster != null && ! bounds.contains( cluster.marker.getPoint() ) && cluster.onMap ){
+           clusterer.map.removeOverlay( cluster.marker );
+           cluster.onMap = false;
+       }
+    }
+
+    // Clustering!  This is some complicated stuff.  We have three goals
+    // here.  One, limit the number of markers & clusters displayed, so the
+    // maps code doesn't slow to a crawl.  Two, when possible keep existing
+    // clusters instead of replacing them with new ones, so that the app pans
+    // better.  And three, of course, be CPU and memory efficient.
+    if ( visibleMarkers.length > clusterer.maxVisibleMarkers ){
+       // Add to the list of clusters by splitting up the current bounds
+       // into a grid.
+       var latRange = bounds.getNorthEast().lat() - bounds.getSouthWest().lat();
+       var latInc = latRange / clusterer.gridSize;
+       var lngInc = latInc / Math.cos( ( bounds.getNorthEast().lat() + bounds.getSouthWest().lat() ) / 2.0 * Math.PI / 180.0 );
+       for ( var lat = bounds.getSouthWest().lat(); lat <= bounds.getNorthEast().lat(); lat += latInc )
+           for ( var lng = bounds.getSouthWest().lng(); lng <= bounds.getNorthEast().lng(); lng += lngInc ){
+               cluster = new Object();
+               cluster.clusterer = clusterer;
+               cluster.bounds = new GLatLngBounds( new GLatLng( lat, lng ), new GLatLng( lat + latInc, lng + lngInc ) );
+               cluster.markers = [];
+               cluster.markerCount = 0;
+               cluster.onMap = false;
+               cluster.marker = null;
+               clusterer.clusters.push( cluster );
+           }
+
+       // Put all the unclustered visible markers into a cluster - the first
+       // one it fits in, which favors pre-existing clusters.
+       for ( i = 0, len = visibleMarkers.length ; i < len; ++i ){
+           marker = visibleMarkers[i];
+           if ( marker != null && ! marker.inCluster ){
+               for ( j = 0, len2 = clusterer.clusters.length ; j < len2 ; ++j ){
+                   cluster = clusterer.clusters[j];
+                   if ( cluster != null && cluster.bounds.contains( marker.getPoint() ) ){
+                       cluster.markers.push( marker );
+                       ++cluster.markerCount;
+                       marker.inCluster = true;
+                   }
+               }
+           }
+       }
+
+       // Get rid of any clusters containing only a few markers.
+       for ( i = 0, len = clusterer.clusters.length ; i < len ; ++i )
+           if ( clusterer.clusters[i] != null && clusterer.clusters[i].markerCount < clusterer.minMarkersPerCluster ){
+               clusterer.clearCluster( clusterer.clusters[i] );
+               clusterer.clusters[i] = null;
+           }
+
+       // Shrink the clusters list.
+       for ( i = clusterer.clusters.length - 1; i >= 0; --i )
+           if ( clusterer.clusters[i] != null )
+               break;
+           else
+               --clusterer.clusters.length;
+
+       // Ok, we have our clusters.  Go through the markers in each
+       // cluster and remove them from the map if they are currently up.
+       for ( i = 0, len = clusterer.clusters.length ; i < len; ++i ){
+           cluster = clusterer.clusters[i];
+           if ( cluster != null ){
+               for ( j = 0 , len2 = cluster.markers.length ; j < len2; ++j ){
+                   marker = cluster.markers[j];
+                   if ( marker != null && marker.onMap ){
+                       clusterer.map.removeOverlay( marker );
+                       marker.onMap = false;
+                   }
+               }
+           }
+       }
+       
+       // Now make cluster-markers for any clusters that need one.
+       for ( i = 0, len = clusterer.clusters.length; i < len; ++i ){
+           cluster = clusterer.clusters[i];
+           if ( cluster != null && cluster.marker == null ){
+               // Figure out the average coordinates of the markers in this
+               // cluster.
+               var xTotal = 0.0, yTotal = 0.0;
+               for ( j = 0, len2 = cluster.markers.length; j < len2 ; ++j ){
+                   marker = cluster.markers[j];
+                   if ( marker != null ){
+                       xTotal += ( + marker.getPoint().lng() );
+                       yTotal += ( + marker.getPoint().lat() );
+                   }
+               }
+               var location = new GLatLng( yTotal / cluster.markerCount, xTotal / cluster.markerCount );
+               marker = new GMarker( location, { icon: clusterer.icon } );
+               cluster.marker = marker;
+               GEvent.addListener( marker, 'click', Clusterer.makeCaller( Clusterer.popUp, cluster ) );
+           }
+       }
+    }
+
+    // Display the visible markers not already up and not in clusters.
+    for ( i = 0, len = visibleMarkers.length; i < len; ++i ){
+       marker = visibleMarkers[i];
+       if ( marker != null && ! marker.onMap && ! marker.inCluster )
+       {
+           clusterer.map.addOverlay( marker );
+           marker.addedToMap();
+           marker.onMap = true;
+       }
+    }
+
+    // Display the visible clusters not already up.
+    for ( i = 0, len = clusterer.clusters.length ; i < len; ++i ){
+       cluster = clusterer.clusters[i];
+       if ( cluster != null && ! cluster.onMap && bounds.contains( cluster.marker.getPoint() )){
+           clusterer.map.addOverlay( cluster.marker );
+           cluster.onMap = true;
+       }
+    }
+
+    // In case a cluster is currently popped-up, re-pop to get any new
+    // markers into the infobox.
+    Clusterer.rePop( clusterer );
+};
+
+
+Clusterer.popUp = function ( cluster ){
+    var clusterer = cluster.clusterer;
+    var html = '<table width="300">';
+    var n = 0;
+    for ( var i = 0 , len = cluster.markers.length; i < len; ++i )
+       {
+       var marker = cluster.markers[i];
+       if ( marker != null )
+           {
+           ++n;
+           html += '<tr><td>';
+           if ( marker.getIcon().smallImage != null )
+               html += '<img src="' + marker.getIcon().smallImage + '">';
+           else
+               html += '<img src="' + marker.getIcon().image + '" width="' + ( marker.getIcon().iconSize.width / 2 ) + '" height="' + ( marker.getIcon().iconSize.height / 2 ) + '">';
+           html += '</td><td>' + marker.description + '</td></tr>';
+           if ( n == clusterer.maxLinesPerInfoBox - 1 && cluster.markerCount > clusterer.maxLinesPerInfoBox  )
+               {
+               html += '<tr><td colspan="2">...and ' + ( cluster.markerCount - n ) + ' more</td></tr>';
+               break;
+               }
+           }
+       }
+    html += '</table>';
+    clusterer.map.closeInfoWindow();
+    cluster.marker.openInfoWindowHtml( html );
+    clusterer.poppedUpCluster = cluster;
+};
+
+Clusterer.rePop = function ( clusterer ){
+    if ( clusterer.poppedUpCluster != null )
+       Clusterer.popUp( clusterer.poppedUpCluster );
+};
+
+Clusterer.popDown = function ( clusterer ){
+    clusterer.poppedUpCluster = null;
+};
+
+Clusterer.prototype.clearCluster = function ( cluster ){
+    var i, marker;
+
+    for ( i = 0; i < cluster.markers.length; ++i ){
+       if ( cluster.markers[i] != null ){
+           cluster.markers[i].inCluster = false;
+           cluster.markers[i] = null;
+       }
+    }
+    
+    cluster.markers.length = 0;
+    cluster.markerCount = 0;
+    
+    if ( cluster == this.poppedUpCluster )
+       this.map.closeInfoWindow();
+    
+    if ( cluster.onMap )
+    {
+       this.map.removeOverlay( cluster.marker );
+       cluster.onMap = false;
+    }
+};
+
+// This returns a function closure that calls the given routine with the
+// specified arg.
+Clusterer.makeCaller = function ( func, arg ){
+    return function () { func( arg ); };
+};
+
+
+// Augment GMarker so it handles markers that have been created but
+// not yet addOverlayed.
+GMarker.prototype.setMap = function ( map ){
+    this.map = map;
+};
+
+GMarker.prototype.getMap = function (){
+    return this.map;
+}
+
+GMarker.prototype.addedToMap = function (){
+    this.map = null;
+};
+
+
+GMarker.prototype.origOpenInfoWindow = GMarker.prototype.openInfoWindow;
+GMarker.prototype.openInfoWindow = function ( node, opts ){
+    if ( this.map != null )
+       return this.map.openInfoWindow( this.getPoint(), node, opts );
+    else
+       return this.origOpenInfoWindow( node, opts );
+};
+
+GMarker.prototype.origOpenInfoWindowHtml = GMarker.prototype.openInfoWindowHtml;
+GMarker.prototype.openInfoWindowHtml = function ( html, opts ){
+    if ( this.map != null )
+       return this.map.openInfoWindowHtml( this.getPoint(), html, opts );
+    else
+       return this.origOpenInfoWindowHtml( html, opts );
+};
+
+GMarker.prototype.origOpenInfoWindowTabs = GMarker.prototype.openInfoWindowTabs;
+GMarker.prototype.openInfoWindowTabs = function ( tabNodes, opts ){
+    if ( this.map != null )
+       return this.map.openInfoWindowTabs( this.getPoint(), tabNodes, opts );
+    else
+       return this.origOpenInfoWindowTabs( tabNodes, opts );
+};
+
+GMarker.prototype.origOpenInfoWindowTabsHtml = GMarker.prototype.openInfoWindowTabsHtml;
+GMarker.prototype.openInfoWindowTabsHtml = function ( tabHtmls, opts ){
+    if ( this.map != null )
+       return this.map.openInfoWindowTabsHtml( this.getPoint(), tabHtmls, opts );
+    else
+       return this.origOpenInfoWindowTabsHtml( tabHtmls, opts );
+};
+
+GMarker.prototype.origShowMapBlowup = GMarker.prototype.showMapBlowup;
+GMarker.prototype.showMapBlowup = function ( opts ){
+    if ( this.map != null )
+       return this.map.showMapBlowup( this.getPoint(), opts );
+    else
+       return this.origShowMapBlowup( opts );
+};
+
+
+function addDescriptionToMarker(marker, description){
+    marker.description = description;
+    return marker;
+}
diff --git a/vendor/plugins/ym4r_gm/javascript/geoRssOverlay.js b/vendor/plugins/ym4r_gm/javascript/geoRssOverlay.js
new file mode 100644 (file)
index 0000000..315c26d
--- /dev/null
@@ -0,0 +1,194 @@
+// GeoRssOverlay: GMaps API extension to display a group of markers from
+// a RSS feed
+//
+// Copyright 2006 Mikel Maron (email: mikel_maron yahoo com)
+//
+// The original version of this code is called MGeoRSS and can be found
+// at the following address:
+// http://brainoff.com/gmaps/mgeorss.html
+//
+// Modified by Andrew Turner to add support for the GeoRss Simple vocabulary
+//
+// Modified and bundled with YM4R in accordance with the following
+// license:
+//
+// This work is public domain
+
+function GeoRssOverlay(rssurl,icon,proxyurl,options){
+    this.rssurl = rssurl;
+    this.icon = icon;
+    this.proxyurl = proxyurl;
+    if(options['visible'] == undefined)
+       this.visible = true;
+    else
+       this.visible = options['visible'];
+    this.listDiv = options['listDiv']; //ID of the item list DIV
+    this.contentDiv = options['contentDiv']; //ID of the content DIV
+    this.listItemClass = options['listItemClass']; //Class of the list item DIV
+    this.limitItems = options['limit']; //Maximum number of displayed entries
+    this.request = false;
+    this.markers = [];
+}
+
+GeoRssOverlay.prototype = new GOverlay();
+
+GeoRssOverlay.prototype.initialize=function(map) {
+    this.map = map;
+    this.load();
+}
+
+GeoRssOverlay.prototype.redraw = function(force){
+    //nothing to do : the markers are already taken care of
+}
+
+GeoRssOverlay.prototype.remove = function(){
+    for(var i= 0, len = this.markers.length ; i< len; i++){
+       this.map.removeOverlay(this.markers[i]);
+    }
+}
+
+GeoRssOverlay.prototype.showHide=function() {
+    if (this.visible) {
+       for (var i=0;i<this.markers.length;i++) {
+           this.map.removeOverlay(this.markers[i]);
+       }
+       this.visible = false;
+    } else {
+       for (var i=0;i<this.markers.length;i++) {
+           this.map.addOverlay(this.markers[i]);
+       }
+       this.visible = true;
+    }
+}
+
+GeoRssOverlay.prototype.showMarker = function(id){
+    var marker = this.markers[id];
+    if(marker != undefined){
+       GEvent.trigger(marker,"click");
+    }
+}
+
+GeoRssOverlay.prototype.copy = function(){
+    var oCopy = new GeoRssOVerlay(this.rssurl,this.icon,this.proxyurl);
+    oCopy.markers = [];
+    for(var i = 0 , len = this.markers.length ;i < len ; i++){
+       oCopy.markers.push(this.markers[i].copy());
+    }
+    return oCopy;
+}
+
+GeoRssOverlay.prototype.load=function() {
+    if (this.request != false) { 
+       return; 
+    }
+    this.request = GXmlHttp.create();
+    if (this.proxyurl != undefined) {
+       this.request.open("GET",this.proxyurl + '?q=' + encodeURIComponent(this.rssurl),true);
+    } else {
+       this.request.open("GET",this.rssurl, true);
+    }
+    var m = this;
+    this.request.onreadystatechange = function() {
+       m.callback();
+    }
+    this.request.send(null);
+}
+
+GeoRssOverlay.prototype.callback = function() {
+    if (this.request.readyState == 4) {
+       if (this.request.status == "200") {
+           var xmlDoc = this.request.responseXML;
+           if(xmlDoc.documentElement.getElementsByTagName("item").length != 0){
+               //RSS
+               var items = xmlDoc.documentElement.getElementsByTagName("item");
+           }else if(xmlDoc.documentElement.getElementsByTagName("entry").length != 0){
+               //Atom
+               var items = xmlDoc.documentElement.getElementsByTagName("entry");
+           }
+           for (var i = 0, len = this.limitItems?Math.min(this.limitItems,items.length):items.length; i < len; i++) {
+               try {
+                   var marker = this.createMarker(items[i],i);
+                   this.markers.push(marker);
+                   if(this.visible){
+                       this.map.addOverlay(marker);
+                   }
+               } catch (e) {
+               }
+           }
+       }
+       this.request = false;
+    }
+}
+
+GeoRssOverlay.prototype.createMarker = function(item,index) {
+    
+    var title = item.getElementsByTagName("title")[0].childNodes[0].nodeValue;
+    if(item.getElementsByTagName("description").length != 0){
+       //Rss
+       var description = item.getElementsByTagName("description")[0].childNodes[0].nodeValue;
+       var link = item.getElementsByTagName("link")[0].childNodes[0].nodeValue;    }else if(item.getElementsByTagName("summary").length != 0){
+       //Atom
+       var description = item.getElementsByTagName("summary")[0].childNodes[0].nodeValue;
+       var link = item.getElementsByTagName("link")[0].attributes[0].nodeValue;
+       }
+    /* namespaces are handled by spec in moz, not in ie */
+    if (navigator.userAgent.toLowerCase().indexOf("msie") < 0) {
+               if(item.getElementsByTagNameNS("http://www.w3.org/2003/01/geo/wgs84_pos#","lat").length != 0){
+           //W3C Geo Vocabulary
+           var lat = item.getElementsByTagNameNS("http://www.w3.org/2003/01/geo/wgs84_pos#","lat")[0].childNodes[0].nodeValue;
+           var lng = item.getElementsByTagNameNS("http://www.w3.org/2003/01/geo/wgs84_pos#","long")[0].childNodes[0].nodeValue;
+       }else if(item.getElementsByTagNameNS("http://www.georss.org/georss","point").length != 0){
+           
+           //Simple
+           var latlng = item.getElementsByTagNameNS("http://www.georss.org/georss","point")[0].childNodes[0].nodeValue.split(" ");
+           var lat = latlng[0];
+           var lng = latlng[1];
+       }
+    } else {
+       
+       if(item.getElementsByTagName("geo:lat").length != 0){
+           //W3C Geo Vocabulary
+           var lat = item.getElementsByTagName("geo:lat")[0].childNodes[0].nodeValue;
+           var lng = item.getElementsByTagName("geo:long")[0].childNodes[0].nodeValue;
+       }else if(item.getElementsByTagName("georss:point").length != 0){
+           //Simple
+           var latlng = item.getElementsByTagName("georss:point")[0].childNodes[0].nodeValue.split(" ");
+           var lat = latlng[0];
+           var lng = latlng[1];
+       }
+    }
+    
+    var point = new GLatLng(parseFloat(lat), parseFloat(lng));
+    var marker = new GMarker(point,{'title': title});
+    var html = "<a href=\"" + link + "\">" + title + "</a><p/>" + description;
+    
+    if(this.contentDiv == undefined){
+       GEvent.addListener(marker, "click", function() {
+           marker.openInfoWindowHtml(html);
+       });
+    }else{
+       var contentDiv = this.contentDiv;
+       GEvent.addListener(marker, "click", function() {
+           document.getElementById(contentDiv).innerHTML = html;
+       });
+    }
+    
+    if(this.listDiv != undefined){
+       var a = document.createElement('a'); 
+       a.innerHTML = title;
+       a.setAttribute("href","#");
+       var georss = this;
+       a.onclick = function(){
+           georss.showMarker(index);
+           return false;
+       };
+       var div = document.createElement('div');
+       if(this.listItemClass != undefined){
+           div.setAttribute("class",this.listItemClass);
+       }
+       div.appendChild(a);
+       document.getElementById(this.listDiv).appendChild(div);
+    }
+    
+    return marker;
+}
diff --git a/vendor/plugins/ym4r_gm/javascript/markerGroup.js b/vendor/plugins/ym4r_gm/javascript/markerGroup.js
new file mode 100644 (file)
index 0000000..02fe624
--- /dev/null
@@ -0,0 +1,114 @@
+function GMarkerGroup(active, markers, markersById) {\r
+    this.active = active;\r
+    this.markers = markers || new Array();\r
+    this.markersById = markersById || new Object();\r
+}\r
+\r
+GMarkerGroup.prototype = new GOverlay();\r
+\r
+GMarkerGroup.prototype.initialize = function(map) {\r
+    this.map = map;\r
+    \r
+    if(this.active){\r
+       for(var i = 0 , len = this.markers.length; i < len; i++) {\r
+           this.map.addOverlay(this.markers[i]);\r
+       }\r
+       for(var id in this.markersById){\r
+           this.map.addOverlay(this.markersById[id]);\r
+       }\r
+    }\r
+}\r
+\r
+//If not already done (ie if not inactive) remove all the markers from the map\r
+GMarkerGroup.prototype.remove = function() {\r
+    this.deactivate();\r
+}\r
+\r
+GMarkerGroup.prototype.redraw = function(force){\r
+    //Nothing to do : markers are already taken care of\r
+}\r
+\r
+//Copy the data to a new Marker Group\r
+GMarkerGroup.prototype.copy = function() {\r
+    var overlay = new GMarkerGroup(this.active);\r
+    overlay.markers = this.markers; //Need to do deep copy\r
+    overlay.markersById = this.markersById; //Need to do deep copy\r
+    return overlay;\r
+}\r
+\r
+//Inactivate the Marker group and clear the internal content\r
+GMarkerGroup.prototype.clear = function(){\r
+    //deactivate the map first (which removes the markers from the map)\r
+    this.deactivate();\r
+    //Clear the internal content\r
+    this.markers = new Array();\r
+    this.markersById = new Object();\r
+}\r
+\r
+//Add a marker to the GMarkerGroup ; Adds it now to the map if the GMarkerGroup is active\r
+GMarkerGroup.prototype.addMarker = function(marker,id){\r
+    if(id == undefined){\r
+       this.markers.push(marker);\r
+    }else{\r
+       this.markersById[id] = marker;\r
+    }\r
+    if(this.active && this.map != undefined ){\r
+       this.map.addOverlay(marker);\r
+    }\r
+}\r
+\r
+//Open the info window (or info window tabs) of a marker\r
+GMarkerGroup.prototype.showMarker = function(id){\r
+    var marker = this.markersById[id];\r
+    if(marker != undefined){\r
+       GEvent.trigger(marker,"click");\r
+    }\r
+}\r
+\r
+//Activate (or deactivate depending on the argument) the GMarkerGroup\r
+GMarkerGroup.prototype.activate = function(active){\r
+    active = (active == undefined) ? true : active;\r
+    if(!active){\r
+       if(this.active){\r
+           if(this.map != undefined){\r
+               for(var i = 0 , len = this.markers.length; i < len; i++){\r
+                   this.map.removeOverlay(this.markers[i])\r
+               }\r
+               for(var id in this.markersById){\r
+                   this.map.removeOverlay(this.markersById[id]);\r
+               }\r
+           }\r
+           this.active = false;\r
+       }\r
+    }else{\r
+       if(!this.active){\r
+           if(this.map != undefined){\r
+               for(var i = 0 , len = this.markers.length; i < len; i++){\r
+                   this.map.addOverlay(this.markers[i]);\r
+               }\r
+               for(var id in this.markersById){\r
+                   this.map.addOverlay(this.markersById[id]);\r
+               }\r
+           }\r
+           this.active = true;\r
+       }\r
+    }\r
+}\r
+\r
+GMarkerGroup.prototype.centerAndZoomOnMarkers = function() {\r
+    if(this.map != undefined){\r
+       //merge markers and markersById\r
+       var tmpMarkers = this.markers.slice();\r
+       for (var id in this.markersById){\r
+           tmpMarkers.push(this.markersById[id]);\r
+       }\r
+       if(tmpMarkers.length > 0){\r
+           this.map.centerAndZoomOnMarkers(tmpMarkers);\r
+       } \r
+    }\r
+}      \r
+\r
+//Deactivate the Group Overlay (convenience method)\r
+GMarkerGroup.prototype.deactivate = function(){\r
+    this.activate(false);\r
+}\r
diff --git a/vendor/plugins/ym4r_gm/javascript/wms-gs.js b/vendor/plugins/ym4r_gm/javascript/wms-gs.js
new file mode 100644 (file)
index 0000000..c67146b
--- /dev/null
@@ -0,0 +1,69 @@
+/*
+ * Call generic wms service for GoogleMaps v2
+ * John Deck, UC Berkeley
+ * Inspiration & Code from:
+ *     Mike Williams http://www.econym.demon.co.uk/googlemaps2/ V2 Reference & custommap code
+ *     Brian Flood http://www.spatialdatalogic.com/cs/blogs/brian_flood/archive/2005/07/11/39.aspx V1 WMS code
+ *     Kyle Mulka http://blog.kylemulka.com/?p=287  V1 WMS code modifications
+ *      http://search.cpan.org/src/RRWO/GPS-Lowrance-0.31/lib/Geo/Coordinates/MercatorMeters.pm
+ *
+ * Modified by Chris Holmes, TOPP to work by default with GeoServer.
+ *
+ * Bundled with YM4R with John Deck's permission.
+ * Slightly modified to fit YM4R.
+ * See johndeck.blogspot.com for the original version and for examples and instructions of how to use it.
+ */
+
+var WGS84_SEMI_MAJOR_AXIS = 6378137.0; //equatorial radius
+var WGS84_ECCENTRICITY = 0.0818191913108718138;
+var DEG2RAD=0.0174532922519943;
+var PI=3.14159267;
+
+function dd2MercMetersLng(p_lng) { 
+       return WGS84_SEMI_MAJOR_AXIS * (p_lng*DEG2RAD); 
+}
+
+function dd2MercMetersLat(p_lat) {
+        var lat_rad = p_lat * DEG2RAD;
+       return WGS84_SEMI_MAJOR_AXIS * Math.log(Math.tan((lat_rad + PI / 2) / 2) * Math.pow( ((1 - WGS84_ECCENTRICITY * Math.sin(lat_rad)) / (1 + WGS84_ECCENTRICITY * Math.sin(lat_rad))), (WGS84_ECCENTRICITY/2)));
+}
+
+function addWMSPropertiesToLayer(tile_layer,base_url,layers,styles,format,merc_proj,use_geo){
+   tile_layer.format = format;
+   tile_layer.baseURL = base_url;
+   tile_layer.styles = styles;
+   tile_layer.layers = layers;
+   tile_layer.mercatorEpsg = merc_proj;
+   tile_layer.useGeographic = use_geo;
+   return tile_layer;
+}
+
+getTileUrlForWMS=function(a,b,c) {
+       var lULP = new GPoint(a.x*256,(a.y+1)*256);
+       var lLRP = new GPoint((a.x+1)*256,a.y*256);
+       var lUL = G_NORMAL_MAP.getProjection().fromPixelToLatLng(lULP,b,c);
+       var lLR = G_NORMAL_MAP.getProjection().fromPixelToLatLng(lLRP,b,c);
+        
+       if (this.useGeographic){
+           var lBbox=lUL.x+","+lUL.y+","+lLR.x+","+lLR.y;
+          var lSRS="EPSG:4326";
+       }else{
+          var lBbox=dd2MercMetersLng(lUL.x)+","+dd2MercMetersLat(lUL.y)+","+dd2MercMetersLng(lLR.x)+","+dd2MercMetersLat(lLR.y);
+          var lSRS="EPSG:" + this.mercatorEpsg;
+        }
+       var lURL=this.baseURL;
+       lURL+="?REQUEST=GetMap";
+       lURL+="&SERVICE=WMS";
+       lURL+="&VERSION=1.1.1";
+       lURL+="&LAYERS="+this.layers;
+       lURL+="&STYLES="+this.styles; 
+       lURL+="&FORMAT=image/"+this.format;
+       lURL+="&BGCOLOR=0xFFFFFF";
+       lURL+="&TRANSPARENT=TRUE";
+       lURL+="&SRS="+lSRS;
+       lURL+="&BBOX="+lBbox;
+       lURL+="&WIDTH=256";
+       lURL+="&HEIGHT=256";
+       lURL+="&reaspect=false";
+       return lURL;
+}
diff --git a/vendor/plugins/ym4r_gm/javascript/ym4r-gm.js b/vendor/plugins/ym4r_gm/javascript/ym4r-gm.js
new file mode 100644 (file)
index 0000000..1c768df
--- /dev/null
@@ -0,0 +1,117 @@
+// JS helper functions for YM4R\r
+\r
+function addInfoWindowToMarker(marker,info,options){\r
+       GEvent.addListener(marker, "click", function() {marker.openInfoWindowHtml(info,options);});\r
+       return marker;\r
+}\r
+\r
+function addInfoWindowTabsToMarker(marker,info,options){\r
+     GEvent.addListener(marker, "click", function() {marker.openInfoWindowTabsHtml(info,options);});\r
+     return marker;\r
+}\r
+\r
+function addPropertiesToLayer(layer,getTile,copyright,opacity,isPng){\r
+    layer.getTileUrl = getTile;\r
+    layer.getCopyright = copyright;\r
+    layer.getOpacity = opacity;\r
+    layer.isPng = isPng;\r
+    return layer;\r
+}\r
+\r
+function addOptionsToIcon(icon,options){\r
+    for(var k in options){\r
+       icon[k] = options[k];\r
+    }\r
+    return icon;\r
+}\r
+\r
+function addCodeToFunction(func,code){\r
+    if(func == undefined)\r
+       return code;\r
+    else{\r
+       return function(){\r
+           func();\r
+           code();\r
+       }\r
+    }\r
+}\r
+\r
+function addGeocodingToMarker(marker,address){\r
+    marker.orig_initialize = marker.initialize;\r
+    orig_redraw = marker.redraw;\r
+    marker.redraw = function(force){}; //empty the redraw method so no error when called by addOverlay.\r
+    marker.initialize = function(map){\r
+       new GClientGeocoder().getLatLng(address,\r
+                                       function(latlng){\r
+           if(latlng){\r
+               marker.redraw = orig_redraw;\r
+               marker.orig_initialize(map); //init before setting point\r
+               marker.setPoint(latlng);\r
+           }//do nothing\r
+       });\r
+    };\r
+    return marker;\r
+}\r
+\r
+\r
+\r
+GMap2.prototype.centerAndZoomOnMarkers = function(markers) {\r
+     var bounds = new GLatLngBounds(markers[0].getPoint(),\r
+                                   markers[0].getPoint());\r
+     for (var i=1, len = markers.length ; i<len; i++) {\r
+        bounds.extend(markers[i].getPoint());\r
+     }\r
+     \r
+     this.centerAndZoomOnBounds(bounds);\r
+ } \r
+\r
+GMap2.prototype.centerAndZoomOnPoints = function(points) {\r
+     var bounds = new GLatLngBounds(points[0],\r
+                                   points[0]);\r
+     for (var i=1, len = points.length ; i<len; i++) {\r
+        bounds.extend(points[i]);\r
+     }\r
+     \r
+     this.centerAndZoomOnBounds(bounds);\r
+ } \r
+\r
+GMap2.prototype.centerAndZoomOnBounds = function(bounds) {\r
+    var center = bounds.getCenter();\r
+    this.setCenter(center, this.getBoundsZoomLevel(bounds));\r
+} \r
+\r
+//For full screen mode\r
+function setWindowDims(elem) {\r
+    if (window.innerWidth){\r
+       elem.style.height = (window.innerHeight) + 'px;';\r
+       elem.style.width = (window.innerWidth) + 'px;';\r
+    }else if (document.body.clientWidth){\r
+       elem.style.width = (document.body.clientWidth) + 'px';\r
+       elem.style.height = (document.body.clientHeight) + 'px';\r
+    }\r
+}\r
+\r
+ManagedMarker = function(markers,minZoom,maxZoom) {\r
+    this.markers = markers;\r
+    this.minZoom = minZoom;\r
+    this.maxZoom = maxZoom;\r
+}\r
+\r
+//Add the markers and refresh\r
+function addMarkersToManager(manager,managedMarkers){\r
+    for(var i = 0, length = managedMarkers.length; i < length;i++) {\r
+       mm = managedMarkers[i];\r
+       manager.addMarkers(mm.markers,mm.minZoom,mm.maxZoom);\r
+    }\r
+    manager.refresh();\r
+    return manager;\r
+}\r
+\r
+\r
+var INVISIBLE = new GLatLng(0,0); //almost always invisible\r
+\r
+if(self.Event && Event.observe){\r
+    Event.observe(window, 'unload', GUnload);\r
+}else{\r
+    window.onunload = GUnload;\r
+}\r
diff --git a/vendor/plugins/ym4r_gm/lib/gm_plugin/control.rb b/vendor/plugins/ym4r_gm/lib/gm_plugin/control.rb
new file mode 100644 (file)
index 0000000..99b3e58
--- /dev/null
@@ -0,0 +1,64 @@
+module Ym4r\r
+  module GmPlugin\r
+    #Small map control. Report to the Google Maps API documentation for details.\r
+    class GSmallMapControl\r
+      include MappingObject\r
+      def create\r
+        "new GSmallMapControl()"\r
+      end\r
+    end\r
+    #Large Map control. Report to the Google Maps API documentation for details.\r
+    class GLargeMapControl\r
+      include MappingObject\r
+      def create\r
+        "new GLargeMapControl()"\r
+      end\r
+    end\r
+    #Small Zoom control. Report to the Google Maps API documentation for details.\r
+    class GSmallZoomControl\r
+      include MappingObject\r
+      def create\r
+        "new GSmallZoomControl()"\r
+      end\r
+    end\r
+    #Scale control. Report to the Google Maps API documentation for details.\r
+    class GScaleControl\r
+      include MappingObject\r
+      def create\r
+        "new GScaleControl()"\r
+      end\r
+    end\r
+    #Map type control. Report to the Google Maps API documentation for details.\r
+    class GMapTypeControl\r
+      include MappingObject\r
+      def create\r
+        "new GMapTypeControl()"\r
+      end\r
+    end\r
+    #Overview map control. Report to the Google Maps API documentation for details.\r
+    class GOverviewMapControl\r
+      include MappingObject\r
+      def create\r
+        "new GOverviewMapControl()"\r
+      end\r
+    end\r
+\r
+    #An object representing a position of a control.\r
+    #The first argument of the constructor is one of the following : :top_right, :top_left, :bottom_right, :bottom_left.\r
+    class GControlPosition < Struct.new(:anchor,:offset)\r
+      include MappingObject\r
+      def create\r
+        js_anchor = if anchor == :top_right\r
+                      "G_ANCHOR_TOP_RIGHT"\r
+                    elsif anchor == :top_left\r
+                      "G_ANCHOR_TOP_LEFT"\r
+                    elsif anchor == :bottom_right\r
+                      "G_ANCHOR_BOTTOM_RIGHT"\r
+                    else\r
+                      "G_ANCHOR_BOTTOM_LEFT"\r
+                    end\r
+        "new GControlPosition(#{js_anchor},#{offset})"\r
+      end\r
+    end\r
+  end\r
+end\r
diff --git a/vendor/plugins/ym4r_gm/lib/gm_plugin/geocoding.rb b/vendor/plugins/ym4r_gm/lib/gm_plugin/geocoding.rb
new file mode 100644 (file)
index 0000000..ea015eb
--- /dev/null
@@ -0,0 +1,116 @@
+require 'open-uri'\r
+require 'rexml/document'\r
+\r
+module Ym4r\r
+  module GmPlugin\r
+    module Geocoding\r
+\r
+      GEO_SUCCESS = 200\r
+      GEO_MISSING_ADDRESS = 601\r
+      GEO_UNKNOWN_ADDRESS = 602\r
+      GEO_UNAVAILABLE_ADDRESS = 603\r
+      GEO_BAD_KEY = 610\r
+      GEO_TOO_MANY_QUERIES = 620\r
+      GEO_SERVER_ERROR = 500\r
+      \r
+      #Gets placemarks by querying the Google Maps Geocoding service with the +request+ string. Options can either an explicity GMaps API key (<tt>:key</tt>) or a host, (<tt>:host</tt>). \r
+      def self.get(request,options = {})\r
+        api_key = ApiKey.get(options)\r
+        output =  options[:output] || "kml"\r
+        url = "http://maps.google.com/maps/geo?q=#{URI.encode(request)}&key=#{api_key}&output=#{output}"\r
+\r
+        res = open(url).read\r
+\r
+        case output.to_sym\r
+          when :json\r
+          res = eval(res.gsub(":","=>")) #!!!EVAL EVAL EVAL EVAL!!! hopefully we can trust google...\r
+          placemarks = Placemarks.new(res['name'],res['Status']['code'])\r
+          if res['Placemark']\r
+            placemark = res['Placemark']\r
+   \r
+            placemark.each do |data|\r
+              \r
+              data_country = data['Country']['CountryNameCode'] rescue ""\r
+              data_administrative = data['Country']['AdministrativeArea']['AdministrativeAreaName'] rescue ""\r
+              data_sub_administrative = data['Country']['AdministrativeArea']['SubAdministrativeArea']['SubAdministrativeAreaName'] rescue ""\r
+              data_locality = data['Country']['AdministrativeArea']['SubAdministrativeArea']['Locality']['LocalityName'] rescue ""\r
+              data_dependent_locality = data['Country']['AdministrativeArea']['SubAdministrativeArea']['Locality']['DependentLocality']['DependentLocalityName'] rescue ""\r
+              data_thoroughfare = data['Country']['AdministrativeArea']['SubAdministrativeArea']['Locality']['DependentLocality']['Thoroughfare']['ThoroughfareName'] rescue ""\r
+              data_postal_code = data['Country']['AdministrativeArea']['SubAdministrativeArea']['Locality']['DependentLocality']['Thoroughfare']['PostalCode']['PostalCodeNumber'] rescue ""\r
+              lon, lat = data['Point']['coordinates'][0,2]\r
+              data_accuracy = data['Accuracy']\r
+              unless data_accuracy.nil?\r
+                data_accuracy = data_accuracy.to_i\r
+              end\r
+        \r
+              placemarks << Geocoding::Placemark.new(data['address'],\r
+                                                     data_country,\r
+                                                     data_administrative,\r
+                                                     data_sub_administrative,\r
+                                                     data_locality,\r
+                                                     data_dependent_locality,\r
+                                                     data_thoroughfare,\r
+                                                     data_postal_code,\r
+                                                     lon, lat, data_accuracy)\r
+                                                     \r
+            end\r
+          end\r
+          when :kml, :xml\r
+          \r
+          doc = REXML::Document.new(res) \r
+\r
+          response = doc.elements['//Response']\r
+          placemarks = Placemarks.new(response.elements['name'].text,response.elements['Status/code'].text.to_i)\r
+          response.elements.each(".//Placemark") do |placemark|\r
+            data = placemark.elements\r
+            data_country = data['.//CountryNameCode']\r
+            data_administrative = data['.//AdministrativeAreaName']\r
+            data_sub_administrative = data['.//SubAdministrativeAreaName']\r
+            data_locality = data['.//LocalityName']\r
+            data_dependent_locality = data['.//DependentLocalityName']\r
+            data_thoroughfare = data['.//ThoroughfareName']\r
+            data_postal_code = data['.//PostalCodeNumber']\r
+            lon, lat = data['.//coordinates'].text.split(",")[0..1].collect {|l| l.to_f }\r
+            data_accuracy = data['.//*[local-name()="AddressDetails"]'].attributes['Accuracy']\r
+            unless data_accuracy.nil?\r
+               data_accuracy = data_accuracy.to_i\r
+             end\r
+            placemarks << Geocoding::Placemark.new(data['address'].text,\r
+                                                   data_country.nil? ? "" : data_country.text,\r
+                                                   data_administrative.nil? ? "" : data_administrative.text,\r
+                                                   data_sub_administrative.nil? ? "" : data_sub_administrative.text,\r
+                                                   data_locality.nil? ? "" : data_locality.text,\r
+                                                   data_dependent_locality.nil? ? "" : data_dependent_locality.text,\r
+                                                   data_thoroughfare.nil? ? "" : data_thoroughfare.text,\r
+                                                   data_postal_code.nil? ? "" : data_postal_code.text,\r
+                                                   lon, lat, data_accuracy )\r
+          end\r
+        end\r
+                \r
+        placemarks\r
+      end\r
+\r
+      #Group of placemarks returned by the Geocoding service. If the result is valid the +status+ attribute should be equal to <tt>Geocoding::GE0_SUCCESS</tt>\r
+      class Placemarks < Array\r
+        attr_accessor :name,:status\r
+\r
+        def initialize(name,status)\r
+          super(0)\r
+          @name = name\r
+          @status = status\r
+        end\r
+      end\r
+\r
+      #A result from the Geocoding service.\r
+      class Placemark < Struct.new(:address,:country_code,:administrative_area,:sub_administrative_area,:locality,:dependent_locality,:thoroughfare,:postal_code,:longitude,:latitude,:accuracy)\r
+        def lonlat\r
+          [longitude,latitude]\r
+        end\r
+\r
+        def latlon\r
+          [latitude,longitude]\r
+        end\r
+      end\r
+    end\r
+  end\r
+end\r
diff --git a/vendor/plugins/ym4r_gm/lib/gm_plugin/helper.rb b/vendor/plugins/ym4r_gm/lib/gm_plugin/helper.rb
new file mode 100644 (file)
index 0000000..ddaf8bb
--- /dev/null
@@ -0,0 +1,41 @@
+\r
+Ym4r::GmPlugin::GPolyline.class_eval do\r
+  #Creates a GPolyline object from a georuby line string. Assumes the points of the line strings are stored in Longitude(x)/Latitude(y) order.\r
+  def self.from_georuby(line_string,color = nil,weight = nil,opacity = nil)\r
+    GPolyline.new(line_string.points.collect { |point| GLatLng.new([point.y,point.x])},color,weight,opacity)\r
+  end\r
+end\r
+\r
+Ym4r::GmPlugin::GMarker.class_eval do\r
+  #Creates a GMarker object from a georuby point. Accepts the same options as the GMarker constructor. Assumes the points of the line strings are stored in Longitude(x)/Latitude(y) order.\r
+  def self.from_georuby(point,options = {})\r
+    GMarker.new([point.y,point.x],options)\r
+  end\r
+end\r
+\r
+Ym4r::GmPlugin::GLatLng.class_eval do\r
+  #Creates a GLatLng object from a georuby point. Assumes the points of the line strings are stored in Longitude(x)/Latitude(y) order.\r
+  def self.from_georuby(point,unbounded = nil)\r
+    GLatLng.new([point.y,point.x],unbounded)\r
+  end\r
+end\r
+\r
+Ym4r::GmPlugin::GLatLngBounds.class_eval do\r
+  #Creates a GLatLng object from a georuby point. Assumes the points of the line strings are stored in Longitude(x)/Latitude(y) order.\r
+  def self.from_georuby(envelope)\r
+    GLatLngBounds.new(GLatLng.from_georuby(envelope.lower_corner),\r
+                      GLatLng.from_georuby(envelope.upper_corner))\r
+  end\r
+end\r
+\r
+Ym4r::GmPlugin::GPolygon.class_eval do\r
+  #Creates a GPolygon object from a georuby polygon or line string. Assumes the points of the line strings are stored in Longitude(x)/Latitude(y) order.\r
+  def self.from_georuby(ls_or_p, stroke_color="#000000",stroke_weight=1,stroke_opacity=1.0,color="#ff0000",opacity=1.0)\r
+    if ls_or_p.is_a?(GeoRuby::SimpleFeatures::LineString)\r
+      GPolygon.new(ls_or_p.collect { |point| GLatLng.new([point.y,point.x])},stroke_color,stroke_weight,stroke_opacity,color,opacity)\r
+    else\r
+      GPolygon.new(ls_or_p[0].collect { |point| GLatLng.new([point.y,point.x])},stroke_color,stroke_weight,stroke_opacity,color,opacity)\r
+    end\r
+  end\r
+end\r
+\r
diff --git a/vendor/plugins/ym4r_gm/lib/gm_plugin/key.rb b/vendor/plugins/ym4r_gm/lib/gm_plugin/key.rb
new file mode 100644 (file)
index 0000000..0de9c18
--- /dev/null
@@ -0,0 +1,37 @@
+module Ym4r\r
+  module GmPlugin\r
+    class GMapsAPIKeyConfigFileNotFoundException < StandardError\r
+    end\r
+        \r
+    class AmbiguousGMapsAPIKeyException < StandardError\r
+    end\r
+    \r
+    #Class fo the manipulation of the API key\r
+    class ApiKey\r
+      #Read the API key config for the current ENV\r
+      unless File.exist?(RAILS_ROOT + '/config/gmaps_api_key.yml')\r
+        raise GMapsAPIKeyConfigFileNotFoundException.new("File RAILS_ROOT/config/gmaps_api_key.yml not found")\r
+      else\r
+        env = ENV['RAILS_ENV'] || RAILS_ENV\r
+        GMAPS_API_KEY = YAML.load_file(RAILS_ROOT + '/config/gmaps_api_key.yml')[env]\r
+      end\r
+      \r
+      def self.get(options = {})\r
+        if options.has_key?(:key)\r
+          options[:key]\r
+        elsif GMAPS_API_KEY.is_a?(Hash)\r
+          #For this environment, multiple hosts are possible.\r
+          #:host must have been passed as option\r
+          if options.has_key?(:host)\r
+            GMAPS_API_KEY[options[:host]]\r
+          else\r
+            raise AmbiguousGMapsAPIKeyException.new(GMAPS_API_KEY.keys.join(","))\r
+          end\r
+        else\r
+          #Only one possible key: take it and ignore the :host option if it is there\r
+          GMAPS_API_KEY\r
+        end\r
+      end\r
+    end\r
+  end\r
+end\r
diff --git a/vendor/plugins/ym4r_gm/lib/gm_plugin/layer.rb b/vendor/plugins/ym4r_gm/lib/gm_plugin/layer.rb
new file mode 100644 (file)
index 0000000..bab6625
--- /dev/null
@@ -0,0 +1,125 @@
+module Ym4r\r
+  module GmPlugin\r
+    #Map types of the map\r
+    class GMapType\r
+      include MappingObject\r
+      \r
+      G_NORMAL_MAP = Variable.new("G_NORMAL_MAP")\r
+      G_SATELLITE_MAP = Variable.new("G_SATELLITE_MAP")\r
+      G_HYBRID_MAP = Variable.new("G_HYBRID_MAP")\r
+      \r
+      attr_accessor :layers, :name, :projection, :options\r
+      \r
+      #The options can be any of the GMapType options detailed in the documentation + a <tt>:projection</tt>.\r
+      def initialize(layers, name, options = {})\r
+        @layers = layers\r
+        @name = name\r
+        @projection = options.delete(:projection) || GMercatorProjection.new\r
+        @options = options\r
+      end\r
+\r
+      def create\r
+        "new GMapType(#{MappingObject.javascriptify_variable(Array(layers))}, #{MappingObject.javascriptify_variable(projection)}, #{MappingObject.javascriptify_variable(name)}, #{MappingObject.javascriptify_variable(options)})"\r
+      end\r
+    end\r
+\r
+    #Represents a mercator projection for zoom levels 0 to 17 (more than that by passing an argument to the constructor)\r
+    class GMercatorProjection\r
+      include MappingObject\r
+      \r
+      attr_accessor :n\r
+      \r
+      def initialize(n = nil)\r
+        @n = n\r
+      end\r
+\r
+      def create\r
+        if n.nil?\r
+          return "G_NORMAL_MAP.getProjection()"\r
+        else\r
+          "new GMercatorProjection(#{@n})"\r
+        end\r
+      end\r
+    end\r
+\r
+    #Abstract Tile layer. Subclasses must implement a get_tile_url method.\r
+    class GTileLayer\r
+      include MappingObject\r
+            \r
+      attr_accessor :opacity, :zoom_range, :copyright, :format\r
+\r
+      #Options are the following, with default values:\r
+      #:zoom_range (0..17), :copyright ({'prefix' => '', 'copyright_texts' => [""]}), :opacity (1.0), :format ("png")\r
+      def initialize(options = {})\r
+        @opacity = options[:opacity] || 1.0\r
+        @zoom_range = options[:zoom_range] || (0..17)\r
+        @copyright = options[:copyright] || {'prefix' => '', 'copyright_texts' => [""]}\r
+        @format = (options[:format] || "png").to_s\r
+      end\r
+\r
+      def create\r
+        "addPropertiesToLayer(new GTileLayer(new GCopyrightCollection(\"\"),#{zoom_range.begin},#{zoom_range.end}),#{get_tile_url},function(a,b) {return #{MappingObject.javascriptify_variable(@copyright)};}\n,function() {return #{@opacity};},function(){return #{@format == "png"};})"\r
+      end\r
+      \r
+      #for subclasses to implement\r
+      def get_tile_url\r
+      end\r
+    end\r
+    \r
+    #Represents a pre tiled layer, taking images directly from a server, without using a server script.\r
+    class PreTiledLayer < GTileLayer\r
+      attr_accessor :base_url\r
+      \r
+      #Possible options are the same as for the GTileLayer constructor\r
+      def initialize(base_url,options = {})\r
+        super(options)\r
+        @base_url = base_url\r
+      end\r
+      \r
+      #Returns the code to determine the url to fetch the tile. Follows the convention adopted by the tiler: {base_url}/tile_{b}_{a.x}_{a.y}.{format}\r
+      def get_tile_url\r
+        "function(a,b) { return '#{@base_url}/tile_' + b + '_' + a.x + '_' + a.y + '.#{format}';}"\r
+      end \r
+    end\r
+\r
+    #Represents a pretiled layer (it actually does not really matter where the tiles come from). Calls an action on the server to get back the tiles. It passes the action arguments x, y (coordinates of the tile) and z (zoom level). It can be used, for example, to return default tiles when the requested tile is not present.\r
+    class PreTiledLayerFromAction < PreTiledLayer\r
+      def get_tile_url\r
+        "function(a,b) { return '#{base_url}?x=' + a.x + '&y=' + a.y + '&z=' + b ;}"\r
+      end\r
+    end\r
+    \r
+    #Represents a TileLayer where the tiles are generated dynamically from a WMS server (MapServer, GeoServer,...)\r
+    #You need to include the JavaScript file wms-gs.js for this to work\r
+    #see http://docs.codehaus.org/display/GEOSDOC/Google+Maps\r
+    class WMSLayer < GTileLayer\r
+      attr_accessor :base_url, :layers, :styles, :merc_proj, :use_geographic\r
+\r
+      #Options are the same as with GTileLayer + :styles (""), :merc_proj (:mapserver), :use_geographic (false)\r
+      def initialize(base_url, layers, options = {})\r
+        super(options)\r
+        @base_url = base_url.gsub(/\?$/,"") #standardize the url\r
+        @layers = layers\r
+        @styles = options[:styles] || ""\r
+        merc_proj = options[:merc_proj] || :mapserver\r
+        @merc_proj = if merc_proj == :mapserver\r
+                       "54004"\r
+                     elsif merc_proj == :geoserver\r
+                       "41001"\r
+                     else\r
+                       merc_proj.to_s\r
+                     end\r
+        @use_geographic = options.has_key?(:use_geographic)? options[:use_geographic] : false\r
+        puts format\r
+      end\r
+      \r
+      def get_tile_url\r
+        "getTileUrlForWMS"\r
+      end\r
+\r
+      def create\r
+        "addWMSPropertiesToLayer(#{super},#{MappingObject.javascriptify_variable(@base_url)},#{MappingObject.javascriptify_variable(@layers)},#{MappingObject.javascriptify_variable(@styles)},#{MappingObject.javascriptify_variable(format)},#{MappingObject.javascriptify_variable(@merc_proj)},#{MappingObject.javascriptify_variable(@use_geographic)})"\r
+      end\r
+    end\r
+  end\r
+end\r
diff --git a/vendor/plugins/ym4r_gm/lib/gm_plugin/map.rb b/vendor/plugins/ym4r_gm/lib/gm_plugin/map.rb
new file mode 100644 (file)
index 0000000..82d1374
--- /dev/null
@@ -0,0 +1,268 @@
+module Ym4r\r
+  module GmPlugin \r
+    #Representing the Google Maps API class GMap2.\r
+    class GMap\r
+      include MappingObject\r
+      \r
+      #A constant containing the declaration of the VML namespace, necessary to display polylines under IE.\r
+      VML_NAMESPACE = "xmlns:v=\"urn:schemas-microsoft-com:vml\""\r
+      \r
+      #The id of the DIV that will contain the map in the HTML page. \r
+      attr_reader :container\r
+      \r
+      #By default the map in the HTML page will be globally accessible with the name +map+.\r
+      def initialize(container, variable = "map")\r
+        @container = container\r
+        @variable = variable\r
+        @init = []\r
+        @init_end = [] #for stuff that must be initialized at the end (controls)\r
+        @init_begin = [] #for stuff that must be initialized at the beginning (center + zoom)\r
+        @global_init = []\r
+      end\r
+\r
+      #Deprecated. Use the static version instead.\r
+      def header(with_vml = true)\r
+        GMap.header(:with_vml => with_vml)\r
+      end\r
+\r
+      #Outputs the header necessary to use the Google Maps API, by including the JS files of the API, as well as a file containing YM4R/GM helper functions. By default, it also outputs a style declaration for VML elements. This default can be overriddent by passing <tt>:with_vml => false</tt> as option to the method. You can also pass a <tt>:host</tt> option in order to select the correct API key for the location where your app is currently running, in case the current environment has multiple possible keys. Usually, in this case, you should pass it <tt>@request.host</tt>. If you have defined only one API key for the current environment, the <tt>:host</tt> option is ignored. Finally you can override all the key settings in the configuration by passing a value to the <tt>:key</tt> key. Finally, you can pass a language for the map type buttons with the <tt>:hl</tt> option (possible values are: Japanese (ja), French (fr), German (de), Italian (it), Spanish (es), Catalan (ca), Basque (eu) and Galician (gl): no values means english)\r
+      def self.header(options = {})\r
+        options[:with_vml] = true unless options.has_key?(:with_vml)\r
+        options[:hl] ||= ''\r
+        api_key = ApiKey.get(options)\r
+        a = "<script src=\"http://maps.google.com/maps?file=api&amp;v=2.x&amp;key=#{api_key}&amp;hl=#{options[:hl]}\" type=\"text/javascript\"></script>\n"\r
+        a << "<script src=\"/javascripts/ym4r-gm.js\" type=\"text/javascript\"></script>\n" unless options[:without_js]\r
+        a << "<style type=\"text/css\">\n v\:* { behavior:url(#default#VML);}\n</style>" if options[:with_vml]\r
+        a\r
+      end\r
+     \r
+      #Outputs the <div id=...></div> which has been configured to contain the map. You can pass <tt>:width</tt> and <tt>:height</tt> as options to output this in the style attribute of the DIV element (you could also achieve the same effect by putting the dimension info into a CSS or using the instance method GMap#header_width_height). You can aslo pass <tt>:class</tt> to set the classname of the div.\r
+      def div(options = {})\r
+        attributes = "id=\"#{@container}\" "\r
+        if options.has_key?(:height) && options.has_key?(:width)\r
+          attributes += "style=\"width:#{options.delete(:width)}px;height:#{options.delete(:height)}px\" "\r
+        end\r
+        if options.has_key?(:class)\r
+          attributes += options.keys.map {|opt| "#{opt}=\"#{options[opt]}\"" }.join(" ")\r
+        end\r
+        "<div #{attributes}></div>"\r
+      end\r
+\r
+      #Outputs a style declaration setting the dimensions of the DIV container of the map. This info can also be set manually in a CSS.\r
+      def header_width_height(width,height)\r
+        "<style type=\"text/css\">\n##{@container} { height: #{height}px;\n  width: #{width}px;\n}\n</style>"\r
+      end\r
+\r
+      #Records arbitrary JavaScript code and outputs it during initialization inside the +load+ function.\r
+      def record_init(code)\r
+        @init << code\r
+      end\r
+\r
+      #Initializes the controls: you can pass a hash with keys <tt>:small_map</tt>, <tt>:large_map</tt>, <tt>:small_zoom</tt>, <tt>:scale</tt>, <tt>:map_type</tt> and <tt>:overview_map</tt> and a boolean value as the value (usually true, since the control is not displayed by default)\r
+      def control_init(controls = {})\r
+        @init_end << add_control(GSmallMapControl.new) if controls[:small_map]\r
+        @init_end << add_control(GLargeMapControl.new) if controls[:large_map]\r
+        @init_end << add_control(GSmallZoomControl.new) if controls[:small_zoom]\r
+        @init_end << add_control(GScaleControl.new) if controls[:scale]\r
+        @init_end << add_control(GMapTypeControl.new) if controls[:map_type]\r
+        @init_end << add_control(GOverviewMapControl.new) if controls[:overview_map]\r
+      end\r
+      \r
+      #Initializes the interface configuration: double-click zoom, dragging, continuous zoom,... You can pass a hash with keys <tt>:dragging</tt>, <tt>:info_window</tt>, <tt>:double_click_zoom</tt>, <tt>:continuous_zoom</tt> and <tt>:scroll_wheel_zoom</tt>. The values should be true or false. Check the google maps API doc to know what the default values are.\r
+      def interface_init(interface = {})\r
+        if !interface[:dragging].nil?\r
+          if interface[:dragging]\r
+             @init << enableDragging() \r
+          else\r
+            @init << disableDragging() \r
+          end\r
+        end\r
+        if !interface[:info_window].nil?\r
+          if interface[:info_window]\r
+            @init << enableInfoWindow()\r
+          else\r
+            @init << disableInfoWindow()\r
+          end\r
+        end\r
+        if !interface[:double_click_zoom].nil?\r
+          if interface[:double_click_zoom]\r
+            @init << enableDoubleClickZoom()\r
+          else\r
+            @init << disableDoubleClickZoom()\r
+          end\r
+        end\r
+        if !interface[:continuous_zoom].nil?\r
+          if interface[:continuous_zoom]\r
+            @init << enableContinuousZoom()\r
+          else\r
+            @init << disableContinuousZoom()\r
+          end\r
+        end\r
+        if !interface[:scroll_wheel_zoom].nil?\r
+          if interface[:scroll_wheel_zoom]\r
+            @init << enableScrollWheelZoom()\r
+          else\r
+            @init << disableScrollWheelZoom()\r
+          end\r
+        end\r
+      end\r
+\r
+      #Initializes the initial center and zoom of the map. +center+ can be both a GLatLng object or a 2-float array.\r
+      def center_zoom_init(center, zoom)\r
+        if center.is_a?(GLatLng)\r
+          @init_begin << set_center(center,zoom)\r
+        else\r
+          @init_begin << set_center(GLatLng.new(center),zoom)\r
+        end\r
+      end\r
+\r
+      #Center and zoom based on the coordinates passed as argument (either 2D arrays or GLatLng objects)\r
+      def center_zoom_on_points_init(*points)\r
+        if(points.length > 0)\r
+          if(points[0].is_a?(Array))\r
+            points = points.collect { |point| GLatLng.new(point) }\r
+          end\r
+          @init_begin << center_and_zoom_on_points(points)\r
+        end\r
+      end\r
+\r
+      #Center and zoom based on the bbox corners. Pass a GLatLngBounds object, an array of 2D coordinates (sw and ne) or an array of GLatLng objects (sw and ne).\r
+      def center_zoom_on_bounds_init(latlngbounds)\r
+        if(latlngbounds.is_a?(Array))\r
+          if latlngbounds[0].is_a?(Array)\r
+            latlngbounds = GLatLngBounds.new(GLatLng.new(latlngbounds[0]),GLatLng.new(latlngbounds[1]))\r
+          elsif latlngbounds[0].is_a?(GLatLng)\r
+            latlngbounds = GLatLngBounds.new(*latlngbounds)\r
+          end\r
+        end\r
+        #else it is already a latlngbounds object\r
+\r
+        @init_begin << center_and_zoom_on_bounds(latlngbounds)\r
+      end\r
+\r
+      #Initializes the map by adding an overlay (marker or polyline).\r
+      def overlay_init(overlay)\r
+        @init << add_overlay(overlay)\r
+      end\r
+\r
+      #Sets up a new map type. If +add+ is false, all the other map types of the map are wiped out. If you want to access the map type in other methods, you should declare the map type first (with +declare_init+).\r
+      def add_map_type_init(map_type, add = true)\r
+        unless add\r
+          @init << get_map_types.set_property(:length,0)\r
+        end\r
+        @init << add_map_type(map_type)\r
+      end\r
+      #for legacy purpose\r
+      alias :map_type_init :add_map_type_init\r
+\r
+      #Sets the map type displayed by default after the map is loaded. It should be known from the map (ie either the default map types or a user-defined map type added with <tt>add_map_type_init</tt>). Use <tt>set_map_type_init(GMapType::G_SATELLITE_MAP)</tt> or <tt>set_map_type_init(GMapType::G_HYBRID_MAP)</tt> to initialize the map with repsecitvely the Satellite view and the hybrid view.\r
+      def set_map_type_init(map_type)\r
+        @init << set_map_type(map_type)\r
+      end\r
+\r
+      #Locally declare a MappingObject with variable name "name"\r
+      def declare_init(variable, name)\r
+        @init << variable.declare(name)\r
+      end\r
+\r
+      #Records arbitrary JavaScript code and outputs it during initialization outside the +load+ function (ie globally).\r
+      def record_global_init(code)\r
+        @global_init << code\r
+      end\r
+      \r
+      #Deprecated. Use icon_global_init instead.\r
+      def icon_init(icon , name)\r
+        icon_global_init(icon , name)\r
+      end\r
+      \r
+      #Initializes an icon  and makes it globally accessible through the JavaScript variable of name +variable+.\r
+      def icon_global_init(icon , name, options = {})\r
+        declare_global_init(icon,name,options)\r
+      end\r
+\r
+      #Registers an event\r
+      def event_init(object,event,callback)\r
+        @init << "GEvent.addListener(#{object.to_javascript},\"#{MappingObject.javascriptify_method(event.to_s)}\",#{callback});"\r
+      end\r
+\r
+      #Registers an event globally\r
+      def event_global_init(object,event,callback)\r
+        @global_init << "GEvent.addListener(#{object.to_javascript},\"#{MappingObject.javascriptify_method(event.to_s)}\",#{callback});"\r
+      end\r
+      \r
+      #Declares the overlay globally with name +name+\r
+      def overlay_global_init(overlay,name, options = {})\r
+        declare_global_init(overlay,name, options)\r
+        @init << add_overlay(overlay)\r
+      end\r
+\r
+      #Globally declare a MappingObject with variable name "name". Option <tt>:local_construction</tt> should be passed if the construction has to be done inside the onload callback method (for exsample if it depends on the GMap to be initialized)\r
+      def declare_global_init(variable,name, options = {})\r
+        unless options[:local_construction]\r
+          @global_init << "var #{variable.assign_to(name)}"\r
+        else\r
+          @global_init << "var #{name};"\r
+          @init << variable.assign_to(name)\r
+        end\r
+      end\r
+      \r
+      #Outputs the initialization code for the map. By default, it outputs the script tags, performs the initialization in response to the onload event of the window and makes the map globally available. If you pass +true+ to the option key <tt>:full</tt>, the map will be setup in full screen, in which case it is not necessary (but not harmful) to set a size for the map div.\r
+      def to_html(options = {})\r
+        no_load = options[:no_load]\r
+        no_script_tag = options[:no_script_tag]\r
+        no_declare = options[:no_declare]\r
+        no_global = options[:no_global]\r
+        fullscreen = options[:full]\r
+        load_pr = options[:proto_load] #to prevent some problems when the onload event callback from Prototype is used\r
+        \r
+        html = ""\r
+        html << "<script type=\"text/javascript\">\n" if !no_script_tag\r
+        #put the functions in a separate javascript file to be included in the page\r
+        html << @global_init * "\n"\r
+        html << "var #{@variable};\n" if !no_declare and !no_global\r
+        if !no_load\r
+          if load_pr\r
+            html << "Event.observe(window,'load',"\r
+          else\r
+            html << "window.onload = addCodeToFunction(window.onload,"\r
+          end\r
+          html << "function() {\n"\r
+        end\r
+\r
+        html << "if (GBrowserIsCompatible()) {\n" \r
+        \r
+        if fullscreen\r
+          #Adding the initial resizing and setting up the event handler for\r
+          #future resizes\r
+          html << "setWindowDims(document.getElementById('#{@container}'));\n"\r
+          html << "if (window.attachEvent) { window.attachEvent(\"onresize\", function() {setWindowDims(document.getElementById('#{@container}'));})} else {window.addEventListener(\"resize\", function() {setWindowDims(document.getElementById('#{@container}')); } , false);}\n"\r
+        end\r
+      \r
+        if !no_declare and no_global \r
+          html << "#{declare(@variable)}\n"\r
+        else\r
+          html << "#{assign_to(@variable)}\n"\r
+        end\r
+        html << @init_begin * "\n"\r
+        html << @init * "\n"\r
+        html << @init_end * "\n"\r
+        html << "\n}\n"\r
+        html << "});\n" if !no_load\r
+        html << "</script>" if !no_script_tag\r
+        \r
+        if fullscreen\r
+          #setting up the style in case of full screen\r
+          html << "<style>html, body {width: 100%; height: 100%} body {margin-top: 0px; margin-right: 0px; margin-left: 0px; margin-bottom: 0px} ##{@container} {margin:  0px;} </style>"\r
+        end\r
+        \r
+        html\r
+      end\r
+      \r
+      #Outputs in JavaScript the creation of a GMap2 object \r
+      def create\r
+        "new GMap2(document.getElementById(\"#{@container}\"))"\r
+      end\r
+    end\r
+  end\r
+end\r
+\r
diff --git a/vendor/plugins/ym4r_gm/lib/gm_plugin/mapping.rb b/vendor/plugins/ym4r_gm/lib/gm_plugin/mapping.rb
new file mode 100644 (file)
index 0000000..66d825e
--- /dev/null
@@ -0,0 +1,128 @@
+module Ym4r\r
+  module GmPlugin\r
+    #The module where all the Ruby-to-JavaScript conversion takes place. It is included by all the classes in the YM4R library.\r
+    module MappingObject\r
+      #The name of the variable in JavaScript space.\r
+      attr_reader :variable\r
+      \r
+      #Creates javascript code for missing methods + takes care of listeners\r
+      def method_missing(name,*args)\r
+        str_name = name.to_s\r
+        if str_name =~ /^on_(.*)/\r
+          if args.length != 1\r
+            raise ArgumentError("Only 1 argument is allowed on on_ methods");\r
+          else\r
+            Variable.new("GEvent.addListener(#{to_javascript},\"#{MappingObject.javascriptify_method($1)}\",#{args[0]})")\r
+          end\r
+        else\r
+          args.collect! do |arg|\r
+            MappingObject.javascriptify_variable(arg)\r
+          end\r
+          Variable.new("#{to_javascript}.#{MappingObject.javascriptify_method(str_name)}(#{args.join(",")})")\r
+        end\r
+      end\r
+            \r
+      #Creates javascript code for array or hash indexing\r
+      def [](index) #index could be an integer or string\r
+        return Variable.new("#{to_javascript}[#{MappingObject.javascriptify_variable(index)}]")\r
+      end\r
+\r
+      #Transforms a Ruby object into a JavaScript string : MAppingObject, String, Array, Hash and general case (using to_s)\r
+      def self.javascriptify_variable(arg)\r
+        if arg.is_a?(MappingObject)\r
+          arg.to_javascript\r
+        elsif arg.is_a?(String)\r
+          "\"#{MappingObject.escape_javascript(arg)}\""\r
+        elsif arg.is_a?(Array)\r
+          "[" + arg.collect{ |a| MappingObject.javascriptify_variable(a)}.join(",") + "]"\r
+        elsif arg.is_a?(Hash)\r
+          "{" + arg.to_a.collect do |v|\r
+            "#{MappingObject.javascriptify_method(v[0].to_s)} : #{MappingObject.javascriptify_variable(v[1])}"\r
+          end.join(",") + "}"\r
+        elsif arg.nil?\r
+          "undefined"\r
+        else\r
+          arg.to_s\r
+        end\r
+      end\r
+      \r
+      #Escape string to be used in JavaScript. Lifted from rails.\r
+      def self.escape_javascript(javascript)\r
+        javascript.gsub(/\r\n|\n|\r/, "\\n").gsub("\"") { |m| "\\#{m}" }\r
+      end\r
+      \r
+      #Transform a ruby-type method name (like add_overlay) to a JavaScript-style one (like addOverlay).\r
+      def self.javascriptify_method(method_name)\r
+        method_name.gsub(/_(\w)/){|s| $1.upcase}\r
+      end\r
+      \r
+      #Declares a Mapping Object bound to a JavaScript variable of name +variable+.\r
+      def declare(variable)\r
+        @variable = variable\r
+        "var #{@variable} = #{create};"\r
+      end\r
+\r
+      #declare with a random variable name\r
+      def declare_random(init,size = 8)\r
+        s = init.clone\r
+        6.times { s << (i = Kernel.rand(62); i += ((i < 10) ? 48 : ((i < 36) ? 55 : 61 ))).chr }\r
+        declare(s)\r
+      end\r
+\r
+      #Checks if the MappinObject has been declared\r
+      def declared?\r
+        !@variable.nil?\r
+      end\r
+      \r
+      #Binds a Mapping object to a previously declared JavaScript variable of name +variable+.\r
+      def assign_to(variable)\r
+        @variable = variable\r
+        "#{@variable} = #{create};"\r
+      end\r
+\r
+      #Assign the +value+ to the +property+ of the MappingObject\r
+      def set_property(property, value)\r
+        "#{to_javascript}.#{MappingObject.javascriptify_method(property.to_s)} = #{MappingObject.javascriptify_variable(value)}"\r
+      end\r
+\r
+      #Returns the code to get a +property+ from the MappingObject\r
+      def get_property(property)\r
+        Variable.new("#{to_javascript}.#{MappingObject.javascriptify_method(property.to_s)}")\r
+      end\r
+      \r
+      #Returns a Javascript code representing the object\r
+      def to_javascript\r
+        unless @variable.nil?\r
+          @variable\r
+        else\r
+          create\r
+        end\r
+      end\r
+      \r
+      #Creates a Mapping Object in JavaScript.\r
+      #To be implemented by subclasses if needed\r
+      def create\r
+      end\r
+    end\r
+\r
+    #Used to bind a ruby variable to an already existing JavaScript one. It doesn't have to be a variable in the sense "var variable" but it can be any valid JavaScript expression that has a value.\r
+    class Variable\r
+      include MappingObject\r
+      \r
+      def initialize(variable)\r
+        @variable = variable\r
+      end\r
+      #Returns the javascript expression contained in the object.\r
+      def create\r
+        @variable\r
+      end\r
+      #Returns the expression inside the Variable followed by a ";"\r
+      def to_s\r
+        @variable + ";"\r
+      end\r
+\r
+      UNDEFINED = Variable.new("undefined")\r
+    end\r
+  end\r
+end\r
+\r
diff --git a/vendor/plugins/ym4r_gm/lib/gm_plugin/overlay.rb b/vendor/plugins/ym4r_gm/lib/gm_plugin/overlay.rb
new file mode 100644 (file)
index 0000000..5e0953a
--- /dev/null
@@ -0,0 +1,386 @@
+module Ym4r\r
+  module GmPlugin\r
+    #A graphical marker positionned through geographic coordinates (in the WGS84 datum). An HTML info window can be set to be displayed when the marker is clicked on.\r
+    class GMarker\r
+      include MappingObject\r
+      attr_accessor :point, :options, :info_window, :info_window_tabs, :address\r
+      #The +points+ argument can be either a GLatLng object or an array of 2 floats. The +options+ keys can be: <tt>:icon</tt>, <tt>:clickable</tt>, <tt>:title</tt>, <tt>:info_window</tt> and <tt>:info_window_tabs</tt>, as well as <tt>:max_width</tt>. The value of the +info_window+ key is a string of HTML code that will be displayed when the markers is clicked on. The value of the +info_window_tabs+ key is an array of GInfoWindowTab objects or a hash directly, in which case it will be transformed to an array of GInfoWindowTabs, with the keys as the tab headers and the values as the content.\r
+      def initialize(position, options = {})\r
+        if position.is_a?(Array)\r
+          @point = GLatLng.new(position)\r
+        elsif position.is_a?(String)\r
+          @point = Variable.new("INVISIBLE") #default coordinates: won't appear anyway\r
+          @address = position\r
+        else\r
+          @point = position\r
+        end\r
+        @info_window = options.delete(:info_window)\r
+        @info_window_tabs = options.delete(:info_window_tabs)\r
+        if options.has_key?(:max_url)\r
+          @info_window_options = {:max_url => options.delete(:max_url) } \r
+        else\r
+          @info_window_options = {}\r
+        end\r
+        @options = options\r
+      end\r
+      #Creates a marker: If an info_window or info_window_tabs is present, the response to the click action from the user is setup here.\r
+      def create\r
+        if @options.empty?\r
+          creation = "new GMarker(#{MappingObject.javascriptify_variable(@point)})"\r
+        else\r
+          creation = "new GMarker(#{MappingObject.javascriptify_variable(@point)},#{MappingObject.javascriptify_variable(@options)})"\r
+        end\r
+        if @info_window && @info_window.is_a?(String)\r
+          creation = "addInfoWindowToMarker(#{creation},#{MappingObject.javascriptify_variable(@info_window)},#{MappingObject.javascriptify_variable(@info_window_options)})"\r
+        elsif @info_window_tabs && @info_window_tabs.is_a?(Hash)\r
+          creation = "addInfoWindowTabsToMarker(#{creation},#{MappingObject.javascriptify_variable(@info_window_tabs.to_a.collect{|kv| GInfoWindowTab.new(kv[0],kv[1] ) })},#{MappingObject.javascriptify_variable(@info_window_options)})"\r
+        elsif @info_window_tabs \r
+          creation = "addInfoWindowTabsToMarker(#{creation},#{MappingObject.javascriptify_variable(Array(@info_window_tabs))},#{MappingObject.javascriptify_variable(@info_window_options)})"\r
+        end\r
+        if @address.nil?\r
+          creation\r
+        else\r
+          "addGeocodingToMarker(#{creation},#{MappingObject.javascriptify_variable(@address)})"\r
+        end\r
+      end\r
+    end\r
+    \r
+    #Represents a tab to be displayed in a bubble when a marker is clicked on.\r
+    class GInfoWindowTab < Struct.new(:tab,:content)\r
+      include MappingObject\r
+      def create\r
+        "new GInfoWindowTab(#{MappingObject.javascriptify_variable(tab)},#{MappingObject.javascriptify_variable(content)})"\r
+      end\r
+    end\r
+        \r
+    #Represents a definition of an icon. You can pass rubyfied versions of the attributes detailed in the Google Maps API documentation. You can initialize global icons to be used in the application by passing a icon object, along with a variable name, to GMap#icon_init. If you want to declare an icon outside this, you will need to declare it first, since the JavaScript constructor does not accept any argument.\r
+    class GIcon\r
+      include MappingObject\r
+      DEFAULT = Variable.new("G_DEFAULT_ICON")\r
+      attr_accessor :options, :copy_base\r
+\r
+      #Options can contain all the attributes (in rubyfied format) of a GIcon object (see Google's doc), as well as <tt>:copy_base</tt>, which indicates if the icon is copied from another one.\r
+      def initialize(options = {})\r
+        @copy_base = options.delete(:copy_base)\r
+        @options = options\r
+      end\r
+      #Creates a GIcon.\r
+      def create\r
+        if @copy_base\r
+          c = "new GIcon(#{MappingObject.javascriptify_variable(@copy_base)})"\r
+        else\r
+          c = "new GIcon()"\r
+        end\r
+        if !options.empty?\r
+          "addOptionsToIcon(#{c},#{MappingObject.javascriptify_variable(@options)})"\r
+        else\r
+          c\r
+        end\r
+      end\r
+    end\r
+     \r
+    #A polyline.\r
+    class GPolyline\r
+      include MappingObject\r
+      attr_accessor :points,:color,:weight,:opacity\r
+      #Can take an array of +GLatLng+ or an array of 2D arrays. A method to directly build a polyline from a GeoRuby linestring is provided in the helper.rb file.\r
+      def initialize(points,color = nil,weight = nil,opacity = nil)\r
+        if !points.empty? and points[0].is_a?(Array)\r
+          @points = points.collect { |pt| GLatLng.new(pt) }\r
+        else\r
+          @points = points\r
+        end\r
+        @color = color\r
+        @weight = weight\r
+        @opacity = opacity\r
+      end\r
+      #Creates a new polyline.\r
+      def create\r
+        a = "new GPolyline(#{MappingObject.javascriptify_variable(points)}"\r
+        a << ",#{MappingObject.javascriptify_variable(@color)}" if @color\r
+        a << ",#{MappingObject.javascriptify_variable(@weight)}" if @weight\r
+        a << ",#{MappingObject.javascriptify_variable(@opacity)}" if @opacity\r
+        a << ")"\r
+      end\r
+    end\r
+\r
+    #Encoded GPolyline class\r
+    class GPolylineEncoded \r
+      include MappingObject\r
+      attr_accessor :points,:color,:weight,:opacity,:levels,:zoom_factor,:num_levels\r
+\r
+      def initialize(options={})\r
+        #points = options[:points]\r
+        #if !points.empty? and points[0].is_a?(Array)\r
+        #  @points = points.collect { |pt| GLatLng.new(pt) }\r
+        #else\r
+        #@points = points\r
+          #end\r
+        @points = options[:points]\r
+        @color = options[:color]\r
+        @weight = options[:weight]\r
+        @opacity = options[:opacity]\r
+        @levels = options[:levels] || "BBBBBBBBBBBB"\r
+        @zoom_factor = options[:zoom_factor] || 32\r
+        @num_levels = options[:num_levels] || 4\r
+      end\r
+      def create\r
+        a = "new GPolyline.fromEncoded({points: #{MappingObject.javascriptify_variable(points)},\n" \r
+        a << "levels: #{MappingObject.javascriptify_variable(@levels)},"\r
+        a << "zoomFactor: #{MappingObject.javascriptify_variable(@zoom_factor)},"\r
+        a << "numLevels: #{MappingObject.javascriptify_variable(@num_levels)}"\r
+        a << ",color: #{MappingObject.javascriptify_variable(@color)}" if @color\r
+        a << ",weight: #{MappingObject.javascriptify_variable(@weight)}" if @weight\r
+        a << ",opacity: #{MappingObject.javascriptify_variable(@opacity)}" if @opacity\r
+        a << "})"\r
+      end\r
+    end\r
+\r
+    #A basic Latitude/longitude point.\r
+    class GLatLng \r
+      include MappingObject\r
+      attr_accessor :lat,:lng,:unbounded\r
+      \r
+      def initialize(latlng,unbounded = nil)\r
+        @lat = latlng[0]\r
+        @lng = latlng[1]\r
+        @unbounded = unbounded\r
+      end\r
+      def create\r
+        unless @unbounded\r
+          "new GLatLng(#{MappingObject.javascriptify_variable(@lat)},#{MappingObject.javascriptify_variable(@lng)})"\r
+        else\r
+          "new GLatLng(#{MappingObject.javascriptify_variable(@lat)},#{MappingObject.javascriptify_variable(@lng)},#{MappingObject.javascriptify_variable(@unbounded)})"\r
+        end\r
+      end\r
+    end\r
+    \r
+    #A rectangular bounding box, defined by its south-western and north-eastern corners.\r
+    class GLatLngBounds < Struct.new(:sw,:ne)\r
+      include MappingObject\r
+      def create\r
+        "new GLatLngBounds(#{MappingObject.javascriptify_variable(sw)},#{MappingObject.javascriptify_variable(ne)})"\r
+      end\r
+    end\r
+\r
+    #Polygon. Not documented yet in the Google Maps API\r
+    class GPolygon\r
+      include MappingObject\r
+      \r
+      attr_accessor :points,:stroke_color,:stroke_weight,:stroke_opacity,:color,:opacity\r
+      \r
+      #Can take an array of +GLatLng+ or an array of 2D arrays. A method to directly build a polygon from a GeoRuby polygon is provided in the helper.rb file.\r
+      def initialize(points,stroke_color="#000000",stroke_weight=1,stroke_opacity=1.0,color="#ff0000",opacity=1.0,encoded=false)\r
+        if !points.empty? and points[0].is_a?(Array)\r
+          @points = points.collect { |pt| GLatLng.new(pt) }\r
+        else\r
+          @points = points\r
+        end\r
+        @stroke_color = stroke_color\r
+        @stroke_weight = stroke_weight\r
+        @stroke_opacity = stroke_opacity\r
+        @color = color\r
+        @opacity = opacity\r
+      end\r
+      \r
+      #Creates a new polygon\r
+      def create\r
+        a = "new GPolygon(#{MappingObject.javascriptify_variable(points)}"\r
+        a << ",#{MappingObject.javascriptify_variable(@stroke_color)}"\r
+        a << ",#{MappingObject.javascriptify_variable(@stroke_weight)}"\r
+        a << ",#{MappingObject.javascriptify_variable(@stroke_opacity)}"\r
+        a << ",#{MappingObject.javascriptify_variable(@color)}"\r
+        a << ",#{MappingObject.javascriptify_variable(@opacity)}"\r
+        a << ")"\r
+      end\r
+    end\r
+\r
+    class GPolygonEncoded \r
+      include MappingObject\r
+      \r
+      attr_accessor :polyline, :color, :opacity, :outline, :fill\r
+      \r
+      def initialize(polylines,fill=true,color="#000000",opacity=0.5,outline=false)\r
+        #force polylines to be an array\r
+        if polylines.is_a? Array\r
+          @polylines = polylines\r
+        else\r
+          @polylines = [polylines]\r
+        end\r
+        @color = color\r
+        @fill = fill \r
+        @opacity = opacity\r
+        @outline = outline\r
+      end\r
+      \r
+      #Creates a new polygon.\r
+      def create\r
+        polylines_for_polygon= []\r
+        @polylines.each do |p|\r
+          x = "{points: #{MappingObject.javascriptify_variable(p.points)}," \r
+          x << "levels: #{MappingObject.javascriptify_variable(p.levels)},"\r
+          x << "zoomFactor: #{MappingObject.javascriptify_variable(p.zoom_factor)},"\r
+          x << "numLevels: #{MappingObject.javascriptify_variable(p.num_levels)} "\r
+          x << "}"\r
+          polylines_for_polygon << x\r
+        end\r
+\r
+        polylines_for_polygon = "[" + polylines_for_polygon.join(",") + "]"\r
+\r
+        a = "new GPolygon.fromEncoded({polylines: #{polylines_for_polygon},"\r
+        a << "fill: #{MappingObject.javascriptify_variable(@fill)},"\r
+        a << "color: #{MappingObject.javascriptify_variable(@color)},"\r
+        a << "opacity: #{MappingObject.javascriptify_variable(@opacity)},"\r
+        a << "outline: #{MappingObject.javascriptify_variable(@outline)}"\r
+        a << "})"\r
+      end\r
+    end\r
+\r
+    class ELabel\r
+      attr_accessor :point, :text, :style\r
+      include MappingObject\r
+\r
+      def initialize(point, text=nil, style=nil)\r
+        @point = point\r
+        @text = text\r
+        @style = style\r
+      end\r
+\r
+      def create\r
+          a = "new ELabel(#{MappingObject.javascriptify_variable(@point)}"\r
+          a << ",#{MappingObject.javascriptify_variable(@text)}" if @text\r
+          a << ",#{MappingObject.javascriptify_variable(@style)}" if @style\r
+          a << ")"\r
+      end\r
+    end\r
+\r
+\r
+    #A GGeoXml object gets data from a GeoRSS or KML feed and displays it. Use <tt>overlay_init</tt> to add it to a map at initialization time.\r
+    class GGeoXml\r
+      include MappingObject\r
+      \r
+      attr_accessor :url\r
+\r
+      def initialize(url)\r
+        @url = url\r
+      end\r
+\r
+      def create\r
+        "new GGeoXml(#{MappingObject.javascriptify_variable(@url)})"\r
+      end\r
+\r
+    end\r
+    \r
+    #A GOverlay representing a group of GMarkers. The GMarkers can be identified with an id, which can be used to show the info window of a specific marker, in reponse, for example, to a click on a link. The whole group can be shown on and off at once. It should be declared global at initialization time to be useful.\r
+    class GMarkerGroup\r
+      include MappingObject\r
+      attr_accessor :active, :markers, :markers_by_id\r
+\r
+      def initialize(active = true , markers = nil)\r
+        @active = active\r
+        @markers = []\r
+        @markers_by_id = {}\r
+        if markers.is_a?(Array)\r
+          @markers = markers\r
+        elsif markers.is_a?(Hash)\r
+          @markers_by_id = markers\r
+        end\r
+      end\r
+      \r
+      def create\r
+        "new GMarkerGroup(#{MappingObject.javascriptify_variable(@active)},#{MappingObject.javascriptify_variable(@markers)},#{MappingObject.javascriptify_variable(@markers_by_id)})"\r
+      end\r
+    end\r
+\r
+    #Can be used to implement a clusterer, similar to the clusterer below, except that there is more stuff to manage explicitly byt the programmer (but this is also more flexible). See the README for usage esamples.\r
+    class GMarkerManager\r
+      include MappingObject\r
+      \r
+      attr_accessor :map,:options,:managed_markers\r
+            \r
+      #options can be <tt>:border_padding</tt>, <tt>:max_zoom</tt>, <tt>:track_markers</tt> and <tt>:managed_markers</tt>: managed_markers must be an array of ManagedMarker objects\r
+      def initialize(map, options = {})\r
+        @map = map\r
+        @managed_markers = Array(options.delete(:managed_markers)) #[] if nil\r
+        @options = options\r
+      end\r
+\r
+      def create\r
+        puts @options.inspect\r
+        "addMarkersToManager(new GMarkerManager(#{MappingObject.javascriptify_variable(@map)},#{MappingObject.javascriptify_variable(@options)}),#{MappingObject.javascriptify_variable(@managed_markers)})"\r
+      end\r
+\r
+    end\r
+\r
+    #A set of similarly managed markers: They share the same minZoom and maxZoom.\r
+    class ManagedMarker\r
+      include MappingObject\r
+      \r
+      attr_accessor :markers,:min_zoom, :max_zoom\r
+      \r
+      def initialize(markers,min_zoom,max_zoom = nil)\r
+        @markers = markers\r
+        @min_zoom = min_zoom\r
+        @max_zoom = max_zoom\r
+      end\r
+\r
+      def create\r
+        "new ManagedMarker(#{MappingObject.javascriptify_variable(@markers)},#{MappingObject.javascriptify_variable(@min_zoom)},#{MappingObject.javascriptify_variable(@max_zoom)})"\r
+      end\r
+      \r
+    end\r
+\r
+    #Makes the link with the Clusterer2 library by Jef Poskanzer (slightly modified though). Is a GOverlay making clusters out of its GMarkers, so that GMarkers very close to each other appear as one when the zoom is low. When the zoom gets higher, the individual markers are drawn.\r
+    class Clusterer\r
+      include MappingObject\r
+      attr_accessor :markers,:icon, :max_visible_markers, :grid_size, :min_markers_per_cluster , :max_lines_per_info_box\r
+\r
+      def initialize(markers = [], options = {})\r
+        @markers = markers\r
+        @icon = options[:icon] || GIcon::DEFAULT\r
+        @max_visible_markers = options[:max_visible_markers] || 150\r
+        @grid_size = options[:grid_size] || 5\r
+        @min_markers_per_cluster = options[:min_markers_per_cluster] || 5\r
+        @max_lines_per_info_box = options[:max_lines_per_info_box] || 10\r
+      end\r
+\r
+      def create \r
+        js_marker = '[' + @markers.collect do |marker|\r
+          add_description(marker)\r
+        end.join(",") + ']'\r
+\r
+        "new Clusterer(#{js_marker},#{MappingObject.javascriptify_variable(@icon)},#{MappingObject.javascriptify_variable(@max_visible_markers)},#{MappingObject.javascriptify_variable(@grid_size)},#{MappingObject.javascriptify_variable(@min_markers_per_cluster)},#{MappingObject.javascriptify_variable(@max_lines_per_info_box)})"\r
+      end\r
+            \r
+      private\r
+      def add_description(marker)\r
+        "addDescriptionToMarker(#{MappingObject.javascriptify_variable(marker)},#{MappingObject.javascriptify_variable(marker.options[:description] || marker.options[:title] || '')})"\r
+      end\r
+    end\r
+    \r
+    #Makes the link with the MGeoRSS extension by Mikel Maron (a bit modified though). It lets you overlay on top of Google Maps the items present in a RSS feed that has GeoRss data. This data can be either in W3C Geo vocabulary or in the GeoRss Simple format. See http://georss.org to know more about GeoRss.\r
+    class GeoRssOverlay\r
+      include MappingObject\r
+      attr_accessor :url, :proxy, :icon, :options\r
+      \r
+      #You can pass the following options:\r
+      #- <tt>:icon</tt>: An icon for the items of the feed. Defaults to the classic red balloon icon.\r
+      #- <tt>:proxy</tt>: An URL on your server where fetching the RSS feed will be taken care of.\r
+      #- <tt>:list_div</tt>: In case you want a list of all the markers, with a link on which you can click in order to display the info on the marker, use this option to indicate the ID of the div (that you must place yourself).\r
+      #- <tt>:list_item_class</tt>: class of the DIV containing each item of the list. Ignored if option <tt>:list_div</tt> is not set.\r
+      #- <tt>:limit</tt>: Maximum number of items to display on the map.\r
+      #- <tt>:content_div</tt>: Instead of having an info window appear, indicates the ID of the DIV where this info should be displayed.\r
+      def initialize(url, options = {})\r
+        @url = url\r
+        @icon = options.delete(:icon) || GIcon::DEFAULT\r
+        @proxy = options.delete(:proxy) || Variable::UNDEFINED\r
+        @options = options \r
+      end\r
+\r
+      def create \r
+        "new GeoRssOverlay(#{MappingObject.javascriptify_variable(@url)},#{MappingObject.javascriptify_variable(@icon)},#{MappingObject.javascriptify_variable(@proxy)},#{MappingObject.javascriptify_variable(@options)})"\r
+      end\r
+    end\r
+\r
+  end\r
+end\r
diff --git a/vendor/plugins/ym4r_gm/lib/gm_plugin/point.rb b/vendor/plugins/ym4r_gm/lib/gm_plugin/point.rb
new file mode 100644 (file)
index 0000000..bcde4e2
--- /dev/null
@@ -0,0 +1,34 @@
+module Ym4r\r
+  module GmPlugin\r
+    #A point in pixel coordinates\r
+    class GPoint < Struct.new(:x,:y)\r
+      include MappingObject\r
+      def create\r
+        "new GPoint(#{x},#{y})"\r
+      end\r
+    end\r
+    #A rectangular that contains all the pixel points passed as arguments\r
+    class GBounds\r
+      include MappingObject\r
+      attr_accessor :points\r
+      #Accepts both an array of GPoint and an array of 2-element arrays\r
+      def initialize(points)\r
+        if !points.empty? and points[0].is_a?(Array)\r
+          @points = points.collect { |pt| GPoint.new(pt[0],pt[1]) }\r
+        else\r
+          @points = points\r
+        end\r
+      end\r
+      def create\r
+        "new GBounds([#{@points.map { |pt| pt.to_javascript}.join(",")}])"\r
+      end\r
+    end\r
+    #A size object, in pixel space\r
+    class GSize < Struct.new(:width,:height)\r
+      include MappingObject\r
+      def create\r
+        "new GSize(#{width},#{height})"\r
+      end\r
+    end\r
+  end\r
+end\r
diff --git a/vendor/plugins/ym4r_gm/lib/ym4r_gm.rb b/vendor/plugins/ym4r_gm/lib/ym4r_gm.rb
new file mode 100644 (file)
index 0000000..24c9068
--- /dev/null
@@ -0,0 +1,11 @@
+require 'gm_plugin/key'\r
+require 'gm_plugin/mapping'\r
+require 'gm_plugin/map'\r
+require 'gm_plugin/control'\r
+require 'gm_plugin/point'\r
+require 'gm_plugin/overlay'\r
+require 'gm_plugin/layer'\r
+require 'gm_plugin/helper'\r
+require 'gm_plugin/geocoding'\r
+\r
+include Ym4r::GmPlugin\r
diff --git a/vendor/plugins/ym4r_gm/rakefile.rb b/vendor/plugins/ym4r_gm/rakefile.rb
new file mode 100644 (file)
index 0000000..e2d46bf
--- /dev/null
@@ -0,0 +1,22 @@
+require 'rake'
+require 'rake/testtask'
+require 'rake/rdoctask'
+
+desc 'Default: run unit tests.'
+task :default => :test
+
+desc 'Test the gm plugin.'
+Rake::TestTask.new(:test) do |t|
+  t.libs << 'lib'
+  t.pattern = 'test/**/*_test.rb'
+  t.verbose = true
+end
+
+desc 'Generate documentation for the gm plugin.'
+Rake::RDocTask.new(:rdoc) do |rdoc|
+  rdoc.rdoc_dir = 'ym4r_gm-doc'
+  rdoc.title    = 'GM'
+  rdoc.options << '--line-numbers' << '--inline-source'
+  rdoc.rdoc_files.include('README')
+  rdoc.rdoc_files.include('lib/**/*.rb')
+end
diff --git a/vendor/plugins/ym4r_gm/tasks/gm_tasks.rake b/vendor/plugins/ym4r_gm/tasks/gm_tasks.rake
new file mode 100644 (file)
index 0000000..40745d0
--- /dev/null
@@ -0,0 +1,4 @@
+# desc "Explaining what the task does"
+# task :gm do
+#   # Task goes here
+# end
\ No newline at end of file
diff --git a/vendor/plugins/ym4r_gm/test/gm_test.rb b/vendor/plugins/ym4r_gm/test/gm_test.rb
new file mode 100644 (file)
index 0000000..cea8447
--- /dev/null
@@ -0,0 +1,79 @@
+$:.unshift(File.dirname(__FILE__) + '/../lib')
+
+require File.expand_path(File.dirname(__FILE__) + "/../../../../config/environment")
+
+
+require 'ym4r_gm'
+require 'test/unit'
+
+include Ym4r::GmPlugin
+
+class TestGoogleMaps< Test::Unit::TestCase
+  def test_javascriptify_method
+    assert_equal("addOverlayToHello",MappingObject::javascriptify_method("add_overlay_to_hello"))
+  end
+
+  def test_javascriptify_variable_mapping_object
+    map = GMap.new("div")
+    assert_equal(map.to_javascript,MappingObject::javascriptify_variable(map))
+  end
+
+  def test_javascriptify_variable_numeric
+    assert_equal("123.4",MappingObject::javascriptify_variable(123.4))
+  end
+
+  def test_javascriptify_variable_array
+    map = GMap.new("div")
+    assert_equal("[123.4,#{map.to_javascript},[123.4,#{map.to_javascript}]]",MappingObject::javascriptify_variable([123.4,map,[123.4,map]]))
+  end
+
+  def test_javascriptify_variable_hash
+    map = GMap.new("div")
+    test_str = MappingObject::javascriptify_variable("hello" => map, "chopotopoto" => [123.55,map])
+    assert("{hello : #{map.to_javascript},chopotopoto : [123.55,#{map.to_javascript}]}" == test_str || "{chopotopoto : [123.55,#{map.to_javascript}],hello : #{map.to_javascript}}" == test_str)
+  end
+
+  def test_method_call_on_mapping_object
+    map = GMap.new("div","map")
+    assert_equal("map.addHello(123.4);",map.add_hello(123.4).to_s)
+  end
+
+  def test_nested_calls_on_mapping_object
+    gmap = GMap.new("div","map")
+    assert_equal("map.addHello(map.hoYoYo(123.4),map);",gmap.add_hello(gmap.ho_yo_yo(123.4),gmap).to_s)
+  end
+  
+  def test_declare_variable_latlng
+    point = GLatLng.new([123.4,123.6])
+    assert_equal("var point = new GLatLng(123.4,123.6);",point.declare("point"))
+    assert_equal("point",point.variable)
+  end
+
+  def test_array_indexing
+    obj = Variable.new("obj")
+    assert_equal("obj[0]",obj[0].variable)
+  end
+
+  def test_google_maps_geocoding
+    
+
+    placemarks = Geocoding.get("Rue Clovis Paris")
+    assert_equal(Geocoding::GEO_SUCCESS,placemarks.status)
+    assert_equal(1,placemarks.length)
+    placemark = placemarks[0]
+    assert_equal("FR",placemark.country_code)
+    assert_equal("Paris",placemark.locality)
+    assert_equal("75005",placemark.postal_code)
+    
+    #test iwht multiple placemarks
+    placemarks = Geocoding.get('hoogstraat, nl')
+    assert_equal(Geocoding::GEO_SUCCESS,placemarks.status)
+    assert(placemarks.length > 1)
+    assert(placemarks[0].latitude != placemarks[1].latitude )
+    
+
+  end
+
+  
+end
+

Benjamin Mako Hill || Want to submit a patch?