var Phaser = Phaser || {};
var Ritual = Ritual || {};

Ritual.RunState = function () {
    "use strict";
    Phaser.State.call(this);
};

Ritual.RunState.prototype = Object.create(Phaser.State.prototype);
Ritual.RunState.prototype.constructor = Ritual.RunState;

var tw = 96;
var gameWidth = 10.66*tw;
var gameHeight = 8*tw;

Ritual.RunState.prototype.init = function (level_data) {
    "use strict";
    this.level_data = level_data;
	this.maxSteps = 12;
	
	this.obstacles = this.level_data.obstacles ? this.level_data.obstacles : ['obstacle'];
    this.scale.scaleMode = Phaser.ScaleManager.NO_SCALE;
    //this.scale.pageAlignHorizontally = true;
    //this.scale.pageAlignVertically = true;
	
	//create background and buttons
	this.setBackground();
    
    // start physics system
    //this.game.physics.startSystem(Phaser.Physics.ARCADE);
    //this.game.physics.arcade.gravity.y = 1000;
    
	// create map and set tileset
	//map = game.add.tilemap('map');

    //map.addTilesetImage('wall');
    //map.addTilesetImage('obstacle');

    //map.setCollisionBetween(1, 12);
	
	
	
    //this.map = this.game.add.tilemap(level_data.map.key);
    //this.map.addTilesetImage(this.map.tilesets[0].name, level_data.map.tileset);
};

Ritual.RunState.prototype.create = function () {
    "use strict";
    var group_name, object_layer, collision_tiles;
    
	// create map layers
    this.layers = {};
	
	// create groups
    this.groups = {};
    this.level_data.groups.forEach(function (group_name) {
        this.groups[group_name] = this.game.add.group();
    }, this);
    
	this.groups['menus'].add(buttonStart);
	this.groups['menus'].add(buttonBack);
	
    this.prefabs = {};
	this.winner = undefined;	
	
	this.create_object({
		"height":0,
        "name":"player1",
        "properties":
        {
			"leftPlayer": true,
            "bouncing":"20",
            "group":"players",
            "jumping_speed":"500",
            "texture":"player_spritesheet",
            "walking_speed":"200"
        },
        "type":"player",
        "visible":true,
        "width":0,
        "x":gameWidth/4 - tw,
        "y":gameHeight - 2*tw
	});
	
	this.create_object({
		"height":0,
        "name":"player2",
        "properties":
        {
            "leftPlayer": false,
			"bouncing":"20",
            "group":"players",
            "jumping_speed":"500",
            "texture":"player_spritesheet",
            "walking_speed":"200"
        },
        "type":"player",
        "visible":true,
        "width":0,
        "x":gameWidth/2 + gameWidth/4,
        "y":gameHeight - 2*tw
	});
	
	this.bangLeft = this.game.add.sprite(0, 0, 'bang');
	this.bangLeft.anchor.setTo(0.5, 0);
	this.bangLeft.visible = false;
    this.bangLeft.alpha = 1;
	this.bangLeft.scale.setTo(0.2, 0.2);
	this.bangRight = this.game.add.sprite(0, 0, 'bang');
	this.bangRight.anchor.setTo(0.5, 0);
	this.bangRight.visible = false;
    this.bangRight.alpha = 1;
	this.bangRight.scale.setTo(0.2, 0.2);
	
	this.readyFlag = false;
	
	/*
	this.create_object({
				"height":0,
				"name":"obstacle1",
				"properties":
				{
					"bouncing":"20",
					"group":"obstaclesLeft",
					"jumping_speed":"0",
					"texture":"obstacle",
					"walking_speed":"0"
				},
				"type":"obstacle",
				"visible":true,
				"width":0,
				"x":gameWidth/4 + tw + gameWidth/4,
				"y":gameHeight - tw
			});
	*/
	this.add_obstacles();
	
	this.add_walls();
};

Ritual.RunState.prototype.setBackground = function() {
	//game.stage.backgroundColor = '#0055ff';
	
	//game.stage.backgroundColor = '#2d2d2d';
	var padding = 0;
	bg1 = game.add.tileSprite(padding, -gameHeight*(this.maxSteps - 1), gameWidth/2, gameHeight*this.maxSteps, 'background');
	bg2 = game.add.tileSprite(padding + gameWidth/2, -gameHeight*(this.maxSteps - 1), gameWidth/2, gameHeight*this.maxSteps, 'background');
	
	buttonStart = game.add.button(game.world.centerX, game.world.centerY - 13, 'buttonStart', this.actionOnStart, this, 1, 0, 0);
    buttonStart.anchor.setTo(0.5, 0.5);

    buttonBack = game.add.button(game.world.centerX, game.world.centerY + 62, 'buttonBack', this.actionOnBack, this, 1, 0, 0);
    buttonBack.anchor.setTo(0.5, 0.5);	
}

Ritual.RunState.prototype.actionOnBack = function() {
    window.location.href = "../index.html"
}

Ritual.RunState.prototype.actionOnStart = function() {
    //this.readyFlag = true;
    buttonStart.visible = false;
    buttonBack.visible = false;

    one = game.add.sprite(game.world.centerX, game.world.centerY, 'one');
    one.anchor.setTo(0.5, 0.5);
    one.alpha = 1;
    e = game.add.tween(one.scale).to({x: 2, y: 2, alpha: 0}, 700, "Linear");
    e.start();
    e = game.add.tween(one).to({alpha: 0}, 700, "Linear");
    e.onComplete.add(this.twoTween, this);
    e.start();
}

Ritual.RunState.prototype.twoTween = function() {
    two = game.add.sprite(game.world.centerX, game.world.centerY, 'two');
    two.anchor.setTo(0.5, 0.5);
    two.alpha = 1;
    e = game.add.tween(two.scale).to({x: 2, y: 2, alpha: 0}, 700, "Linear");
    e.start();
    e = game.add.tween(two).to({alpha: 0}, 700, "Linear");
    e.onComplete.add(this.threeTween, this);
    e.start();

}

Ritual.RunState.prototype.threeTween = function() {
    three = game.add.sprite(game.world.centerX, game.world.centerY, 'three');
    three.anchor.setTo(0.5, 0.5);
    three.alpha = 1;
    e = game.add.tween(three.scale).to({x: 2, y: 2, alpha: 0}, 700, "Linear");
    e.start();
    e = game.add.tween(three).to({alpha: 0}, 700, "Linear");
    e.onComplete.add(this.startTween, this);
    e.start();

}

Ritual.RunState.prototype.startTween = function() {
    fight = game.add.sprite(game.world.centerX, game.world.centerY, 'start');
    fight.anchor.setTo(0.5, 0.5);
    fight.alpha = 1;
    e = game.add.tween(fight.scale).to({x: 2, y: 2, alpha: 0}, 700, "Linear");
    e.start();
    e = game.add.tween(fight).to({alpha: 0}, 700, "Linear");
    e.start();

    this.readyFlag = true;
}

Ritual.RunState.prototype.showEndButtons = function() {
    buttonBack.visible = true;
    buttonAgain = game.add.button(game.world.centerX, game.world.centerY - 13, 'buttonAgain', this.actionOnAgain, this, 1, 0, 0);
	this.groups['menus'].add(buttonAgain);
    buttonAgain.anchor.setTo(0.5, 0.5);
}

Ritual.RunState.prototype.actionOnAgain = function() {
    window.location.reload();
}

Ritual.RunState.prototype.winPlayer1 = function() {
    player1wins = game.add.sprite(game.world.centerX, 144, 'player1wins');
    player1wins.anchor.setTo(0.5, 0);

    setTimeout(this.showTurtle(1), 10000);
}

Ritual.RunState.prototype.winPlayer2= function() {
    player2wins = game.add.sprite(game.world.centerX, 144, 'player2wins');
    player2wins.anchor.setTo(0.5, 0);

    setTimeout(this.showTurtle(2), 10000);
}

Ritual.RunState.prototype.showTurtle = function(winner) {
    this.showEndButtons();
	if (winner == 1) {
        turtle1 = game.add.sprite(80, 240, 'big_turtle');
    } else {
        turtle2 = game.add.sprite(950, 240, 'big_turtle');
		turtle2.scale.setTo(-1, 1);
    }
}

Ritual.RunState.prototype.update = function () {
	if(this.winner || !this.prefabs.player1 || !this.prefabs.player2) {
		return;
	}
	
	if(this.prefabs.player1.justHitted) {
		this.prefabs.player1.justHitted = false;
		bg1.y -= 40;
		this.bang(this.bangLeft, this.prefabs.player1.x, this.prefabs.player1.y);
	}
	
	if(this.prefabs.player2.justHitted) {
		this.prefabs.player2.justHitted = false;
		bg2.y -= 40;
		this.bang(this.bangRight, this.prefabs.player2.x, this.prefabs.player2.y);
	}
	
	/*
	if(bg1.y > 0) {
		bg1.y = -gameHeight/2;
		this.add_step(true);
	}
	else {
		bg1.y += this.prefabs.player1.speed;
	}
	*/
	
	bg1.y += this.prefabs.player1.speed;
	
	//console.log((Math.abs(bg1.y) / gameHeight) + ' < ' + this.prefabs.player1.steps);
	
	if(Math.abs(bg1.y) / gameHeight < (this.maxSteps - 1 - this.prefabs.player1.steps)) {
		this.add_step(true);
	}
	
	this.groups.obstaclesLeft.y += this.prefabs.player1.speed;
	
	/*
	if(bg2.y > 0) {
		bg2.y = -gameHeight/2;
		this.add_step(false);
	}
	else {
		bg2.y += this.prefabs.player2.speed;
	}
	*/
	bg2.y += this.prefabs.player2.speed;
	
	//console.log(bg1.y);
	
	if(Math.abs(bg2.y) / gameHeight < (this.maxSteps - 1 - this.prefabs.player2.steps)) {
		this.add_step(false);
	}
	
	this.groups.obstaclesRight.y += this.prefabs.player2.speed;	
	
	//this.prefabs.player1.y -= this.prefabs.player1.speed;
	//this.prefabs.player2.y -= this.prefabs.player2.speed;
	
	//console.log(this.prefabs.player1.steps + ' : ' + this.maxSteps);
		
	if(this.prefabs.player1.steps >= this.maxSteps - 1) {
		this.winner = 'Player1';
		//console.log('player1 wins');
		this.winPlayer1();
	}
	
	if(this.prefabs.player2.steps >= this.maxSteps - 1) {
		if(this.winner) {
			//this.winner = 'Both players'
			console.log('we have a draw');
		}
		
		this.winner = 'Player2';
		this.winPlayer2();
	}
	
	if(this.winner) {
		this.prefabs.player1.speed = -1;
		this.prefabs.player1.speed = -1;
		//var text = game.add.bitmapText(gameWidth/2, gameHeight/2, 'desyrel', this.winner + ' wins!!!', 64);
		//text.anchor.x = 0.5;
		//text.anchor.y = 0.5;
	}
	
	return;
}

Ritual.RunState.prototype.add_obstacles = function (object) {

	var textures = this.obstacles;
	
	//console.log(textures);
	
	var goalLeft = this.game.add.sprite(gameWidth/4 - tw + 0.25*tw, gameHeight - 6*tw - (this.maxSteps - 4)*10*tw, 'goal');
	this.groups['obstaclesLeft'].add(goalLeft);
	
	var goalRight = this.game.add.sprite(gameWidth/2 + gameWidth/4 - 0.25*tw, gameHeight - 6*tw - (this.maxSteps - 4)*10*tw, 'goal');
	this.groups['obstaclesRight'].add(goalRight);

	for(var row = 4; row < (this.maxSteps - 4)*10; row++) {
		if(Math.random() > 0.5) {
			continue;
		}
		for(var i=0; i<2; i++) {
			if(i == 1 && Math.random() > 0.5) {
				continue;
			}
			
			var texture = textures[Math.min(textures.length -1, Math.floor(Math.random()*textures.length))];
			var lx = Math.floor(Math.random()*5)*tw;
			var y = gameHeight - tw - row*tw;
			var rx = 5.75*tw + lx;
			this.create_object({
				"height":0,
				"name":"obstacle1",
				"properties":
				{
					"bouncing":"20",
					"group":"obstaclesLeft",
					"jumping_speed":"0",
					"texture":texture,
					"walking_speed":"0"
				},
				"type":"obstacle",
				"visible":true,
				"width":0,
				"x":lx,
				"y":y
			});
			
			this.create_object({
				"height":0,
				"name":"obstacle1",
				"properties":
				{
					"bouncing":"20",
					"group":"obstaclesRight",
					"jumping_speed":"0",
					"texture":texture,
					"walking_speed":"0"
				},
				"type":"obstacle",
				"visible":true,
				"width":0,
				"x":rx,
				"y":y
			});
		}
	}
}

Ritual.RunState.prototype.add_walls = function (object) {
	for(i = 0; i < 10; i++) {
		this.create_object({
			"height":0,
			"name":"wall" + i,
			"properties":
			{
				"bouncing":"20",
				"group":"walls",
				"jumping_speed":"0",
				"texture":"wall",
				"walking_speed":"0"
			},
			"type":"wall",
			"visible":true,
			"width":0,
			"x":gameWidth/2 - tw/2,
			"y":gameHeight - (i+1) * tw
		});
	}
	
	//bottom walls
	for(i = 0; i <= 10; i++) {
		this.create_object({
			"height":0,
			"name":"wall_bottom" + i,
			"properties":
			{
				"bouncing":"20",
				"group":"walls",
				"jumping_speed":"0",
				"texture":"wall",
				"walking_speed":"0"
			},
			"type":"wall",
			"visible":true,
			"width":0,
			"x":i*tw,
			"y":gameHeight - 64
		});
	}
	
	game.add.sprite(0, gameHeight - 56, 'controls_left');
	game.add.sprite(gameWidth - 268, gameHeight - 56, 'controls_right');
	
	//top walls
	for(i = 0; i <= 10; i++) {
		this.create_object({
			"height":0,
			"name":"wall_top" + i,
			"properties":
			{
				"bouncing":"20",
				"group":"walls",
				"jumping_speed":"0",
				"texture":"wall",
				"walking_speed":"0"
			},
			"type":"wall",
			"visible":true,
			"width":0,
			"x":i*tw,
			"y":-32
		});
	}
	
	game.add.sprite(0, 0, 'player1');
	game.add.sprite(gameWidth - 190, 0, 'player2');
	game.add.sprite(gameWidth/2 - 212, 0, 'title');
}

Ritual.RunState.prototype.bang = function(bangInstance, x, y) {
	bangInstance.alpha = 1;
	bangInstance.scale.setTo(0.2, 0.2);
	bangInstance.x = x;
	bangInstance.y = y - tw/2;
	bangInstance.visible = true;
    e = this.game.add.tween(bangInstance.scale).to({x: 1, y: 1, alpha: 0}, 700, "Linear");
    e.start();
    e = this.game.add.tween(bangInstance).to({alpha: 0}, 700, "Linear");
    e.onComplete.add(this.hideBang, this);
    e.start();
}

Ritual.RunState.prototype.hideBang = function(bangInstance) {
	bangInstance.visible = false;
}

Ritual.RunState.prototype.add_step = function (left) {
	var steps = 0;
	if(left) {
		this.prefabs.player1.steps++;
		steps = this.prefabs.player1.steps;
	}
	else {
		this.prefabs.player2.steps++;
		steps = this.prefabs.player2.steps;
	}
	this.create_object({
		"height":0,
		"name":"step" + i + 'player' + (left ? '1' : '2'),
		"properties":
		{
			"bouncing":"20",
			"group":"steps",
			"jumping_speed":"0",
			"texture":"steps",
			"walking_speed":"0"
		},
		"type":"wall",
		"visible":true,
		"width":0,
		"x":gameWidth/2 - tw/2 - (left ? 1 : -1) * tw/4,
		"y":gameHeight - tw*0.8 - steps*tw/1.65
	});
}

Ritual.RunState.prototype.create_object = function (object) {
    "use strict";
    var position, prefab;
    // tiled coordinates starts in the bottom left corner
    position = {"x": object.x + tw/2, "y": object.y + tw/2};
    // create object according to its type
    switch (object.type) {
    case "player":
		position.y -= 1;
        prefab = new Ritual.Player(this, position, object.properties);
        break;
	case "obstacle":
		prefab = new Ritual.Obstacle(this, position, object.properties);
        break;
    case "wall":
        //console.log('wall');
		prefab = new Ritual.Wall(this, position, object.properties);
        break;
    }
    this.prefabs[object.name] = prefab;
};

Ritual.RunState.prototype.restart_level = function () {
    "use strict";
    this.game.state.restart(true, false, this.level_data);
};
