# Performance fix for https://groups.google.com/forum/?fromgroups#!msg/ruby-capybara/DhcXGW-a8hs/ZxWY1cZuy1YJ
module Capybara
  module Node
    module Actions

      def fill_in(locator, options = {})
        raise "Must pass a hash containing 'with'" if not options.is_a?(Hash) or not options.has_key?(:with)
        find_fillable_field(locator).set(options[:with])
      end

      def find_fillable_field(locator)
        msg = "cannot fill in, no text field, text area or password field with id, name, or label '#{locator}' found"
        label_tags = all(:css, 'label', :text => locator)
        label_tag = label_tags.sort_by{ |tag| tag.text.length }.first
        if label_tag
          text_field_id = label_tag[:for]
        else
          text_field_id = locator
        end
        find(:css, "input[id='#{text_field_id}'],textarea[id='#{text_field_id}']", msg)
      end

    end
  end
end

# Make #find_fillable_field available in Cucumber step definitions.
module Capybara
  module DSL
    delegate :find_fillable_field, :to => :page
  end
end

# Make #find_fillable_field available Capybara's root node ("page")
module Capybara
  class Session
    delegate :find_fillable_field, :to => :current_node
  end
end
