Num = {  
  level: 1 ,
  cells: [],
  grid_size: 8,
  px: 6,
  py: 6,
  mx:-1,
  my:-1,
  correct: 0,
  mtimer: null,
  mtime: 2000,
  score: 0,
  lives: 0,
  
  init: function(){
    this.level = 1;
    this.correct = 0;
    this.lives = 2;
    this.score = 0;
    this.initLevel(this.level+1);
    this.initPlayer();
    this.initMonster();
  },

  drawNumbers: function(){
    $('#level').html(this.level);
    $('#score').html(this.score);
    $('#task').html(this.level+1);
    $('#lives').html(this.lives);
  },
  
  initPlayer: function(){
    $(this.gel(this.py, this.px)).removeClass('pl');
    this.px = 6;
    this.py = 6;
    this.drawPlayer();
  },
  
  initMonster: function (){
    $(this.gel(this.my, this.mx)).removeClass('mn');
    this.mx = -1;
    this.my = -1;
    if(this.mtimer){
      clearTimeout(this.mtimer);
    }
    this.mtimer = setTimeout('Num.moveMonster()', this.mtime);
  },
  
  moveMonster: function(){
    if (this.mx == -1){
      this.mx = 0
      this.my = 0
    } else {
      var dir = -1; 
      var dx = 0;
      var dy = 0;
      do {
        dir = Math.floor(Math.random()*4);
        switch(dir){
          case 0: dx = 0; dy = -1; break;
          case 1: dx = 1; dy = 0; break;
          case 2: dx = 0; dy = 1; break;
          case 3: dx = -1; dy = 0; break; 
        }
      } while (!this.canMoveMonster(dy, dx));
      $(this.gel(this.my, this.mx)).removeClass('mn');
      this.mx = this.mx+dx;
      this.my = this.my+dy;    
    }
    $(this.gel(this.my, this.mx)).addClass('mn');
    if (!this.checkGotcha()){ 
      this.mtimer = setTimeout('Num.moveMonster()', this.mtime)
    }
  },
  
  canMoveMonster: function(dy, dx){
    return ((this.mx + dx < this.grid_size) 
      && this.mx+dx >=0 
      && (this.my + dy < this.grid_size)
      && this.my+dy >=0);
  },
  
  gel: function(y, x){
    return '#c_'+y+'_'+x;
  },
  
  movePlayer: function(dy, dx){
    if ((dx != 0) && (this.px + dx < this.grid_size) && (this.px + dx >= 0)) {
      nx = this.px + dx;
      $(this.gel(this.py, this.px)).removeClass('pl');
      this.px = nx;
      this.drawPlayer();
    }
    if ((dy != 0) && (this.py + dy < this.grid_size) && (this.py + dy >= 0)) {
      ny = this.py + dy;
      $(this.gel(this.py, this.px)).removeClass('pl');
      this.py = ny;
      this.drawPlayer();
    }
    this.checkGotcha();
  },
  
  drawPlayer: function(){
    $(this.gel(this.py, this.px)).addClass('pl');
  },
    
  initLevel: function(level){
    var values = [];
    this.cells = [];
    this.correct = 0;
    this.drawNumbers();
    var n;
    for (var i = 0; i < 10; i++){
      n = Math.floor(Math.random()*level);
      values.push({'f': n, 's': level-n});
    }
    var vcount = this.grid_size * this.grid_size;
    
    do{
      n = Math.floor(Math.random()*level);
      m = Math.floor(Math.random()*level);
      if (n+m != level && n+m > 0){
        values.push({'f': n, 's': m});
      }
    } while (values.length < vcount);
    var shf = this.shuffle(values);
    for (var y = 0; y < this.grid_size; y++){
      this.cells[y] = []
      for (var x = 0; x< this.grid_size; x++){
        this.cells[y][x] = values.pop();
        this.text(y, x, this.cells[y][x]);
      }
    } 
    //console.log(this.cells);
  },
  
  notice: function (text){
    var notice = $('#notice');
    notice.hide();
    notice.html(text);
    notice.fadeIn(1).show().fadeOut(1000);
  },
  
  checkGotcha: function(){
    if (this.px == this.mx && this.py == this.my){
      if(this.mtimer){
        clearTimeout(this.mtimer);
      }
      this.notice('Сгащи те математическата полиция');
      this.lives--;
      this.drawNumbers();
      if (this.lives <0){
        this.notice('Нямаш повече опити, ще трябва да започнеш отначало');
        this.init();
        return true;
      }
      this.initPlayer();
      this.initMonster();
      return true;
    }
  },
  
  checkTile: function(){
    var cell = this.cells[this.py][this.px];
    if (cell.f != -1){
      if (cell.f+cell.s == this.level+1){
        this.cells[this.py][this.px] = {'f': -1, 's': -1};
        $(this.gel(this.py, this.px)).html('');
        this.correct++;
        this.score++;
        this.drawNumbers();
        this.notice('правилно '+this.correct+'/10');
        if (this.correct == 10){
          //new level
          this.level = this.level+1;
          this.notice('Ура!<br /> Мина на '+this.level+' ниво');
          this.initLevel(this.level+1);
        } 
      } else {
        this.notice('грешка '+this.correct+'/10');
        this.lives--;
        this.drawNumbers();
        if (this.lives <0){
          this.notice('Нямаш повече опити, ще трябва да започнеш отначало');
          this.init();
        }      
      }
    }
  },
  
  text: function(y, x, nums){
    var ename = '#c_'+y+'_'+x;
    $(ename).html(nums.f+'+'+nums.s);
  },
  
  shuffle: function(o){ //v1.0
	  for(var j, x, i = o.length; i; j = parseInt(Math.random() * i), x = o[--i], o[i] = o[j], o[j] = x);
	  return o;
  },
  
  start: function(){
    
  },
}
Num.init();

$(document).keydown(function(event){
  if(event.keyCode == 38){
    Num.movePlayer(-1, 0);
    event.preventDefault();
  };
  if(event.keyCode == 40){
    Num.movePlayer(1, 0);
    event.preventDefault();
  };
  if(event.keyCode == 37){
    Num.movePlayer(0, -1);
    event.preventDefault();
  }
  if(event.keyCode == 39){
    Num.movePlayer(0, 1);
    event.preventDefault();
  }
  if(event.keyCode == 32){
    Num.checkTile();
    event.preventDefault();
  }
});

