jQuery(function($){

  EvolutionMan = function(selector, columns, rows){
    this.el = $(selector);
    this.columns = columns;
    this.rows    = rows;
    this.init();
    
    return this;
  };
  
  EvolutionMan.prototype = {
    init: function(){
      this.width   = 90;
      this.height  = 125;
      this.counter = 0;
      this.currentColumn = 1;
      this.currentRow    = 1;
    },
    start: function(time){
      var that;
      that = this;
      clearInterval(this.intV);
      this.intV = setInterval(function(){
        switch(that.counter){
          case 0:
            that.nextFrame();
            that.el.css('top', "+=30");
            that.counter++;
            break;
          case 1:
            that.prevFrame();
            that.el.css('top', "+=30");
            that.counter++;
            break;
          case 2:
            that.nextFrame();
            that.counter++;
            break;
          case 3:
            that.el.css('top', "+=50");
            that.nextFrame();
            that.counter++;
            break;
          case 4: 
            //that.el.css('top', "+=30");
            that.counter = 0;
            break;
        }
      }, time);
      return this;
    },
    stop: function(){
      clearInterval(this.intV);
      return this;
    },
    nextFrame: function(){
      if(this.currentColumn < this.columns){
        this.currentColumn++;
      }else if(this.currentRow < this.rows){
        this.currentColumn = 1;
        this.currentRow++;
      }else{
        var that = this;
        this.stop()
        this.el.fadeOut(500, function(){
          that.el.remove();
        });
        /*this.currentColumn = 1;
        this.currentRow    = 1;*/
      }
      this.setFrame(this.currentColumn, this.currentRow);
    },
    prevFrame: function(){
      if(this.currentColumn == this.columns){
        this.currentColumn--;
      }else if(this.currentRow == this.rows){
        this.currentColumn = this.columns;
        this.currentRow--;
      }else{
        this.currentColumn = this.columns;
        this.currentRow = this.rows;
      }
      this.setFrame(this.currentColumn, this.currentRow);
    },
    setFrame: function(col, row){
      if(col > this.columns || row > this.rows){
        console.error("Out of sprite");
        return false;
      }
      
      this.el.css('background-position', -((col - 1) * this.width) + "px " + -((row - 1) * this.height) + "px");
    }
  };
  
  var randomnumber=Math.floor(Math.random()*11);
  if (randomnumber==1){
  	$('#evolution_man').css('display', 'block');
  	evMan = new EvolutionMan('#evolution_man', 2, 6).start(1000);
  }
  
});
