var $ = require('jquery');
var Light = require('./light');
var Levels = require('./levels');
var neighborCoords = require('./neighbor-coords');

function Board(level) {
  this.width = 5;
  this.element = $('.board');
  this.levelsGenerator = new Levels();
  this.level = level || this.randomLevel();
  this.clearGrid();
  this.initLightGrid();
}

Board.prototype.clearGrid = function () {
  $('.board').empty();
};

Board.prototype.randomLevel = function(){
  return this.levelsGenerator.random();
}

Board.prototype.jsonLitStatus = function (x, y) {
  var row = this.level[parseInt(y)];
  return row[x];
};

Board.prototype.getLit = function(x, y) {
  if(this.jsonLitStatus(x, y) === "1") {
    return true;
  } else {
    return false;
  }
};

Board.prototype.initLightGrid = function(){
  var grid = this.createEmptyGrid(this.width, this.width);
  this.lightGrid = this.fillLightGrid(grid);
};

Board.prototype.fillLightGrid = function(grid) {
  for(var j = 0; j < this.width; j++){
    for(var i = 0; i < this.width; i++){
      var lit = this.getLit(i, j);
      grid[i][j] = new Light(i, j, this, lit);
    }
  }
  return grid;
};

Board.prototype.createEmptyGrid = function(width, height) {
  var grid = new Array(width);
  for(var i = 0; i < width; i++){
    grid[i] = new Array(height);
  }
  return grid;
};

Board.prototype.equals = function(other) {
  for(var i = 0; i < this.width; i++) {
    for(var j = 0; j < this.width; j++) {
      if(this.lightGrid[i][j].lit !== other.lightGrid[i][j].lit) return false;
    }
  }
  return true;
};

Board.prototype.getNeighbors = function(light){
  return neighborCoords(light.x, light.y, this).map(function(pair){
    return this.lightGrid[pair[0]][pair[1]];
  }.bind(this));
};

Board.prototype.updateNeighbors = function(light){
  this.getNeighbors(light).forEach(function(light){
    light.flipSwitch().rerender();
  }.bind(this));
};

Board.prototype.countLights = function() {
  return this.element.find('.lit').length;
};

Board.prototype.toJSON = function() {
  var level = {};
  for(var y = 0; y < this.width; y++) {
    var row = "";
    for(var x = 0; x < this.width; x++) {
      row = row + this.lightGrid[x][y].isLitJSON();
    }
    level[y] = row;
  }
  return level;
};

module.exports = Board;

@@ -1992,17 +1992,20 @@
 ototype.
-t
+rowT
 oJSON = 
@@ -2009,24 +2009,25 @@
  = function(
+y
 ) %7B%0A  var le
@@ -2028,80 +2028,23 @@
 var 
-level = %7B%7D;%0A  for(var y = 0; y %3C this.width; y++) %7B%0A    var row
+converted
  = %22%22
-;%0A  
+%0A
   fo
@@ -2087,21 +2087,20 @@
     
-  row = row
+converted
  +
+=
  thi
@@ -2136,30 +2136,162 @@
 ;%0A  
-  %7D%0A    level%5By%5D = row
+%7D%0A  return converted;%0A%7D;%0A%0ABoard.prototype.toJSON = function() %7B%0A  var level = %7B%7D;%0A  for(var y = 0; y %3C this.width; y++) %7B%0A    level%5By%5D = this.rowToJSON(y)
 ;%0A  

Factor out rowToJSON