require "selenium-webdriver"
require 'rubygems'
require 'rspec'

def wait_for_ajax(seconds = 60, explicit_sleep = 0)
  counter = 0
  while @driver.execute_script("return $.active").to_i > 0
    counter += 1
    sleep 1
    raise "Request took longer than %d minutes." % ((seconds.fdiv 60).round 1) if counter >= seconds
  end
  sleep explicit_sleep
end

def alert_present?()
   @driver.switch_to.alert
   true
rescue Selenium::WebDriver::Error::NoAlertPresentError
   false
end

def close_alert_and_get_its_text(how, what)
	puts "***** Checking for alert ******"
	@accept_next_alert = false
	if alert_present?
		puts "***** Has alert *****"
		alert = @driver.switch_to().alert()
		alert_text = alert.text
		if @accept_next_alert
			alert.accept()
		else
			puts "dismiss the alert"
			alert.dismiss()
		end
		alert_text
	end
ensure
	@accept_next_alert = true
end