$(document).ready(function() {
	var myAudio = document.getElementById("polka");
	var myAudioShot = document.getElementById("shot");
	var myAudioQuack = document.getElementById("quack");
	

	var started = false;
	var backgroundWidth = 900;
	var birdWidth = 64;
	var birdArray = [];
	var tBirdArray = [];
	var noOfBirds = 5;//Anzahl der Vögel
	var noOfTBirds = 1;
	var tickCount = 0;
	

	var pulseGame = null;//Timer drawCanvas() zeichnen
	var time;//Spielzeit-Startwert
	var timepassed = 0;//Spielzeit-Gesamt

	var points = 0;//Punktestand
	var counter = 0;//Vogelbewegung
	var tBirdExists = false; //Check, ob bereits Time Bird existiert
	var sBirdExists = false; //Check, ob bereits ein Storch existiert
	var sort = localStorage.scores;
	var scores = [];
	var name;

	/******************    BIRD TYPES    *********************/
	/*
	    0 = Default Bird
		1 = Time Bird
		2 = Stork Bird
	*/
	/*********************************************************/


	$('#gameContainer').hide();
	$('#resultScreen').hide();
	$('#highscoreScreen').hide();
	
	$('#startbutton').click(start);
	$('#restart').click(reload);
	$('#goToHighscore').click(showHighscore);




	function reload(){
		window.location.reload()
	}

	function shoot(sound) {
		sound.play();
	}
	
	function start() {

		$('#gameContainer').show();
		
		$('#start').hide();
		$('#resultScreen').hide();
		$('#highscoreScreen').hide();

		$('#stats').show();
	
		
		time = 30;//Hier wird der Spielzeit-Startwert festgelegt
		points = 0;

		for(var i = 0; i < noOfBirds; i++)
			birdArray.push(new Bird(0));

		$('#gameContainer').click(function() {
				shoot(myAudioShot);
			
		});

		if (!started) { 
			pulseGame = setInterval(update, 20);
			started = true;

			showPoints();
			showTime();
		} else { 
			clearInterval(pulseGame);
		}
		//Timer Ende - weiter bei endgame()
	}

	function showPoints() {
		$('#showPoints').html(points);
	}

	function showTime() {
		$('#remTime').text(time);
	}

	function update() {
		tickCount++;

		if(tickCount === 50) {
			tickCount = 0;

			if(time <= 1)
				endgame();

			time--;
			timepassed++;
			showTime();
		}

		if (time % 20 === 0 && !tBirdExists) {
			birdArray.push(new Bird(1));
		}

		if (time % 10 === 0 && !sBirdExists) {
			birdArray.push(new Bird(2));
		}

		for (var i = birdArray.length; i--; ) {
			var vogel = birdArray[i];
			var offset = vogel.birdY;

			if (vogel.canBeRemoved) {
				vogel.remove();
				birdArray.splice(i, 1);
				continue;
			} else if (vogel.birdX >= (backgroundWidth - birdWidth) || vogel.birdX < 0) {
				if (vogel.dead) {
					vogel.ondead();
				} else {
					var img = vogel.birdX < 0 ? "url('img/bird.gif')" : "url('img/birdRev.gif')";
					vogel.speed = -vogel.speed;
					vogel.image.css('background-image', img);
				}
			}


			vogel.image.css('margin-left', vogel.birdX + "px");

			if (points > 10) {
				vogel.image.css('margin-top',vogel.birdY + "px");
				vogel.birdX += vogel.speed;
				vogel.birdY = vogel.constY + Math.sin(vogel.constY + counter) * (points)*0.3;
				counter+=0.02;
			} else {
				vogel.image.css('margin-left',vogel.birdX+"px");
				vogel.birdX += vogel.speed;
			}
		}
	}

	function Bird(birdType) {
		var img;
		var self = this;
		this.birdType = birdType;
		this.canBeRemoved = false;
		this.ondead = function() {
			this.canBeRemoved = true;
		};

		switch(birdType) {
			//Default Bird
			case 0:
				var r = Math.random();
				img = 'bird.gif';

				//Vogel Startgeschwindigkeit		
				if (points > 15 && points < 30)
					this.speed = r * 3 + 3;
				else if (points > 30)
					this.speed = r * 3 + 5;
				else
					this.speed = r * 3 + 1;

				//Vogel Startposition
				this.birdY =  Math.random() * 400;

				if(Math.random() > 0.5)
					this.birdX = 0;
				else
					this.birdX = backgroundWidth - birdWidth;
				
				this.dead = false;
				this.onclick = function() {
					points++;
				};
				this.remove = function() {
					this.image.remove();
					birdArray.push(new Bird(0));
				};
				break;

			//Time Bird
			case 1:
				img = 'tbird.gif';
				tBirdExists = true;
				this.speed = 7;
				this.birdX = 0;
				this.birdY =  Math.random() * 400;
				this.dead = true;
				this.onclick = function() {
					time = time + 15;
					
				};
				this.remove = function() {
					this.image.remove();
					tBirdExists = false;
				};
				break;

			//Storck Bird
			case 2:
				img = 'sbirdRev.gif';
				sBirdExists = true;
				this.speed = -3;
				this.birdX = backgroundWidth - birdWidth - 2;
				this.birdY =  Math.random() * 400;
				this.dead = true;
				this.onclick = function() {
					points -= 5;
					
				};
				this.remove = function() {
					this.image.remove();
					sBirdExists = false;
				};
				break;
		}		

		this.constY = this.birdY;
	
		//Vogel wird erstellt
		this.image = $('<button/>')
			.addClass('mybird')
			.css({
				'background-image': "url('img/" + img + "')",
				'z-Index': 1,
				'margin-top' : this.birdY,
				'margin-left': this.birdX
			})
			.one('click', function(ev) {
					shoot(myAudioQuack);
					self.dead = true;
					self.image.css({'border-radius': 0,'width':'149px','height':'108px','transform': 'translate(-64px,-64px)','z-Index':0});
					self.image.css('background-image',"url('img/explosion.gif')");
					setTimeout(function() {
						self.ondead();
					}, 1000);
					self.onclick();
					showPoints();

					ev.preventDefault();
					
			})
			.appendTo('#birdContainer');
	}

	// Musik an/aus Button
	$('#play_pause').click(function () {  		
  		if (myAudio.paused)
    		myAudio.play();
  		else
    		myAudio.pause();
	});

	// Geräusche an/aus Button
	$('#sound').click(function () {
    	myAudioShot.muted = !myAudioShot.muted;
    	myAudioQuack.muted = !myAudioQuack.muted;
	});

	//Endgame wenn Timer abgelaufen
	function endgame(){
		$('#gameContainer').hide();
		$('#stats').hide();
		$('#start').hide();
		$('#resultScreen').show();
		$('#highscoreScreen').hide();
		clearInterval(pulseGame);
		pulseGame = null;
		noOfBirds -= 1;
			birdArray = [];
			noOfBirds++;
			$('#birdContainer').empty();
			started = false;
			$('#endPoints').html(Math.round(points));
		

	}
	function showHighscore(){
		$('#gameContainer').hide();
		$('#stats').hide();
		$('#start').hide();
		$('#resultScreen').hide();
		$('#highscoreScreen').show();

		var name = $('#name').val();

		if(localStorage.scores){
			localStorage.scores+=","+points+" "+name;
		}
		else{
			localStorage.scores = points+" "+name;
		}
		
		sort=localStorage.scores;
		if(sort){
			scores = sort.split(",");
			scores.sort();
		}
		for(var i = 0; i<scores.length; i++){
			$('#highscore').html(
				(1)+": " +scores[i]+ "<br>" +
				(2)+": " +scores[i-1]+"<br>" +
				(3)+": " +scores[i-2] );
		}
	}	
});

