 class Board
   constructor: (@id) ->
     @board = Snap(@id)
-
-    @board.mouseup () ->
-      if game.state is game.states.Empty
-        @board.init()
+    @board.mouseup @mouseUpHandler
 
     @nbHorizontalCases = 19
     @nbVerticalCases = 13
     @cases = []
+
+
+  mouseUpHandler: (evt) =>
+    if game.state is game.states.Empty
+      @board.init()
 
 
   createBoard: () ->

    @flagsLbl.transform 'translate(0, 580)'



class Flag extends Case
  constructor: () ->
    super
    @g.append Flag.render @ctx, @size

  @render: (ctx, size) ->
    polygon = ctx.polygon([size/3, size/2,

    @g = @ctx.g @tileBackground
    @g.transform "translate(#{@x * @size}, #{@y * @size})"

    @g.mouseover @mouseOverHandler
    @g.mouseout @mouseOutHandler
    @g.mouseup @mouseUpHandler


  mouseOverHandler: (evt) =>
    if game.state isnt game.states.GameOver
      @tileBackground.attr fill: '#ccc'


  mouseOutHandler: (evt) =>
    if game.state isnt game.states.GameOver
      @tileBackground.attr fill: '#ddd'


  mouseUpHandler: (evt) =>
    return if game.state is game.states.GameOver
    if game.state is game.states.Empty
      game.initGame @x, @y

    if evt.button is 2 # Right click
      casePosition = game.positionFromCoord @x, @y
      game.board.cases[casePosition].g.remove()
      if game.board.cases[casePosition].constructor is Flag
        game.board.flagsLbl.attr text: --game.flags
        game.board.cases[casePosition] = new Case @ctx, @x, @y
      else
        game.board.flagsLbl.attr text: ++game.flags
        game.board.cases[casePosition] = new Flag @ctx, @x, @y
    else
      @showCase()


  showCase: () ->
    casePosition = game.positionFromCoord @x, @y
