module FeaturesHelpers
  def wait_for_ajax(wait_time = nil)
    Timeout.timeout(wait_time || Capybara.default_max_wait_time) do
      loop until finished_all_ajax_requests?
    end
  end

  def finished_all_ajax_requests?
    # in feature jQuery.ajax.active
    # sleep 0.075
    page.evaluate_script('jQuery.active').zero?
  end

  def open_group(selector)
    group = find(selector)
    unless group[:class] =~ /open/
      group.find('.module-heading').click
    end
  end

  def element_position(selector)
    x = page.evaluate_script("jQuery('#{selector}').position().left").to_i
    y = page.evaluate_script("jQuery('#{selector}').position().top").to_i
    [x, y]
  end

  def element_width(selector)
    page.evaluate_script("jQuery('#{selector}').width()").to_i
  end

end
