ig.module( 
	'game.main' 
)
.requires(
	'impact.game',
	'impact.font',

	// Entities.
	'game.entities.pirate',
	'game.entities.coins',
	'game.entities.chest',
	'game.entities.potion',
	'game.entities.showel',
	'game.entities.busk',
		'game.entities.busk2',
			'game.entities.busk3',
			'game.entities.jordhaug',


	'game.entities.buttonnext',

	'game.entities.spawnpoint',
	'game.entities.spawnchest',
	'game.entities.spawnShowels',

	// Levels.
	'game.levels.island',

	// Plugins.
	'plugins.impactconnect',
	'plugins.inputBox'
)
.defines(function(){

MyGame = ig.Game.extend({
	
	// Load a font
	font: new ig.Font( 'media/areal16black.font.png' ),
	font2: new ig.Font( 'media/cambria18.font.png' ),

	endscreen: new ig.Image('media/endscreen.png'),

	snd_angry: new ig.Sound( 'media/sound/angry.*' ),
	sword: new ig.Sound( 'media/sound/sword.*' ),
	snd_wind: new ig.Sound( 'media/sound/wind.*' ),
	snd_birds: new ig.Sound( 'media/sound/birds.*'),
	snd_evil: new ig.Sound( 'media/sound/evil.*'),

	    startscreen: new ig.Image('media/startscreen.png'),

	pirates: [],
	player_id: 0,
	player: null,

	on_island: true, // If game has started and is running.

	host: false, // Game world runs at host. Set to false before game starts and until lobby system sets host.
	potions: [],
	coins: [],
	chests: [],
	showels: [],

	screenX: 800,
	screenY: 600,

	gamesocket: null,
	is_connected: false,

	debug: true,

	my_id: null,
	others: [],

	state: 0,

	btn_next1: null,
	btn_next2: null,
	input_box: null,

    inputb: null,
    failedtojoin: false,
    have_showel: false,
    showel_img: new ig.Image('media/showel.png'),
    timer: new ig.Timer(1),
    time: 180,

    timer_wind: new ig.Timer(15),
    timer_birds: new ig.Timer(19),

	roomid: "",
	
	init: function() {
        this.cameraTimer = new ig.Timer(0.1);

        this.input_box = new ig.InputBox();

		// WASD movement.
		ig.input.bind( ig.KEY.UP_ARROW, 'up' );
		ig.input.bind( ig.KEY.DOWN_ARROW, 'down' );
		ig.input.bind( ig.KEY.LEFT_ARROW, 'left' );
		ig.input.bind( ig.KEY.RIGHT_ARROW, 'right' );

		// Arrow keys movement.
		ig.input.bind( ig.KEY.W, 'up' );
		ig.input.bind( ig.KEY.S, 'down' );
		ig.input.bind( ig.KEY.A, 'left' );
		ig.input.bind( ig.KEY.D, 'right' );

		// Other.
		ig.input.bind( ig.KEY.C, 'C' );
		ig.input.bind( ig.KEY.C, 'V' );
		ig.input.bind( ig.KEY.MOUSE1, 'mouse_l' );

		ig.input.bind( ig.KEY.ENTER, 'start' );

		// Init mouse coordinates.
		ig.input.initMouse();

		//this.loadLevel(LevelIsland);
		this.btn_next1 = new EntityButtonnext(460, 300 + 180, {id:0});
		this.btn_next2 = new EntityButtonnext(460, 300 + 236, {id:1});

		ig.music.add('media/sound/music.*');
		ig.music.volume = 0.5;
		ig.music.play();
		//ig.music.loop = true;

		// Create socket connection.
        this.gamesocket = new ig.Impactconnect(13336);
	},
	
	update: function() {
		// Update all entities and backgroundMaps
		this.parent();
		
		if(this.player !== null) {
			this.handleInput();

			this.cameraMovement();


			if(this.host) {
				this.updateGameWorld();
			}
		}

		if(ig.input.pressed('mouse_l')) {
			ig.system.canvas.focus();
		}

		if(this.btn_next1 !== null)
			this.btn_next1.mouseCollision();

		if(this.btn_next2 !== null) {
			this.btn_next2.mouseCollision();
		}

		if(ig.game.host) {
			if(ig.game.state !== 0
			&& ig.game.state !== 1
			&& ig.game.state !== 2 
			&& ig.game.state !== 3 
			&& ig.game.state !== 199)
			{
				if(ig.game.timer.delta() > 0) {
					ig.game.timer.reset();

					ig.game.time--;

					ig.game.gamesocket.send(
						'broadcast',
						{
							t:"time",
							time:this.time
						}
					);
				}
			}

			if(ig.game.time <= 0) {
				ig.game.state = 199;
			}

			if(ig.game.timer_wind.delta() > 0) {
				//ig.game.timer_wind.reset();
				//ig.game.snd_wind.play();
			}

			if(ig.game.timer_birds.delta() > 0) {
				ig.game.timer_birds.reset();
				ig.game.snd_birds.play();
			}
		}
	},

    // States.
    // 0 - 1 - 2
    // 3 - 4 - 5
    // 6 - 7 - 8
	handleInput: function() {
		if(this.on_island) {
			var dir = -1;
			if(ig.input.state('up')) {
				if(ig.input.state('left')) {
					dir = 0;
				} else if(ig.input.state('right')) {
					dir = 2;
				} else {
					dir = 1;
				}
			}

			else if(ig.input.state('down')) {
				if(ig.input.state('left')) {
					dir = 6;
				} else if(ig.input.state('right')) {
					dir = 8;
				} else {
					dir = 7;
				}
			}

			else if(ig.input.state('left')) {
				dir = 3;
			}

			else if(ig.input.state('right')) {
				dir = 5;

			} else {
				dir = 4;
			}

			if(dir !== -1) {
				// Host handles input locally and sends notice to other clients.
				if(ig.game.host) {
					if(ig.game.player.state !== null && dir !== ig.game.player.state) {
						ig.game.player.changeState(dir);

						//if(ig.game.debug)
						//	console.log("Attempting to send " + dir + " from host: " + this.player.id);

						ig.game.gamesocket.send(
							'state',
							{
								id:ig.game.player.id,
								angle:ig.game.player.angle,
								state:dir,
								x:ig.game.player.pos.x,
								y:ig.game.player.pos.y,
	                			key: ig.game.roomid
							}
						);
					}

				} else { // Other clients sends input notice to host.
					// Send input to host.
					if(dir !== ig.game.player.state) {
						ig.game.player.changeState(dir);
						//if(ig.game.debug)
						//	console.log("Attempting to send input " + dir + " from " + this.player.id);
						// Send notice to others clients.
						ig.game.gamesocket.send(
							'key',
							{
								id:ig.game.player.id,
								angle:ig.game.player.angle,
								state:dir,
								x:ig.game.player.pos.x,
								y:ig.game.player.pos.y,
	                			key: ig.game.roomid
							}
						);
					}
				}
			}

			// Hit.
			if(ig.input.pressed('mouse_l')) {
				if(ig.game.player.currentAnim !== ig.game.player.anims.attack) {
					ig.game.sword.play();

					hitposx = ig.game.player.pos.x + (ig.game.player.size.x/2) + (Math.sin( ig.game.player.currentAnim.angle ) * 64);
					hitposy = ig.game.player.pos.y + (ig.game.player.size.y/2) - (Math.cos( ig.game.player.currentAnim.angle ) * 64);

					if(ig.game.debug)
						console.log("Player pirate is hitting at location " + hitposx + " " + hitposy + ".");

					if(ig.game.host) {
						ig.game.player.hit(ig.game.player.angle);
						// Notify clients.
						if(ig.game.is_connected) {
							ig.game.gamesocket.send(
								'broadcast',
								{
									t:"hit",
									id:ig.game.player.id,
									state:10,
									x:ig.game.player.pos.x,
									y:ig.game.player.pos.y,
									angle:ig.game.player.angle,
                					key: ig.game.roomid
								}
							)
						}

						for(var i = 0; i < ig.game.pirates.length; i++) {
							if(ig.game.pirates[i] === ig.game.player)
								continue;

							if(ig.game.pirates[i].touchesXY(hitposx, hitposy)) {							
								ig.game.setPirateGotHit(ig.game.pirates[i].id, ig.game.player.id);
							}
						}
					} else {
						ig.game.sword.play();
						// Notify input to host.
						ig.game.gamesocket.send(
							'key',
							{
								id:ig.game.player.id,
								state:10,
								x:ig.game.player.pos.x,
								y:ig.game.player.pos.y,
								angle:ig.game.player.angle,
            					key: ig.game.roomid
							}
						)

						if(ig.game.debug)
							console.log("Player " + ig.game.player.id + " is attempting to hit someone. Sends input to server.");
					}
				}
			}
		}
	},


	updateGameWorld: function() { // Host updates game world.
		// Pirate collision against potions.
		for(var i = 0; i < ig.game.potions.length; i++) {
			for(var j = 0; j < ig.game.pirates.length; j++) {
				if(ig.game.potions[i] !== undefined && ig.game.potions[i].touches(ig.game.pirates[j])) {
					if(ig.game.pirates[j].hp !== 3) { // Pick up if not full health.
						// Give other clients notice.
						ig.game.gamesocket.send('broadcast', 
							{
								t:"pp",
								index:i,
								c_id:ig.game.potions[i].id,
								p_id:ig.game.pirates[j].id,
								key:ig.game.roomid
							}
						);

						ig.game.pickUpPotion(i, ig.game.potions[i].id, ig.game.pirates[j].id);
						return;
					}
				}
			}
		}


		// Pirate collision against coins.
		for(var i = 0; i < ig.game.coins.length; i++) {
			for(var j = 0; j < ig.game.pirates.length; j++) {
				if(ig.game.coins[i] !== undefined && ig.game.coins[i].touches(ig.game.pirates[j])) {
					// Give other clients notice.
					ig.game.gamesocket.send('broadcast', 
						{
							t:"pc",
							index:i,
							c_id:ig.game.coins[i].id,
							p_id:ig.game.pirates[j].id,
							key:ig.game.roomid
						}
					);

					ig.game.pickUpCoins(i, ig.game.coins[i].id, ig.game.pirates[j].id);
					return;
				}
			}
		}

		// Pirate collision against chests.
		for(var i = 0; i < ig.game.chests.length; i++) {
			for(var j = 0; j < ig.game.pirates.length; j++) {
				if(ig.game.chests[i].touches(ig.game.pirates[j])) {
					if(ig.game.chests[i].owner_id !== ig.game.pirates[j].id) {

						ig.game.snd_evil.play();

						// Give other clients notice.
						ig.game.gamesocket.send('broadcast', 
							{
								t:"c",
								c_id:i,
								p_id:ig.game.pirates[j].id,
								key:ig.game.roomid
							}
						);

						ig.game.setNewChestOwner(i, ig.game.pirates[j].id);
						return;
					}
				}
			}
		}
	},

	pickUpPotion: function(index, id, pirate_id) {
		var spawnpoints = ig.game.getEntitiesByType(EntitySpawnpoint);

    	for(var i = 0; i < spawnpoints.length; i++) {
    		if(id === spawnpoints[i].id) {
				spawnpoints[i].has_potion = false;
    		}
    	}

		ig.game.potions[index].kill();
		ig.game.potions.splice(index, 1);

		// Add HP.
		ig.game.getPirate(pirate_id).hp++;

		if(ig.game.debug)
			console.log("Pirate " + pirate_id + " picked up potions now has " + ig.game.getPirate(pirate_id).score + " hp.");
	},

	pickUpCoins: function(index, id, pirate_id) {
		var spawnpoints = ig.game.getEntitiesByType(EntitySpawnpoint);

    	for(var i = 0; i < spawnpoints.length; i++) {
    		if(id === spawnpoints[i].id) {
				spawnpoints[i].has_coin = false;
    		}
    	}

		ig.game.coins[index].kill();
		ig.game.coins.splice(index, 1);

		ig.game.getPirate(pirate_id).score += 10;

		if(ig.game.debug)
			console.log("Pirate " + pirate_id + " picked up 10 coins and now has " + ig.game.getPirate(pirate_id).score + " coins.");
	},

	setNewChestOwner: function(index, pirate_id) {
		ig.game.getPirate(pirate_id).score += 100;

		// Last owner gets score reduced.
        if(ig.game.chests[index].owner_id !== -1)
            ig.game.getPirate(ig.game.chests[index].owner_id).score -= 100;

        if(ig.game.debug)
			console.log("Pirate " + pirate_id + " is set as new owner of chest " + index + ". It was stolen from " + ig.game.chests[index].owner_id);

        ig.game.chests[index].owner_id = pirate_id;
    },

    leaveGame: function() {

    },

	respawnPirate: function(pirate_id, id) {
		var spawnpoints = ig.game.getEntitiesByType(EntitySpawnpoint);
		var pirate = ig.game.getPirate(pirate_id);

    	for(var i = 0; i < spawnpoints.length; i++) {
    		if(id === spawnpoints[i].id) {
    			pirate.pos = {x: spawnpoints[i].pos.x, y: spawnpoints[i].pos.y};
    			
    			if(ig.game.debug)
					console.log("Pirate " + pirate_id + " spawned at spawn point " + id);
    		}
    	}
    	this.snd_angry.play();

	    pirate.hp = 3;
    },

    setPirateDiggingChest: function(index, pirate_id) {

    },

    setPirateDigginUpChest: function(index, pirate_id) {

    },

    setPirateCarryingChest: function(index, pirate_id) {

    },

    setPirateDropChest: function(index, pirate_id) {
    	ig.game.getPirate(pirate_id).resetWalkSpeed();
    },

    setPirateWalkState: function(pirate_id, state, x, y) {
    	ig.game.getPirate(pirate_id).idle(state, x, y);
    },

    setPirateHit: function(pirate_id, angle) {
    	var pirate = ig.game.getPirate(pirate_id);
    	pirate.setAngle(angle);
    	pirate.hit(angle);

    	// Notify clients.
		if(ig.game.host) {
			if(ig.game.is_connected) {
				ig.game.gamesocket.send(
					'broadcast',
					{
						t: "hit",
						id: pirate.id,
						angle:pirate.angle,
	        			key: ig.game.roomid
					}
				);
			}

			var hitposx = pirate.pos.x + (pirate.size.x/2) + (Math.sin( pirate.angle ) * 64);
			var hitposy = pirate.pos.y + (pirate.size.y/2) - (Math.cos( pirate.angle ) * 64);

	    	for(var i = 0; i < ig.game.pirates.length; i++) {
				if(ig.game.pirates[i].id === pirate.id) {

				} else if(ig.game.pirates[i].touchesXY(hitposx, hitposy)) {							
					// Notice other clients.
					ig.game.setPirateGotHit(ig.game.pirates[i].id, pirate.id);
				}
			}
		}

		ig.game.sword.play();

    	if(ig.game.debug)
			console.log("Pirate " + pirate_id + " should now play a hit animation.");
    },

    setPirateGotHit: function(pirate_id, other_id) {
    	var pirate = ig.game.getPirate(pirate_id);
    	pirate.hp--;
    	if(pirate.hp === 0) {
    		pirate.score -= 5;
    	}

    	ig.game.getPirate(other_id).score += 10;

    	// Play damage animation.
    	pirate.damage();

    	if(ig.game.debug) {
			console.log("Pirate "  + pirate_id + " got hit by " + other_id + " and now has " + pirate.hp + " hp left.");
		}

		if(ig.game.host) {

			// Notify clients.
			ig.game.gamesocket.send(
				'broadcast',
				{
					t:"dmg",
					other_id: ig.game.getPirate(other_id).id,
					id: pirate.id,
					key: ig.game.roomid
				}
			);

			if(pirate.hp === 0) {

				// Get list of respawn points. Spawn at location farthest away from a pirate location.
				var spawnpoints = ig.game.getEntitiesByType(EntitySpawnpoint);
				var max_dist = 0;
				var spawnpoint_id = -1;
				for(var s = 0; s < spawnpoints.length; s++) {
				 	for(var t = 0; t < ig.game.pirates.length; t++) {
				 		var dist = spawnpoints[s].pos.x - ig.game.pirates[t].pos.x;
				 		if(dist < 0) dist *=-1;

				 		var dist2 = spawnpoints[s].pos.y - ig.game.pirates[t].pos.y;
				 		if(dist2 < 0) dist2 *=-1;

				 		if((dist + dist2) > max_dist) {
				 			max_dist = dist + dist2;
				 			spawnpoint_id = s;
				 		}
				 	}
				}

				if(spawnpoint_id !== -1) {
					ig.game.respawnPirate(pirate.id, spawnpoint_id);

					// Notify clients.
					ig.game.gamesocket.send(
						'broadcast',
						{
							t:"respawn",
							id: pirate.id,
							spawnpoint_id: spawnpoint_id,
	            			key: ig.game.roomid
						}
					)
				}
			}
		}
    },

    spawnCoin: function(id) {
    	var spawncoins = ig.game.getEntitiesByType(EntitySpawncoins) 

    	for(var i = 0; i < spawncoins.length; i++) {
    		if(id === spawncoins[i].id) {
    			spawncoins[i].spawnCoin();
    		}
    	}
    },

    spawnPotion: function(id) {
    	var spawncoins = ig.game.getEntitiesByType(EntitySpawncoins) 

    	for(var i = 0; i < spawncoins.length; i++) {
    		if(id === spawncoins[i].id) {
    			spawncoins[i].spawnPotion();
    		}
    	}
    },

	addPlayerPirate: function(player_id, id) {
		var pirate = ig.game.spawnEntity(EntityPirate, 0, 0, {id:player_id});

		var spawnpoints = ig.game.getEntitiesByType(EntitySpawnpoint);

    	for(var i = 0; i < spawnpoints.length; i++) {
    		if(id === spawnpoints[i].id) {
    			pirate.pos = {x: spawnpoints[i].pos.x, y: spawnpoints[i].pos.y};
    		}
    	}

		ig.game.player = pirate; // Add reference to current host/client player pirate.
		ig.game.pirates.push(pirate);

		if(ig.game.debug) {
			console.log("Player pirate with id " + pirate.id + " spawned.")
		}
	},

	addOtherPirate: function(player_id, id) {
		var pirate = ig.game.spawnEntity(EntityPirate, 0, 0, {id:player_id});
		var spawnpoints = ig.game.getEntitiesByType(EntitySpawnpoint);

    	for(var i = 0; i < spawnpoints.length; i++) {
    		if(id === spawnpoints[i].id) {
    			pirate.pos = {x: spawnpoints[i].pos.x, y: spawnpoints[i].pos.y};
    		}
    	}

		ig.game.pirates.push(pirate);

		if(ig.game.debug) {
			console.log("A new remote player with id " + pirate.id + " was added to the room.")
		}
	},

	removePirate: function(id) {
		var pirate = ig.game.getPirate(id);

		ig.game.removePirateFromList(id);

		pirate.kill();
	},

	removePirateFromList: function(id) {
        for(var i = 0; i < pirates.length; i++) {
            if(ig.game.pirates[i].id === id){
                ig.game.pirates(i, 1);
            }
        }
	},

	getPirates: function() {
		return ig.game.getEntitiesByType(EntityPirate);
	},

	getPirate: function(id) {
        for(var i = 0; i < ig.game.pirates.length; i++){
            if(ig.game.pirates[i].id === id){
                return ig.game.pirates[i];
            }
        }

        return null;
	},

    cameraMovement: function() {
        var player = ig.game.player;
        if(player && ig.game.cameraTimer.delta() > 0) {
            var screenX = player.pos.x - ig.system.width / 2 ;
            var screenY = player.pos.y - ig.system.height * 0.5; 

            if(screenX < 0 || screenX > ((ig.game.collisionMap.width * ig.game.collisionMap.tilesize ) - (ig.game.collisionMap.tilesize ))){
            } else {
                //this.screen.x = screenX;
                TweenMax.to(ig.game.screen, 0.5, {x: screenX});
            }

            if (screenY < 0 || screenY > ((ig.game.collisionMap.height * ig.game.collisionMap.tilesize ))){
            } else {
            //this.screen.y = screenY;
                TweenMax.to(ig.game.screen, 0.5, {y: screenY});
            }
            ig.game.cameraTimer.reset();
        }
    },

    createGame: function() {
    	ig.game.host = true;

    	ig.game.btn_next2.kill();
    	ig.game.btn_next2 = null;

    	ig.game.btn_next1.kill();
    	ig.game.btn_next1 = new EntityButtonnext(650, 512, {id:2});

    	ig.game.state = 1;

		ig.game.gamesocket.send(
			'createGame',
			{

			}
		);

		if(ig.game.debug)
			console.log("Created game room.")
    },

    joinGame: function() {
		ig.game.host = false;

    	ig.game.state = 2;

    	ig.game.btn_next2.kill();
    	ig.game.btn_next2 = null;

    	ig.game.btn_next1.kill();
    	ig.game.btn_next1 = new EntityButtonnext(500, 510, {id:3});

        ig.game.inputb = ig.game.input_box.createInputBox( 
            ig.game.screen.x + 350, 
            550, // Position below chat bar background image.
            90,
            ig.game.max_txt,
            16,
            'verdana'
        );

        ig.game.inputb.style.backgroundColor = "#e6ddd4";
        ig.game.inputb.style.borderColor = "#e6ddd4";
        ig.game.inputb.style.outlineColor = "#FFFFFF";
    },

    joinedGame: function() {
    	ig.game.state = 3;

    	if(ig.game.debug)
    		console.log("Joining game.");

    	ig.game.roomid = ig.game.inputb.value;

    	if(ig.game.input_box !== null && ig.game.inputb !== null) {
    		ig.game.input_box.removeElement(ig.game.inputb);
    		ig.game.inputb = null;
    	}

    	if(ig.game.btn_next1 !== null) {
    		ig.game.btn_next1.kill();
    		ig.game.btn_next1 = null;
    	}
    },

    startGame: function() {
		ig.game.btn_next1.kill();
		ig.game.btn_next1 = null;

		ig.game.state = 10;

		ig.game.on_island = true;

		ig.game.gamesocket.send('broadcast', { 
			t:"start",
			key: ig.game.roomid
		});

		ig.game.loadLevel(LevelIsland);

		ig.game.addPlayerPirate(ig.game.my_id, 0);

        // Notify clients.
        ig.game.gamesocket.send(
            'spawn',
            {
                id: ig.game.player.id,
                spawnpoint_id: 0,
                key: ig.game.roomid
            }
        );
        
    	for(var i = 0; i < ig.game.others.length; i++) {
            // Notify clients.
            ig.game.gamesocket.send(
                'spawn',
                {
                    id: ig.game.others[i],
                    spawnpoint_id: i+1,
                	key: ig.game.roomid
                }
            );

            ig.game.addOtherPirate(ig.game.others[i], i+1);

            if(ig.game.debug)
            	console.log("Attempting to spawn " + ig.game.others[i] + " at spawn location " + i+1 + ".");
    	}

    	console.log("Has started game.")
    },

    draw: function() {
    	this.parent();
    	/*ig.game(!ig.game.is_connected) {
			ig.game.font.draw(
    			"Wait for connection ..."
    			+ "If nothing happens, the server might be down.\n",
    			512, 500, ig.Font.ALIGN.CENTER
    		);
    	} else {*/
	    	// Menu.
	    	if(ig.game.state === 0
	    		||ig.game.state === 1
	    		||ig.game.state === 2
	    		|| ig.game.state === 3) {
	    		this.startscreen.draw(0, 0);
	    	}

	    	if(ig.game.state === 0) {
	    		ig.game.font.draw(
	    			"Create game",
	    			ig.system.width/2, (ig.system.height * 0.5) + 200, ig.Font.ALIGN.CENTER
	    		);

	    		ig.game.font.draw(
	    			"Join game",
	    			ig.system.width/2, (ig.system.height * 0.5) + 256, ig.Font.ALIGN.CENTER
	    		);
	    	}

	    	// Create game.
	    	else if(ig.game.state === 1) {
	    		ig.game.font.draw(
	    			"Room id: " + ig.game.roomid,
	    			400, 390, ig.Font.ALIGN.CENTER
	    		);

	    	ig.game.font.draw(
	    			"There are currently " + (ig.game.others.length+1) + "/8 players in this session",
	    			ig.system.width/2, (ig.system.height * 0.5) + 256, ig.Font.ALIGN.CENTER
	    		);

	    		ig.game.font.draw(
	    			"Start game",
	    			670, 490, ig.Font.ALIGN.CENTER
	    		);
	    	}

	    	// Join game.
	    	else if(ig.game.state === 2) {
	    		ig.game.font.draw(
	    			"Write ID of hosted game",
	    			ig.system.width/2, (ig.system.height * 0.5) + 216, ig.Font.ALIGN.CENTER
	    		);

	    		if(ig.game.failedtojoin) {
	    			ig.game.font.draw(
	    			"Failed to join. Try again.",
	    			ig.system.width/2, (ig.system.height * 0.5) + 200, ig.Font.ALIGN.CENTER
	    			);
	    		}
	    	}

	    	// Joined game.
	    	else if(ig.game.state === 3) {
	    		ig.game.font.draw(
	    			"Wait for host to start game ...",
	    			ig.system.width/2, (ig.system.height * 0.5) + 202, ig.Font.ALIGN.CENTER
	    		);

	    		ig.game.font.draw(
	    			"There are currently " + (ig.game.others.length+1) + " players in this session",
	    			ig.system.width/2, (ig.system.height * 0.5) + 270, ig.Font.ALIGN.CENTER
	    		);
	    	} else if(ig.game.state === 199) {
	    		// Game over.
	    		var max_score = 0;
	    		for(var i = 0; i < ig.game.pirates.length; i++) {
	    			if(ig.game.pirates[i].score > max_score)
	    				max_score = ig.game.pirates[i].score;
	    		}

	    		ig.game.endscreen.draw(200, (ig.system.height * 0.4));

	    		ig.game.font.draw(
	    			"Biggest treasure was " + max_score,
	    			ig.system.width/2, (ig.system.height * 0.5) - 32, ig.Font.ALIGN.CENTER
	    		);

	    		ig.game.font.draw(
	    			"You collected  " + ig.game.player.score,
	    			ig.system.width/2, (ig.system.height * 0.5) + 32, ig.Font.ALIGN.CENTER
	    		);
	    	}

	    	else {
	    		if(ig.game.have_showel) {
	    			ig.game.showel_img.draw(8, 550);
	    		}

	    		// Draw scores:
	    		var scores = "Score: " + ig.game.player.score;

	    		ig.game.font2.draw(
	    			scores,
	    			16, 16, ig.Font.ALIGN.LEFT
	    		);

	    		ig.game.font2.draw(
	    			"Time left: " + this.time,
	    			16, 38, ig.Font.ALIGN.LEFT
	    		);
	    	}

	    	if(ig.game.btn_next1 !== null) ig.game.btn_next1.draw();
	    	if(ig.game.btn_next2 !== null) ig.game.btn_next2.draw();
    	//}
    }

});


// Start the Game with 60fps, a resolution of 320x240, scaled
// up by a factor of 2
ig.main( '#canvas', MyGame, 60, 800, 600, 1 );

});
