module PageObject
  module Elements
    class Element
      def error_message
        return false unless error_class?
        find_error_tooltip.text
      end

      def error?
        # trigger onblur when checking errors since sometimes only changing the value does not work
        fire_event 'blur'
        error_class?
      end

      def error_class?
        attribute('class').include? 'error'
      end

      alias_method :has_error?, :error?

      def scroll_into_view
        script = 'arguments[0].scrollIntoView();'
        execute_script script
        self
      end

      # monkey patch click action to move away from divs partially covering it causing failures in Chrome browser
      # https://code.google.com/p/selenium/issues/detail?id=2766
      def click
        scroll_into_view
        element.click
      end

      #
      # Element method to execute script with element
      # The script to be executed should have the element as its first argument.
      #
      def execute_script(script, *args)
        element.browser.execute_script(script, self.element, *args)
      end

      private

      def find_error_tooltip
        element.element(xpath: "./following-sibling::div[@class='tooltip-container']")
      end
    end
  end
end
