Meteor.startup ->
  Package.oauth.Oauth.initiateLogin = initiateLogin

getHostnameFromUrl = (url) ->
  aEl = document.createElement 'a'
  aEl.href = url
  aEl.hostname

initiateLogin = (credentialToken,
                 url,
                 credentialRequestCompleteCallback,
                 dimensions) ->
  # Default dimensions that worked well for Facebook and Google
  width = (dimensions and dimensions.width) or 650
  height = (dimensions and dimensions.height) or 331

  popup = openCenteredPopup url, width, height

  # Cordova only tests for when the popup is closed, relies on the
  # InAppBrowser plugin being installed in cordova.
  if cordova?
    popup.addEventListener 'loadstop', (e) ->
      url = e.url
      eventHostname = getHostnameFromUrl(url)
      meteorHostname = getHostnameFromUrl(Meteor.absoluteUrl())
      if eventHostname == meteorHostname
        popup.close()
        credentialRequestCompleteCallback credentialToken
  else
    checkPopupOpen = setInterval ->
      try
        # Fix for #328 - added a second test criteria (popup.closed === undefined)
        # to humour this Android quirk:
        # http://code.google.com/p/android/issues/detail?id=21061
        popupClosed = popup.closed or _.isUndefined popup.closed
      catch e
        # For some unknown reason, IE9 (and others?) sometimes (when
        # the popup closes too quickly?) throws "SCRIPT16386: No such
        # interface supported" when trying to read 'popup.closed'. Try
        # again in 100ms.
        return

      if popupClosed
        clearInterval checkPopupOpen
        credentialRequestCompleteCallback credentialToken
    , 100


openCenteredPopup = (url, width, height) ->
  screenX = window.screenX
  screenX = window.screenLeft unless screenX?

  screenY = window.screenY
  screenY = window.screenTop unless screenY?

  outerWidth = window.outerWidth
  outerWidth = document.body.clientWidth unless outerWidth?

  outerHeight = window.outerHeight
  # XXX: What's the 22?
  outerHeight = (document.body.clientHeight - 22) unless outerHeight?

  # Use `outerWidth - width` and `outerHeight - height` for help in
  # positioning the popup centered relative to the current window
  left = screenX + (outerWidth - width) / 2
  top = screenY + (outerHeight - height) / 2

  features = """
    width=#{width},height=#{height},left=#{left},top=#{top},scrollbars=yes
  """

  popup = window.open url, '_blank', 'location=no'
  popup.focus() if popup.focus?
  popup