 class Button extends Node
 
   constructor: (@video)->
-    button           = document.createElement('button')
-    button.title     = 'Pop out'
-    button.className = 'popout-for-youtube__button'
+    @alignmentInterval = null
+    button             = document.createElement('button')
+    button.title       = 'Pop out'
+    button.className   = 'popout-for-youtube__button'
     super button
     @setClickBehavior()
     @maintainAlignment()

  whenVideoChanges: (callback)->
    setInterval =>
      callback() if @videoChanged()
    , 250

  videoChanged: ->
    @videoId != @getVideoId()

  getVideoId: ->
    new URLSearchParams(document.location.search.substring(1)).get('v')

    @node.style.left = "#{point.x}px"

  remove: ->
    clearInterval @alignmentInterval
    @node.parentNode.removeChild @node

  maintainAlignment: ->
    @alignmentInterval = setInterval =>
      @align() # Can fail if the video node changes. Ignore.
    , 100

class YouTubeVideoPage

  constructor: ->

    @previousVideoId = null

    @whenVideoChanges =>
      try @button.remove() # Can fail if the button isn't arleady there. Ignore.
      @previousVideoId = @newVideoId
      @newVideoId      = @getVideoId()
      @video           = new Video @newVideoId
      @button          = new Button @video

      document.body.appendChild @button.node

      Extension.notifyVideoViewed()
