
var width = window.innerWidth;
var height = window.innerHeight;
var PI=Math.PI;
var absoluteBaseSpeed=200;
var baseSpeed=absoluteBaseSpeed;
console.log(width,height);
var tqwidth = (width*0.75)|0
var tqwbase = (((width-tqwidth)/2))
var opponentcount=60;
var opponentpause=10;
var opponentspeedfactor=0.75;
var fatdownloadsize=130;
var score=0;
var fatscore=0;
var fwscore=0;
var fatrisk=false;
var stext;
var fstext;
var fwtext;
var fdcs=15;
var shightext;
var fhightext;
var fwhightext;
var game = new Phaser.Game(width, height, Phaser.CANVAS, 'gameContainer', { preload: preload, create: create, update: update, render: render });

function preload() {
    game.load.image('player', 'player.png');
    game.load.image('opponent', 'opponent.png');
    game.load.image('opponentb', 'opponentb.png');
    game.load.image('opponent2', 'opponent2.png');
    game.load.image('opponent2b', 'opponent2b.png');
    game.load.image('background', 'background.png');
    game.load.image('firewall', 'firewall.png');
}

var player;
var pad;
var opponents=[];
var fatdownload=[];
var firewall=[];
var bg;
function create() {

    game.physics.startSystem(Phaser.Physics.ARCADE);

    game.stage.backgroundColor = '#000000';
	
	//calc 3/4 width;
	
	console.log("TQWBase",tqwbase);
    bg = game.add.tileSprite(tqwbase, 0, tqwidth, height, 'background');
	
    //bg.fixedToCamera = true;

	player = game.add.sprite((width/2)-16,height-200,'player')
	this.game.physics.enable(player, Phaser.Physics.ARCADE);
	//player.body.drag.set(0.2);
	player.body.setSize(player.width,player.height/2,0,player.height/4);
	//player.body.maxVelocity.setTo(400, 400);
	player.body.collideWorldBounds = true;
	game.input.gamepad.start();
	initOpponents();
	
					//falls pad nicht funktioniert mittels GamepadDebug sample schauen welches pad das aktive ist und entsprechend umcoden
    pad = game.input.gamepad.pad1;
	pad.addCallbacks(this, { onConnect: addButtons });
	stext = game.add.text(10, 40, "Packets:0",{
        font: "30px arial",
        fill: "#ff0044",
        align: "center"
    });
	fstext = game.add.text(10, 80, "Long downloads:0",{
        font: "30px arial",
        fill: "#ff0044",
        align: "center"
    });
	fwtext = game.add.text(10, 120, "Firewalls:0",{
        font: "30px arial",
        fill: "#ff0044",
        align: "center"
    });
	
	game.add.text(10, height-160, "Highscore:",{
        font: "30px arial",
        fill: "#ff0044",
        align: "center"
    });

	shightext=game.add.text(10, height-120, "No Highscore saved",{
        font: "30px arial",
        fill: "#ff0044",
        align: "center"
    });
	fhightext=game.add.text(10, height-80, "No Highscore saved",{
        font: "30px arial",
        fill: "#ff0044",
        align: "center"
    });
	fwhightext=game.add.text(10, height-40, "No Highscore saved:",{
        font: "30px arial",
        fill: "#ff0044",
        align: "center"
    });
	updateHighscore();
}

function initOpponents()
{
	for(var oc=0;oc<opponentcount;oc++)
	{//preseed of opponent cache
		var bx=game.rnd.between(0,3)>1;
		var flubberflargh = game.add.sprite(0,-100,(bx?'opponent':'opponentb'));
		this.game.physics.enable(flubberflargh, Phaser.Physics.ARCADE);
		flubberflargh.body.drag.set(0.2);
		//flubberflargh.body.maxVelocity.setTo(400, 400);
		flubberflargh.body.setSize(flubberflargh.width-4,flubberflargh.height-4-(bx?8:0),2,2+(bx?4:0));
		opponents[oc]=flubberflargh;
	}
	for(var fc=0;fc<fatdownloadsize;fc++)
	{//preseed of fatdl cache
		var b=game.rnd.between(0,4)>1;
		var blubberlutsch = game.add.sprite(0,-100-(fdcs*fc),(b?'opponent2':'opponent2b'));
		this.game.physics.enable(blubberlutsch, Phaser.Physics.ARCADE);
		blubberlutsch.body.drag.set(0.2);
		//blubberlutsch.body.maxVelocity.setTo(400, 400);
		blubberlutsch.body.setSize(blubberlutsch.width-4,blubberlutsch.height,2,0);
		fatdownload[fc]=blubberlutsch;
		
	}
	for(var fwc=0;fwc<3;fwc++)
	{//preseed of fatdl cache
		//var b=game.rnd.between(0,4)>1;
		var blubberlutsch = game.add.sprite(0,-500,'firewall');
		this.game.physics.enable(blubberlutsch, Phaser.Physics.ARCADE);
		blubberlutsch.body.drag.set(0.2);
		//blubberlutsch.body.maxVelocity.setTo(400, 400);
		blubberlutsch.scale.y=0.25;
		//hässlicher hack wegen verschieberitis
		blubberlutsch.body.immovable=true;
		
		firewall[fwc]=blubberlutsch;
	}
}

function addButtons() {

    //  We can't do this until we know that the gamepad has been connected and is started

    buttonA = pad.getButton(Phaser.Gamepad.XBOX360_A);
    buttonB = pad.getButton(Phaser.Gamepad.XBOX360_B);
    buttonX = pad.getButton(Phaser.Gamepad.XBOX360_X);
    buttonY = pad.getButton(Phaser.Gamepad.XBOX360_Y);

    buttonA.onDown.add(onDown, this);
    buttonB.onDown.add(onDown, this);
    buttonX.onDown.add(onDown, this);
    buttonY.onDown.add(onDown, this);

    buttonA.onUp.add(onUp, this);
    buttonB.onUp.add(onUp, this);
    buttonX.onUp.add(onUp, this);
    buttonY.onUp.add(onUp, this);

	
}
var ocb = 0;
function update() {
	
	var baseSpeed=absoluteBaseSpeed+(((score/100)|0)*50)
	bg.tilePosition.y += 10;
	
	stext.setText("Packets:"+score);
	fstext.setText("Long downloads:"+fatscore);
	fwtext.setText("Firewalls:"+fwscore);
	if(pad&&pad._rawPad)
	{
		var vx =0;
		//TODO für später, vielleicht feiner abstufen, deadzone(!!!);
		if (pad.isDown(Phaser.Gamepad.XBOX360_DPAD_LEFT) || pad.axis(Phaser.Gamepad.XBOX360_STICK_LEFT_X) < -0.1||pad.axis(Phaser.Gamepad.XBOX360_STICK_RIGHT_X) < -0.1)
		{
			var af=0;
			if(pad.isDown(Phaser.Gamepad.XBOX360_DPAD_LEFT))
			{
				af=1.0;
			}
			if(pad.axis(Phaser.Gamepad.XBOX360_STICK_LEFT_X) < -0.1)
			{
				af= -pad.axis(Phaser.Gamepad.XBOX360_STICK_LEFT_X)
			}
			if(pad.axis(Phaser.Gamepad.XBOX360_STICK_RIGHT_X) < -0.1)
			{
				af= -pad.axis(Phaser.Gamepad.XBOX360_STICK_RIGHT_X)
			}
			if(player.x>=tqwbase)
			{
				vx=-baseSpeed*af;
			}
		}
		else if (pad.isDown(Phaser.Gamepad.XBOX360_DPAD_RIGHT) || pad.axis(Phaser.Gamepad.XBOX360_STICK_LEFT_X) > 0.1||pad.axis(Phaser.Gamepad.XBOX360_STICK_RIGHT_X) > 0.1)
		{
						var af=0;
			if(pad.isDown(Phaser.Gamepad.XBOX360_DPAD_RIGHT))
			{
				af=1.0;
			}
			if(pad.axis(Phaser.Gamepad.XBOX360_STICK_LEFT_X) > 0.1)
			{
				af= pad.axis(Phaser.Gamepad.XBOX360_STICK_LEFT_X)
			}
			if(pad.axis(Phaser.Gamepad.XBOX360_STICK_RIGHT_X) > 0.1)
			{
				af= pad.axis(Phaser.Gamepad.XBOX360_STICK_RIGHT_X)
			}
			
			
			if(player.x<=(width-tqwbase-32))
			{
				vx=baseSpeed;
			}
		}
		/*
		if (pad.isDown(Phaser.Gamepad.XBOX360_DPAD_UP) || pad.axis(Phaser.Gamepad.XBOX360_STICK_LEFT_Y) < -0.1||pad.axis(Phaser.Gamepad.XBOX360_STICK_RIGHT_Y) < -0.1)
		{
			vy=-baseSpeed;
		}
		else if (pad.isDown(Phaser.Gamepad.XBOX360_DPAD_DOWN) || pad.axis(Phaser.Gamepad.XBOX360_STICK_LEFT_Y) > 0.1||pad.axis(Phaser.Gamepad.XBOX360_STICK_RIGHT_Y) >0.1)
		{
			vy=baseSpeed;
		}
		*/		
		player.body.velocity.x=vx;
		//player.body.velocity.y=vy;
	}
	for(var opcol=0;opcol<opponentcount;opcol++)
	{
		var opn = opponents[opcol];
		if(opn.y>-50&&opn.y<(height-opn.height))
		{
			opn.body.velocity.y=baseSpeed*opponentspeedfactor;
		}
		if(opn.x<tqwbase||opn.x>(width-tqwbase-opn.width))
		{
			opn.body.velocity.x=0;
		}
		if(opn.y>height)
		{
			score++;
			opn.y=-100;
		}
		game.physics.arcade.collide(player, opn, 
		gameover, 
		function(){return true}, this);
		//runterrauschenden traffic nullrouten
		var blubb = function()
		{
			opn.body.velocity.y=0;
			opn.y=-100;  //müssen hintenraus geschossen werden sonst datensalat;
		}
		
		game.physics.arcade.collide(firewall[0],opn , 
		blubb, 
		function(){return true}, this);
		game.physics.arcade.collide(firewall[1],opn , 
		blubb, 
		function(){return true}, this);
		game.physics.arcade.collide(firewall[2],opn , 
		blubb, 
		function(){return true}, this);
	}
	if(ocb%opponentpause==0)
	{
		var nxoidx = (ocb/opponentpause)|0;
		console.log(nxoidx);
		var nxo = opponents[nxoidx]
		
		if(nxo.y<-50||nxo.y>height)
		{
			
			//console.log(ocb);
			nxo.y=-30;
			nxo.x=game.rnd.between(tqwbase,tqwbase+tqwidth-nxo.width);
			console.log(nxo.x);
			nxo.body.velocity.y=baseSpeed*opponentspeedfactor;
			nxo.body.velocity.x=0;
			var fff = game.rnd.between(0,1000);
			if(fff<50)
			{
				nxo.body.velocity.x=fff-50;
			}
			if(fff>950)
			{
				nxo.body.velocity.x=fff-950;
			}
			
		}
		
		//ocb++;
	}
	ocb=(ocb+1)%(opponentcount*opponentpause);
	var firewallchance = game.rnd.between(0,100000);
	if(firewallchance>99995&&firewall[0].y<-400)
	{
		var firstport = game.rnd.between(tqwbase,tqwbase+tqwidth/2);
		var secondport = game.rnd.between(tqwbase+tqwidth/2,tqwbase+tqwidth);
		//firewall segment width = 1000
		fw0width = (firstport-tqwbase);
		firewall[0].x=tqwbase;
		firewall[0].scale.x=fw0width/1000;
		firewall[0].y=-350;
		firewall[0].body.velocity.y=50;
		firewall[0].body.setSize(1000, 60, 0, 30);
		
		fw1base = firstport+10+player.width;
		var fw1width = secondport-fw1base;
		firewall[1].x=fw1base;
		firewall[1].scale.x=(fw1width)/1000;
		firewall[1].y=-350;
		firewall[1].body.velocity.y=50;
		firewall[1].body.setSize(1000, 60, 0, 30);
		fw2base = secondport+10+player.width;
		fw2width = width-tqwbase-fw2base;
		firewall[2].x=fw2base;
		firewall[2].scale.x=fw2width/1000;
		firewall[2].y=-350;
		firewall[2].body.velocity.y=50;
		firewall[2].body.setSize(1000, 60, 0, 30);
	}
	
	if(firewall[0].y>height)
	{
		fwscore++;
		firewall[0].y=-500
		firewall[0].body.velocity.y=0;
		firewall[1].y=-500
		firewall[1].body.velocity.y=0;
		firewall[2].y=-500
		firewall[2].body.velocity.y=0;
	}
	
	var fdc = game.rnd.between(0,1000);
	if(fdc>500&&fatdownload[0].y<-50)
	{
		var fdcolumn = game.rnd.between(tqwbase,tqwbase+tqwidth-fatdownload[0].width);
		for(var fc=0;fc<fatdownloadsize;fc++)
		{
			var fds = fatdownload[fc];
			fds.x=fdcolumn
			fds.y=fds.y+70;
			fds.body.velocity.y=baseSpeed*opponentspeedfactor;
		}
	}
	else 
	{
		if(fatdownload[0].y>-50)//fatdownload transferierend
		{
			for(var fcc=0;fcc<fatdownloadsize;fcc++)
			{
				fds = fatdownload[fcc];
				fds.body.velocity.y=baseSpeed*opponentspeedfactor;
				game.physics.arcade.collide(player,fds , 
				gameover, 
				function(){return true}, this);
				
				//runterrauschenden traffic nullrouten
				var blubb = function()
				{
					fds.body.velocity.y=0;
					fds.y=height+500;  //müssen hintenraus geschossen werden sonst datensalat, und nicht gescored;
				}
				if(firewall[0].y>-300)
				{
					game.physics.arcade.collide(firewall[0],fds , 
					blubb, 
					function(){return true}, this);
					game.physics.arcade.collide(firewall[1],fds , 
					blubb, 
					function(){return true}, this);
					game.physics.arcade.collide(firewall[2],fds , 
					blubb, 
					function(){return true}, this);
				}
				
				
			}
		}
	}
	if(fatdownload[fatdownloadsize-1].y>height-200 &&!fatrisk&&fatdownload[fatdownloadsize-1].y<height-170)
	{
		var fx = fatdownload[fatdownloadsize-1].x
		if(fx<=(tqwbase+(tqwidth*0.2)|0)&&player.x<fx)
		{
			fatrisk=true;
			fatscore+=9;
		}
		else
		{
			if(fx>=(width-tqwbase-(tqwidth*0.2)|0)&&player.x>fx)
			{
				fatrisk=true;
				fatscore+=9;
			}
		}
	}
	if(fatdownload[fatdownloadsize-1].y>height)
	{
		if(fatdownload[fatdownloadsize-1].y<height+200)
		{
			fatscore++;
		}
		fatrisk=false;
		for(var fc=0;fc<fatdownloadsize;fc++)
		{
			var fds = fatdownload[fc];
			fds.x=0
			fds.y=-100-(fdcs*fc);
			fds.body.velocity.y=0;
		}
	}
	game.physics.arcade.collide(firewall[0],player , 
	gameoverFW, 
	function(){return true}, this);
	game.physics.arcade.collide(firewall[1],player , 
	gameoverFW, 
	function(){return true}, this);
	game.physics.arcade.collide(firewall[2],player , 
	gameoverFW, 
	function(){return true}, this);
}

function writeScore(scorekey,value)
{
	 if(localStorage.getItem(scorekey) === null)
	 {

		localStorage.setItem(scorekey,value);

	}

	else if(value > localStorage.getItem(scorekey))
	{

		localStorage.setItem(scorekey,value);
	}
}
function updateHighscore()
{
	updateHighscoreInternal('packets',shightext,'Packets:');
	updateHighscoreInternal('fatdownloasds',fhightext,'Long downloads:');
	updateHighscoreInternal('firewalls',fwhightext,'Firewalls:');
}
function updateHighscoreInternal(scorekey,scoretext,scorelabel)
{
	var value =localStorage.getItem(scorekey)
	if(value  != null)
	{
		scoretext.setText(scorelabel+value);
	}
}
function gameoverpre()
{
	writeScore('packets',score);
	writeScore('fatdownloasds',fatscore);
	writeScore('firewalls',fwscore);
	updateHighscore()
	
	score=0;
	fatscore=0;
	fwscore=0;
	for(var p=0;p<opponentcount;p++)
	{
		var o = opponents[p];
		o.exists=false;
		opponents[p]=null;
	};
	for(var q=0;q<fatdownloadsize;q++)
	{
		var r = fatdownload[q];
		r.exists=false;
		fatdownload[q]=null;
	}
	for(var q=0;q<3;q++)
	{
		var r = firewall[q];
		r.exists=false;
		firewall[q]=null;
	}
}

function gameoverpost()
{
	initOpponents();
	player.y=height-200;
	player.body.velocity.y=0;
}

function gameover()
{
	gameoverpre();
	console.log("Ätschebätsche");
	alert("Packet Loss");
	gameoverpost();
}
function gameoverFW()
{
	gameoverpre();
	console.log("Ätschebätsche");
	alert("Filtered by a firewall");
	gameoverpost();
}
function onDown(button, value) {
	/*
    if (button.buttonCode === Phaser.Gamepad.XBOX360_A)
    {
       //TODO
    }
    else if (button.buttonCode === Phaser.Gamepad.XBOX360_B)
    {
    }*/

}
function onUp(button, value) {

	/*
    if (button.buttonCode === Phaser.Gamepad.XBOX360_A)
    {
       //TODO
    }
    else if (button.buttonCode === Phaser.Gamepad.XBOX360_B)
    {
       
    }*/
}


function render () {

	//game.debug.body(firewall[0]);
	//game.debug.body(firewall[1]);
	//game.debug.body(firewall[2]);
    // game.debug.text(game.time.physicsElapsed, 32, 32);
    //game.debug.body(player);
    // game.debug.bodyInfo(player, 16, 24);

}