/*
* Copyright (c) 2011 Affenzeller Peter, Freihofner Katrin, Friedl Fabian, Kostolnik Dominik (www.gaming-center.net)
*/

//Global constants:
var PLAYGROUND_WIDTH 	= 800;
var PLAYGROUND_HEIGHT 	= 450;
var PLAYER_WIDTH 		= 80;
var PLAYER_HEIGHT 		= 88;
var BOTTOM_LINE			= 48;
var NR_FG_IMAGES		= 9;
var NR_BG_IMAGES		= 9;
var START_POSITION 		= PLAYGROUND_HEIGHT - BOTTOM_LINE - PLAYER_HEIGHT;
var REFRESH_RATE 		= 40;
var POWERUP_REFRESH 	= 15000;
var MIN_OBSTACLE_DISTANCE = 200; //minimalstabstand: 70

var offset = [-40, 150, 80, -10, 190, 0, -70, 120, -30, 100, -50, 170, -20, 160, 90];
var offsetLength = 15;

//obstacles constants:
var HORIZONTAL_SHORT_WIDTH = 250;
var HORIZONTAL_LONG_WIDTH = 450;
var HORIZONTAL_HEIGHT = 70;

var gameStart = false;
var gameOver = false;
var muted = false;
var jump = false; 				//hilfsvariable um abzufragen, ob die Leertaste gedrÃ¼ckt ist, oder nicht!
var numberOfJumps = 0;
var inTheAir = false; 			//hilfsvariable: ist der player in der Luft oder nicht
var currentPos = START_POSITION;
var movingUp = false; 			//ueberprueft ob der player in der aufwaertsbewegung ist oder nicht

var counter = 0;

var background_far_move = 2;
var background_close_move = 4; 		//pixels per frame
var sky_move = 4;
var sky_fast = 5;
var foreground_move = 5;
var difficulty = 1;
var levelUp = true;

//power-up times and booleans
var powerup = false;
var moonwalkTime = 8550; //dient zur definierung der dauer des powerUps 
var moonwalk = false; //gibt an, ob das powerUp aktiv ist oder nicht
var marleyTime = 6300;
var marley = false;
var powerupStartTime;

var bg = "green";
var minObstacleDistance = 200;

$(function() {
	/*---------------------		  
		welcomeScreen
	-----------------------*/
	//initialize the start button
	$("#welcomeScreen").css("cursor","pointer");
	$("#welcomeScreen").hover(function() {
		$(this).css("opacity",1);			 
	},function() {
		$(this).css("opacity",0.8);
	});
	
	// this sets the id of the loading bar:
	$().setLoadBar("loadingBar", 400);
	
	$("#welcomeScreen").click(function() {
		$.playground().startGame(function() {
			gameStart = true;
			$("#welcomeScreen").fadeTo(500, 0, function() { $(this).remove(); });
		});
	});
    $("#submitScoreForm").hide();
	
	
	
	/*---------------------
		PLAYGROUND
	-----------------------*/
	
	//spielfeld erstellen, hierarchie der groups festlegen
	$("#playground").playground({height: PLAYGROUND_HEIGHT, width: PLAYGROUND_WIDTH, keyTracker: true})
		.addGroup("background_far", {width: PLAYGROUND_WIDTH, height: PLAYGROUND_HEIGHT}).end()
		.addGroup("background_close", {width: PLAYGROUND_WIDTH, height: PLAYGROUND_HEIGHT}).end()
		.addGroup("foreground", {width: PLAYGROUND_WIDTH, height: PLAYGROUND_HEIGHT}).end()
		.addGroup("playerAnimations", {width: PLAYGROUND_WIDTH, height: PLAYGROUND_HEIGHT}).end()
		.addGroup("obstacles", {width: PLAYGROUND_WIDTH, height: PLAYGROUND_HEIGHT}).end()
		.addGroup("powerUps", {width: PLAYGROUND_WIDTH, height: PLAYGROUND_HEIGHT}).end()
		.addGroup("light", {width: PLAYGROUND_WIDTH, height: PLAYGROUND_HEIGHT}).end()
		.addGroup("counter", {width: PLAYGROUND_WIDTH - 215, height: 20, posx: 200, posy: 10}).end()
		.addGroup("muteButton", {width: 20, height: 20, posx: 100, posy: 10}).end()
		.addGroup("restart", {width: 80, height: 20, posx: 15, posy: 10}).end()
		.addGroup("pause", {width: 80, height: 20, posx: 130, posy: 10});
	
	/*---------------------		  
		BACKGROUND
	-----------------------*/
	//bg-far-variablen
	var bg_green = new $.gameQuery.Animation({imageURL: "pics/level/bg/bg_green.png"});
	var bg_green_yellow = new $.gameQuery.Animation({imageURL: "pics/level/bg/bg_green_yellow.png"});
	var bg_yellow = new $.gameQuery.Animation({imageURL: "pics/level/bg/bg_yellow.png"});
	var bg_yellow_red = new $.gameQuery.Animation({imageURL: "pics/level/bg/bg_yellow_red.png"});
	var bg_red = new $.gameQuery.Animation({imageURL: "pics/level/bg/bg_red.png"});
	var bg_red_green = new $.gameQuery.Animation({imageURL: "pics/level/bg/bg_red_green.png"});
	var game_over = new $.gameQuery.Animation({imageURL: "pics/level/game_over.png"});
	
	$("#background_far").addSprite("bg_green", {animation: bg_green, width: PLAYGROUND_WIDTH, height: PLAYGROUND_HEIGHT})
		.addSprite("bg_green_yellow", {animation: bg_green_yellow, width: PLAYGROUND_WIDTH, height: PLAYGROUND_HEIGHT, posx: PLAYGROUND_WIDTH})
		.addSprite("bg_yellow", {animation: bg_yellow, width: PLAYGROUND_WIDTH, height: PLAYGROUND_HEIGHT, posx: 1.5 * PLAYGROUND_WIDTH})
		.addSprite("bg_yellow_red", {animation: bg_yellow_red, width: PLAYGROUND_WIDTH, height: PLAYGROUND_HEIGHT, posx: 2.5 * PLAYGROUND_WIDTH})
		.addSprite("bg_red", {animation: bg_red, width: PLAYGROUND_WIDTH, height: PLAYGROUND_HEIGHT, posx: 3 * PLAYGROUND_WIDTH})
		.addSprite("bg_red_green", {animation: bg_red_green, width: PLAYGROUND_WIDTH, height: PLAYGROUND_HEIGHT, posx: 4 * PLAYGROUND_WIDTH});
	
	//bg-close-variablen
	var green1 = new $.gameQuery.Animation({imageURL: "pics/level/fg/fg_green1.png"});
	var green2 = new $.gameQuery.Animation({imageURL: "pics/level/fg/fg_green2.png"});
	var green_yellow = new $.gameQuery.Animation({imageURL: "pics/level/fg/fg_green_yellow.png"});
	var yellow1 = new $.gameQuery.Animation({imageURL: "pics/level/fg/fg_yellow1.png"});
	var yellow2 = new $.gameQuery.Animation({imageURL: "pics/level/fg/fg_yellow2.png"});
	var yellow_red = new $.gameQuery.Animation({imageURL: "pics/level/fg/fg_yellow_red.png"});
	var red1 = new $.gameQuery.Animation({imageURL: "pics/level/fg/fg_red1.png"});
	var red2 = new $.gameQuery.Animation({imageURL: "pics/level/fg/fg_red2.png"});
	var red_green = new $.gameQuery.Animation({imageURL: "pics/level/fg/fg_red_green.png"});
	
	$("#background_close").addSprite("green1", {animation: green1, width: PLAYGROUND_WIDTH, height: PLAYGROUND_HEIGHT})
		.addSprite("green2", {animation: green2, width: PLAYGROUND_WIDTH, height: PLAYGROUND_HEIGHT, posx: PLAYGROUND_WIDTH})
		.addSprite("green_yellow", {animation: green_yellow, width: PLAYGROUND_WIDTH, height: PLAYGROUND_HEIGHT, posx: 2*PLAYGROUND_WIDTH})
		.addSprite("yellow1", {animation: yellow1, width: PLAYGROUND_WIDTH, height: PLAYGROUND_HEIGHT, posx: 3*PLAYGROUND_WIDTH})
		.addSprite("yellow2", {animation: yellow2, width: PLAYGROUND_WIDTH, height: PLAYGROUND_HEIGHT, posx: 4*PLAYGROUND_WIDTH})
		.addSprite("yellow_red", {animation: yellow_red, width: PLAYGROUND_WIDTH, height: PLAYGROUND_HEIGHT, posx: 5*PLAYGROUND_WIDTH})
		.addSprite("red1", {animation: red1, width: PLAYGROUND_WIDTH, height: PLAYGROUND_HEIGHT, posx: 6*PLAYGROUND_WIDTH})
		.addSprite("red2", {animation: red2, width: PLAYGROUND_WIDTH, height: PLAYGROUND_HEIGHT, posx: 7*PLAYGROUND_WIDTH})
		.addSprite("red_green", {animation: red_green, width: PLAYGROUND_WIDTH, height: PLAYGROUND_HEIGHT, posx: 8*PLAYGROUND_WIDTH});
	
	/*---------------------
		FOREGROUND
	-----------------------*/		
	var fg1 = new $.gameQuery.Animation({imageURL: "pics/level/fg/fg1.png"});
	var fg2 = new $.gameQuery.Animation({imageURL: "pics/level/fg/fg2.png"});
	
	//untergruppen fÃ¼r foreground anhÃ¤ngen
	$("#foreground").addSprite("fg1", {animation: fg1, width: PLAYGROUND_WIDTH, height: PLAYGROUND_HEIGHT})
		.addSprite("fg2", {animation: fg2, width: PLAYGROUND_WIDTH, height: PLAYGROUND_HEIGHT, posx: PLAYGROUND_WIDTH})
	
	/*---------------------
		LIGHT
	-----------------------*/
	var flashLight = new $.gameQuery.Animation({imageURL: "pics/powerUps/flashLight.png"});
	var extraPoints = new $.gameQuery.Animation({imageURL: "pics/powerUps/extraPoints.png"});
	var moonwalk_light = new $.gameQuery.Animation({imageURL: "pics/powerUps/moonwalk_light.png"});
	var marley_light = new $.gameQuery.Animation({imageURL: "pics/powerUps/marley_light.png"});
	
	//untergruppen fÃ¼r light anhÃ¤ngen
	$("#light").addSprite("flashLight", {animation: flashLight, width: PLAYGROUND_WIDTH, height: PLAYGROUND_HEIGHT})
		.addSprite("extraPoints", {animation: extraPoints, width: PLAYGROUND_WIDTH, height: PLAYGROUND_HEIGHT})
		.addSprite("moonwalk_light", {animation: moonwalk_light, width: PLAYGROUND_WIDTH, height: PLAYGROUND_HEIGHT})
		.addSprite("marley_light", {animation: marley_light, width: PLAYGROUND_WIDTH, height: PLAYGROUND_HEIGHT});
	$("#flashLight").hide();
	$("#extraPoints").hide();
	$("#moonwalk_light").hide();
	$("#marley_light").hide();
		
	//Movement
	$.playground().registerCallback(function() {
		if(!gameOver) {			
			//----------------------------
			//	background_far movement
			//----------------------------
			//green
			var newPos = (parseInt($("#bg_green").css("left")) - background_far_move - PLAYGROUND_WIDTH) % (-NR_BG_IMAGES * PLAYGROUND_WIDTH / 2) + PLAYGROUND_WIDTH;
			$("#bg_green").css("left", newPos);
			
			//green_yellow
			newPos = (parseInt($("#bg_green_yellow").css("left")) - background_far_move - PLAYGROUND_WIDTH) % (-NR_BG_IMAGES * PLAYGROUND_WIDTH / 2) + PLAYGROUND_WIDTH;
			$("#bg_green_yellow").css("left", newPos);
			
			//yellow
			newPos = (parseInt($("#bg_yellow").css("left")) - background_far_move - PLAYGROUND_WIDTH) % (-NR_BG_IMAGES * PLAYGROUND_WIDTH / 2) + PLAYGROUND_WIDTH;
			$("#bg_yellow").css("left", newPos);
			
			//yellow_red
			newPos = (parseInt($("#bg_yellow_red").css("left")) - background_far_move - PLAYGROUND_WIDTH) % (-NR_BG_IMAGES * PLAYGROUND_WIDTH / 2) + PLAYGROUND_WIDTH;
			$("#bg_yellow_red").css("left", newPos);
			
			//red
			newPos = (parseInt($("#bg_red").css("left")) - background_far_move - PLAYGROUND_WIDTH) % (-NR_BG_IMAGES * PLAYGROUND_WIDTH / 2) + PLAYGROUND_WIDTH;
			$("#bg_red").css("left", newPos);
		
			//red_green
			newPos = (parseInt($("#bg_red_green").css("left")) - background_far_move - PLAYGROUND_WIDTH) % (-NR_BG_IMAGES * PLAYGROUND_WIDTH / 2) + PLAYGROUND_WIDTH;
			$("#bg_red_green").css("left", newPos);
			
			//----------------------------
			//	background_close movement
			//----------------------------
			//green
			newPos = (parseInt($("#green1").css("left")) - background_close_move - PLAYGROUND_WIDTH) % (-NR_FG_IMAGES * PLAYGROUND_WIDTH) + PLAYGROUND_WIDTH;
			$("#green1").css("left", newPos);
		
			newPos = (parseInt($("#green2").css("left")) - background_close_move - PLAYGROUND_WIDTH) % (-NR_FG_IMAGES * PLAYGROUND_WIDTH) + PLAYGROUND_WIDTH;
			$("#green2").css("left", newPos);
			
			//green_yellow
			newPos = (parseInt($("#green_yellow").css("left")) - background_close_move - PLAYGROUND_WIDTH) % (-NR_FG_IMAGES * PLAYGROUND_WIDTH) + PLAYGROUND_WIDTH;
			$("#green_yellow").css("left", newPos);
			
			//yellow
			newPos = (parseInt($("#yellow1").css("left")) - background_close_move - PLAYGROUND_WIDTH) % (-NR_FG_IMAGES * PLAYGROUND_WIDTH) + PLAYGROUND_WIDTH;
			$("#yellow1").css("left", newPos);
		
			newPos = (parseInt($("#yellow2").css("left")) - background_close_move - PLAYGROUND_WIDTH) % (-NR_FG_IMAGES * PLAYGROUND_WIDTH) + PLAYGROUND_WIDTH;
			$("#yellow2").css("left", newPos);
			
			//yellow_red
			newPos = (parseInt($("#yellow_red").css("left")) - background_close_move - PLAYGROUND_WIDTH) % (-NR_FG_IMAGES * PLAYGROUND_WIDTH) + PLAYGROUND_WIDTH;
			$("#yellow_red").css("left", newPos);
			
			//red
			newPos = (parseInt($("#red1").css("left")) - background_close_move - PLAYGROUND_WIDTH) % (-NR_FG_IMAGES * PLAYGROUND_WIDTH) + PLAYGROUND_WIDTH;
			$("#red1").css("left", newPos);
			
			newPos = (parseInt($("#red2").css("left")) - background_close_move - PLAYGROUND_WIDTH) % (-NR_FG_IMAGES * PLAYGROUND_WIDTH) + PLAYGROUND_WIDTH;
			$("#red2").css("left", newPos);
		
			//red_green
			newPos = (parseInt($("#red_green").css("left")) - background_close_move - PLAYGROUND_WIDTH) % (-NR_FG_IMAGES * PLAYGROUND_WIDTH) + PLAYGROUND_WIDTH;
			$("#red_green").css("left", newPos);
		
			//----------------------------
			//	foreground movement
			//----------------------------
			newPos = (parseInt($("#fg1").css("left")) - foreground_move - PLAYGROUND_WIDTH) % (-2 * PLAYGROUND_WIDTH) + PLAYGROUND_WIDTH;
			$("#fg1").css("left", newPos);
			
			newPos = (parseInt($("#fg2").css("left")) - foreground_move - PLAYGROUND_WIDTH) % (-2 * PLAYGROUND_WIDTH) + PLAYGROUND_WIDTH;
			$("#fg2").css("left", newPos);
			
			var green = parseInt($("#bg_green").css("left")) + PLAYGROUND_WIDTH;
			var green_yellow = parseInt($("#green_yellow").css("left")) + PLAYGROUND_WIDTH;
			var yellow_red = parseInt($("#yellow_red").css("left")) + PLAYGROUND_WIDTH;
			var red_green = parseInt($("#red_green").css("left")) + PLAYGROUND_WIDTH;
			
			if(green_yellow < PLAYGROUND_WIDTH && green_yellow > 0) {
				bg = "yellow";
			}
			if(yellow_red < PLAYGROUND_WIDTH && yellow_red > 0) {
				bg = "red";
			}
			if(red_green < PLAYGROUND_WIDTH && red_green > 0) {
				bg = "green";
				if(red_green + 400 > PLAYGROUND_WIDTH - 2 && red_green + 400 < PLAYGROUND_WIDTH + 2 && difficulty < 6) {					
					
					// uerberprueft ob man ueber dem 4. "level" ist
					// und erhoeht ab dem 4. nur mehr jedes 2. mal
					if(difficulty < 4) {
						increase = true;	
					} else {
						if(increase) {
							increase = false;
						} else {
							increase = true;
						}
					}
					
					if(increase) {
						difficulty++;
						minObstacleDistance *= 1.2;
						background_far_move++;
						background_close_move = background_far_move * 2;
						foreground_move += 2;
						levelUp = false;
					} 
				}
			}
		}
	}, REFRESH_RATE);
	
	/*---------------------
			COUNTER
	-----------------------*/
	$("#counter").css("text-align","right").html("Score: " + counter);
	
	$.playground().registerCallback(function() {
		if(!gameOver) {
			counter += difficulty * 2;
			$("#counter").html("Score: " + counter);
		}
	}, 100);
	
	/*---------------------
		RESTART / PAUSE
	----------------------*/
	
	var loggingIn = false;
	$(":input").focusout(function(){
		loggingIn = false;
	});
	$(":input").focus(function(){
		loggingIn = true;
	});
	
	
	$("#restart").html("<a href='#' title='restart'>Restart</a>");
	$("#restart").click(function() {
		location.reload();
	});
	
	function pause() {
	  if(!muted){
		   muteAll();
		   alert("You paused the game! :) Click Ok to resume!");
		   muteAll();
	  } else {
	   	   alert("You paused the game! :) Click Ok to resume!");
	  } 
 	}
	
	$("#pause").html("<a href='#' title='pause'>Pause</a>");
	$("#pause").click(function() {
		pause();
		return false;
	});
	
	$(document).keydown(function(e) {
			switch(e.keyCode) {
				case 82: //r
					if(!gameStart) {
							if(!loggingIn){
								$.playground().startGame(function() {
									gameStart = true;
									$("#welcomeScreen").fadeTo(500, 0, function() { $(this).remove(); });
									soundManager.play('hans');
								});	
							}
						} else {
							if(!loggingIn){
								location.reload();
							}
						}
					break;
				case 80: //p
				//////////////////////////////////////////
				// Kosi mute sounds plz
				// Who is awesome? Your awesome :D
				//////////////////////////////////////////
					if(!loggingIn){
						pause();
					}
					break;
			}
	});
	
    
	/*---------------------		  
			PLAYER
	-----------------------*/
	var playerAnimation = new Array();
	
	/*
	numberOfFrame 	- The total number of frame in the animation (for example for a 10x10 sprite with 15 frames your image will be 10x150 or 150x10)
	delta			- The width or height (depending on the type) of one frame.
	rate			- The number of milliseconds between two frames
	*/
	
	//definiere verschiedene Stadien des Players --> "moves"
	playerAnimation["run"] = new $.gameQuery.Animation({imageURL: "pics/character/hans_run.png", numberOfFrame: 6, delta: PLAYER_WIDTH, rate: 100, type: $.gameQuery.ANIMATION_HORIZONTAL});
	playerAnimation["jump"] = new $.gameQuery.Animation({imageURL: "pics/character/hans_jump.png"});
	playerAnimation["dead"] = new $.gameQuery.Animation({imageURL: "pics/character/hans_dead.png", numberOfFrame: 5, delta: PLAYER_WIDTH, rate: 100, type: $.gameQuery.ANIMATION_HORIZONTAL});
	
	//powerup animations
	playerAnimation["moonwalk"] = new $.gameQuery.Animation({imageURL: "pics/character/hans_moonwalk.png", numberOfFrame: 10, delta: PLAYER_WIDTH, rate: 75, type: $.gameQuery.ANIMATION_HORIZONTAL});
	playerAnimation["marley"] = new $.gameQuery.Animation({imageURL: "pics/character/hans_marley.png", numberOfFrame: 10, delta: PLAYER_WIDTH, rate: 150, type: $.gameQuery.ANIMATION_HORIZONTAL});
	playerAnimation["marleyJump"] = new $.gameQuery.Animation({imageURL: "pics/character/hans_marley_jump.png", type: $.gameQuery.ANIMATION_HORIZONTAL});
	
	//fÃ¼ge Player zum Playground hinzu
	$("#playerAnimations").addGroup("player", {posx: 50, posy: START_POSITION, width: PLAYER_WIDTH, height: PLAYER_HEIGHT})
		.addSprite("playerRun", {animation: playerAnimation["run"], width: PLAYER_WIDTH, height: PLAYER_HEIGHT})
		.addSprite("playerJump", {animation: playerAnimation["jump"], width: PLAYER_WIDTH, height: PLAYER_HEIGHT})
		.addSprite("playerMoonwalk", {animation: playerAnimation["moonwalk"], width: PLAYER_WIDTH, height: PLAYER_HEIGHT})
		.addSprite("playerMarley", {animation: playerAnimation["marley"], width: PLAYER_WIDTH, height: PLAYER_HEIGHT})
		.addSprite("playerMarleyJump", {animation: playerAnimation["marleyJump"], width: PLAYER_WIDTH, height: PLAYER_HEIGHT})
		.addSprite("playerDead", {animation: playerAnimation["dead"], width: PLAYER_WIDTH, height: PLAYER_HEIGHT});
		
	$("#playerJump").hide(); 		//um die sprung Sprite anfangs zu "verstecken"
	$("#playerMoonwalk").hide();
	$("#playerMarley").hide();
	$("#playerMarleyJump").hide();
	$("#playerDead").hide();

	function showJumpAnimation() {
		$("#playerRun").setAnimation();
		$("#playerMoonwalk").setAnimation();
		$("#playerMarley").setAnimation();
		$("#playerJump").show().setAnimation(playerAnimation["jump"]);
	}
	
	function showRunAnimation() {
		$("#playerJump").setAnimation();
		$("#playerMoonwalk").setAnimation();
		$("#playerMarley").setAnimation();
		$("#playerMarleyJump").setAnimation();
		$("#moonwalk_light").hide();
		$("#marley_light").hide();
		$("#playerRun").setAnimation(playerAnimation["run"]);
	}

	function showMoonwalk() {
		$("#playerJump").setAnimation();
		$("#playerRun").setAnimation();
		$("#playerMarley").setAnimation();
		$("#moonwalk_light").show();
		$("#playerMoonwalk").show().setAnimation(playerAnimation["moonwalk"]);
	}
	
	function showMarley() {
		$("#playerJump").setAnimation();
		$("#playerRun").setAnimation();
		$("#playerMarleyJump").setAnimation();
		$("#marley_light").show();
		$("#playerMarley").show().setAnimation(playerAnimation["marley"]);
	}
	
	function showMarleyJump() {
		$("#playerJump").setAnimation();
		$("#playerRun").setAnimation();
		$("#playerMarley").setAnimation();
		$("#playerMarleyJump").show().setAnimation(playerAnimation["marleyJump"]);
	}
	
	function showDead() {
		$("#playerRun").setAnimation();
		$("#playerJump").setAnimation();
		$("#playerMoonwalk").setAnimation();
		$("#playerMarley").setAnimation().hide();
		$("#playerMarleyJump").setAnimation().hide();
		$("#moonwalk_light").hide();
		$("#marley_light").hide();
		$("#playerDead").show().setAnimation(playerAnimation["dead"]);
		playDeathSound();
	}
		
	//tastatursteuerung	
	$(document).keydown(function(e) {
		switch(e.keyCode) {
	
			case 32: //Leertaste
				if(gameStart) {
					if(!marley && !moonwalk && !gameOver) {
						showJumpAnimation();
					}
					else if(marley && !moonwalk && !gameOver) {
						showMarleyJump();
					}
				}
				break;
				
		}
	});
	
	$(document).keyup(function(e) {
		switch(e.keyCode){
			case 32:
				if(!marley && !moonwalk && !gameOver) {
					showRunAnimation();
				}
				else if(marley && !moonwalk && !gameOver) {
					showMarley();
				}
				break;
		}
	});
	
	//Logik des Springens
	function jumpAnimation() {
		currentPos = parseInt($("#player").css("top"));
		var jumpPosition = currentPos - 100; 		// festlegen der sprunghÃ¶he
		
		if(!jump) {		//damit nur ein klick registriert wird!! 
			if(numberOfJumps < 3) {	
				$("#player").stop(true); //stoppt die Animation nach "unten" falls in der luft gedrÃ¼ckt wird			 
				
				if(!marley && !moonwalk) {
					$("#player").animate({"top": jumpPosition + "px"}, 500, 'easeOutQuad') // der sprung selbst
						.animate({"top": START_POSITION + "px"}, 500, 'easeInQuad');
				}
				else if(marley && !moonwalk) {
					$("#player").animate({"top": jumpPosition + "px"}, 750, 'easeOutQuad') // der sprung selbst
						.animate({"top": START_POSITION + "px"}, 750, 'easeInQuad');
				}
					
				numberOfJumps++;
			}
			
			jump = true;
		} 
	}
	
	$.playground().registerCallback(function() {
		if(!gameOver){
			if($.gameQuery.keyTracker[32]) {
				jumpAnimation();
			} 
            else {
				currentPos = parseInt($("#player").css("top"));
				jump = false;
				
				if(currentPos == START_POSITION) {	//wenn der player wieder am boden ist, setze die sprÃ¼nge auf null zurÃ¼ck
					numberOfJumps = 0;				
				}
			}
		}
	}, REFRESH_RATE);
	
	/*---------------------
		Power Ups
	-----------------------*/
	var p_ups = new Array();
	p_ups["moonwalk"] = new $.gameQuery.Animation({imageURL: "pics/powerUps/moonwalk_powerUp.png", numberOfFrame: 11, delta: 101, rate: 100, type: $.gameQuery.ANIMATION_HORIZONTAL});
	p_ups["marley"] = new $.gameQuery.Animation({imageURL: "pics/powerUps/marley_powerUp.png", numberOfFrame: 11, delta: 100, rate: 100, type: $.gameQuery.ANIMATION_HORIZONTAL});
	
	var powerupCounter = 0;
	
	$.playground().registerCallback(function() {
		if(!gameOver) {
			if(!moonwalk && !marley) {
				powerupCounter++;
				var powerupName = "powerup" + powerupCounter;
				
				var decisionVariable = Math.random();
				var posY = Math.random() * (PLAYGROUND_HEIGHT - BOTTOM_LINE - 80);
				
				if(posY > PLAYGROUND_HEIGHT - BOTTOM_LINE - 80) {
					posY = PLAYGROUND_HEIGHT - BOTTOM_LINE - 80;
				}
				else if(posY < 50) {
					posY += 50;
				}
				
				$(".obstacle").each(function() {
					var obstacleLeft = parseInt($(this).css("left"));
					var obstacleRight = obstacleLeft + this.obstacle.width;
					var obstacleTop = parseInt($(this).css("top"));
					var obstacleBottom = obstacleTop + this.obstacle.height;
					
					if(posY + 80 < obstacleTop || posY > obstacleBottom || obstacleLeft > PLAYGROUND_WIDTH + 100 || obstacleRight < PLAYGROUND_WIDTH) {
					}
					else {
						if(obstacleTop <= posY && obstacleBottom >= posY) {
							posY = obstacleBottom + 20;
							
							if(posY > PLAYGROUND_HEIGHT - BOTTOM_LINE - 80) {
								posY = obstacleTop - 100;
							}
						}
						else if(obstacleTop <= posY + 80 && obstacleBottom >= posY + 80) {
							posY = obstacleTop - 100;
							
							if(posY < 50) {
								posY = obstacleBottom + 20;
							}
						}
						else {
							posY = obstacleTop - 100;
							
							if(posY < 50) {
								posY = obstacleBottom + 20;
							}
						}
					}
				});
				
				if(decisionVariable < 0.5) {
					$("#powerUps").addSprite(powerupName, {animation: p_ups["moonwalk"], width: 100, height: 80, posx: PLAYGROUND_WIDTH, posy: posY});
					$("#" + powerupName).addClass("powerup").addClass("moonwalk");
				}
				else {
					$("#powerUps").addSprite(powerupName, {animation: p_ups["marley"], width: 100, height: 80, posx: PLAYGROUND_WIDTH, posy: posY});
					$("#" + powerupName).addClass("powerup").addClass("marley");
				}
			}
		}
	}, 25000);
	
	//powerup movement, collision detection
	$.playground().registerCallback(function() {
		if(!gameOver) {
			$(".powerup").each(function() {
				var newPos = parseInt($(this).css("left")) - foreground_move;
				$(this).css("left", newPos + "px");
				
				var powerupLeft = parseInt($(this).css("left"));
				var powerupRight = powerupLeft + 100;
				var powerupTop = parseInt($(this).css("top"));
				var powerupBottom = powerupTop + 80;
				
				var playerLeft = parseInt($("#player").css("left"));
				var playerRight = playerLeft + PLAYER_WIDTH;
				var playerTop = parseInt($("#player").css("top"));
				var playerBottom = playerTop + PLAYER_HEIGHT;
				
				if(powerupRight < 0) {
					$(this).remove();
					return;
				}
				
				if(powerupLeft + 20 < playerRight && powerupRight - 20 > playerLeft && powerupTop + 20 < playerBottom && powerupBottom - 20 > playerTop) {
					counter += 1000;
					powerupStartTime = new Date();
					powerupStartTime = powerupStartTime.getTime();
					powerup = true;
					$("#flashLight").show().fadeIn(200).fadeOut(1500);
					$("#extraPoints").show().animate({"opacity":1, "left":-50},200)
						.animate({"left":100},200)
						.animate({"left":-50},200)
						.animate({"left":100, "opacity":0},200);
					
					if($(this).hasClass("moonwalk")) {
						$("#player").stop(true);
						$("#player").css("top", START_POSITION);
						$("#player").css("left", 400 - PLAYER_WIDTH / 2);
						showMoonwalk();
						moonwalk = true;
						playMoonwalkSound();
						$(this).remove();
					}
					else if($(this).hasClass("marley")) {
						showMarley();
						playMarleySound();
						marley = true;
						$(this).remove();
					}
				}
			});
		}
	}, REFRESH_RATE);
	
	/*---------------------
            OBSTACLES
    -----------------------*/
	var obstacles = new Array();
	obstacles["green"] = new Array();
	obstacles["green"]["short"] = new $.gameQuery.Animation({imageURL: "pics/obstacles/obstacle_green.png"});
	obstacles["yellow"] = new Array();
	obstacles["yellow"]["short"] = new $.gameQuery.Animation({imageURL: "pics/obstacles/obstacle_yellow.png", numberOfFrame: 10, delta: HORIZONTAL_HEIGHT, rate: 150, type: $.gameQuery.ANIMATION_VERTICAL});
	obstacles["red"] = new Array();
	obstacles["red"]["short"] = new $.gameQuery.Animation({imageURL: "pics/obstacles/obstacle_red.png", numberOfFrame: 2, delta:HORIZONTAL_HEIGHT, rate: 100, type: $.gameQuery.ANIMATION_VERTICAL});
	
	var gameOverCounter = 1;
	var obstacleCounter = 0;
	var first = true;
	var distance = offset[Math.floor(Math.random() * 15)];
	
	$.playground().registerCallback(function() {
		if(!gameOver) {
			//generation of obstacles
			if(!moonwalk) {
				var decisionVariable = Math.random();
				
				var obstacleName = "obstacle" + obstacleCounter;
				var posX = PLAYGROUND_WIDTH;
				
				var prevObstacleNr = -1;
				var prevEndPosX;
				
				if(obstacleCounter > 0) {
					prevObstacleNr = obstacleCounter - 1;
					
					if(!first && prevObstacleNr == 0) {
						prevObstacleNr = 10;
					}
					
					prevEndPosX = parseInt($("#obstacle" + prevObstacleNr).css("left")) + parseInt($("#obstacle" + prevObstacleNr).css("width"));
				}
				
				/*------------------------------
					variable length obstacle
				--------------------------------*/				
				if(prevObstacleNr == -1 || PLAYGROUND_WIDTH - prevEndPosX > MIN_OBSTACLE_DISTANCE + distance) {
					distance = offset[Math.floor(Math.random() * 15)];
					
					if(decisionVariable < 1) {
						var posY = Math.random() * (PLAYGROUND_HEIGHT - BOTTOM_LINE - HORIZONTAL_HEIGHT);
						var prevPosY;
						
						if(posY > PLAYGROUND_HEIGHT - BOTTOM_LINE - HORIZONTAL_HEIGHT) {
							posY -= BOTTOM_LINE - HORIZONTAL_HEIGHT;
						}
						if(posY < 50) {
							posY = 50;
						}
						
						if(obstacleCounter != 0) {
							prevPosY = parseInt($("#obstacle" + prevObstacleNr).css("top"));
							
							if(prevPosY < 100) {
								posY = 300;
							}
						}
						
						$("#obstacles").addSprite(obstacleName, {animation: obstacles[bg]["short"], posx: posX, posy: posY, width: HORIZONTAL_SHORT_WIDTH, height: HORIZONTAL_HEIGHT});
						$("#" + obstacleName).addClass("obstacle");
						$("#" + obstacleName)[0].obstacle = new HorizontalShort($("#" + obstacleName), HORIZONTAL_SHORT_WIDTH, HORIZONTAL_HEIGHT);
					}
				}
				else {
					obstacleCounter--;
				}
			}
			else {
				obstacleCounter = -1;
				first = true;
			}
			
			if(obstacleCounter == 10) {
				first = false;
				obstacleCounter = 0;
			}
			
			obstacleCounter++;
		}
	}, REFRESH_RATE);
	
	var prevPlayerTop = START_POSITION;
	
	$.playground().registerCallback(function() {
		if(!gameOver) {
			if(powerup) {
				var currentTime = new Date();
				currentTime = currentTime.getTime();
				
				if(currentTime - powerupStartTime > moonwalkTime) {
					if(moonwalk) {
						$("#player").css("left", 50);
						$("#player").css("top", START_POSITION);
					}
					
					powerup = false;
					moonwalk = false;
					marley = false;
					stopPowerUpSound();
					$("#flashLight").show().fadeIn(200).fadeOut(1500);
					showRunAnimation();
				}
			}
			
			//obstacles movement, collision detection
			if(!moonwalk) {
				$(".obstacle").each(function() {
					this.obstacle.update($("#player"));
					var obstacleLeft = parseInt($(this).css("left")) + 15;
					var obstacleRight = obstacleLeft + this.obstacle.width - 15;
					var obstacleTop = parseInt($(this).css("top"));
					var obstacleBottom = obstacleTop + this.obstacle.height;
					
					var playerLeft = parseInt($("#player").css("left"));
					var playerRight = playerLeft + PLAYER_WIDTH;
					var playerTop = parseInt($("#player").css("top"));
					var playerBottom = playerTop + PLAYER_HEIGHT;
					
					if(obstacleLeft < playerRight && obstacleRight > playerLeft) {
						if(prevPlayerTop < playerTop && obstacleTop >= playerBottom - 50 && obstacleTop <= playerBottom) {
							$("#player").stop(true);
							$("#player").css("top", obstacleTop - PLAYER_HEIGHT);
							numberOfJumps = 0;
						}
						else if(obstacleTop < playerBottom && obstacleBottom > playerTop) {
							gameOver = true;
							
                            if($("#loggedIn").val()!=""){
                                $("#submitScoreForm").fadeIn(4000);
                            }
							
							$("#flashLight").show().fadeIn(200).fadeOut(500);
							$("#player").stop(true);
							showDead();
							$("#foreground").addSprite("game_over", {animation: game_over, width: 800, height: 1000, posx: 0, posy: 0});
							
							var prevPlayerTopPosition = parseInt($("#player").css("top"));
							
							$(".obstacle").each(function() {
								$(this).remove();
							});
							
							$(".powerup").each(function() {
								$(this).remove();
							});
														
							$("#player").fadeOut(4000);
							
							$.playground().registerCallback(function() {
								if(parseInt($("#green1").css("top")) < PLAYGROUND_HEIGHT + 200) {
									var newTop = prevPlayerTopPosition - 5;
									prevPlayerTopPosition = newTop;
									$("#player").css("top", newTop);
									
									var newPos = parseInt($("#green1").css("top")) + 10;
									
									$("#green1").css("top", newPos);
									$("#green2").css("top", newPos);
									$("#green_yellow").css("top", newPos);
									$("#yellow1").css("top", newPos);
									$("#yellow2").css("top", newPos);
									$("#yellow_red").css("top", newPos);
									$("#red1").css("top", newPos);
									$("#red2").css("top", newPos);
									$("#red_green").css("top", newPos);
									$("#fg1").css("top", newPos);
									$("#fg2").css("top", newPos);
									
									$("#bg_green").css("top", newPos);
									$("#bg_green_yellow").css("top", newPos);
									$("#bg_yellow").css("top", newPos);
									$("#bg_yellow_red").css("top", newPos);
									$("#bg_red").css("top", newPos);
									$("#bg_red_green").css("top", newPos);
									
									$("#fg1").css("top", newPos);
									$("#fg2").css("top", newPos);
									
									$("#game_over").css("top", newPos - 900);
								}
								else if(prevPlayerTopPosition > -PLAYER_HEIGHT) {
									var newTop = prevPlayerTopPosition - 5;
									prevPlayerTopPosition = newTop;
									$("#player").css("top", newTop);
								}
							}, REFRESH_RATE);
						}
					}
					
					if(obstacleRight < 0) {
						$(this).remove();
						return;
					}
				
					if(obstacleRight < playerLeft) {
						$("#player").animate({"top": START_POSITION + "px"}, 500, 'easeInQuad');
					}
					
					prevPlayerTop = playerTop;
				});
			}
			else {
				$(".obstacle").each(function() {
					$(this).remove();
				});
			}
		}
    }, REFRESH_RATE);
	
	function HorizontalShort(node, width, height) {
		this.width = width;
		this.height = height;
		this.speedx = foreground_move;
		this.node = $(node);
		
		this.update = function(obstacleNode) {
			if(marley) {
				this.speedx = foreground_move / 2;
			}
			else {
				this.speedx = foreground_move;
			}
			
			var newPos = parseInt(this.node.css("left")) - this.speedx;
			this.node.css("left", newPos + "px");
		};
	}
	
	$("#submitScore").click(function(){
		$("#score").val(counter);
		$.post("/includes/backend.php", {"score": counter});
	});
	
	//-------------------------
	//SOUND
	//-------------------------
	$("#muteButton").css("cursor","pointer");
	function muteAll() {
		if(!muted) {
			$("#muteButton").css("background-image", "url('pics/speaker_mute.png')");
			soundManager.mute('hans');
     		soundManager.mute('marley');
			soundManager.mute('moonwalk');
			soundManager.mute('jump');
			soundManager.mute('death');
			muted = true;
		} else {
			$("#muteButton").css("background-image", "url('pics/speaker.png')");
			if(marley) {
				soundManager.unmute('marley');
				soundManager.unmute('jump');
			} else if (moonwalk) {
				soundManager.unmute('moonwalk');
				soundManager.unmute('jump');
			} else {
				soundManager.unmute();
			}
		muted = false;
		}
	}
	
	$("#welcomeScreen").click(function(){
		soundManager.play('hans');
	});
	
	$("#muteButton").click(function() {
		muteAll();
	});
	
	$(document).keydown(function(e) {
		jumpSound = false;
		if(gameStart) {
			switch(e.keyCode) {
				case 32: //Leertaste
					if(!marley && !moonwalk && !gameOver && numberOfJumps < 3) {
						if(!jumpSound) {
							jumpSound = true;
							soundManager.play('jump');
						} 
					}
					break;
				case 77: //this is m
					muteAll();
				break;
			}
		}
	});
	
	$(document).keyup(function(e) {
		switch(e.keyCode) {
			case 32: //Leertaste
				jumpSound = false;
				break;
		}
	});
	
	
	//muss noch "verlaengert" werden
	function playDeathSound() {
		soundManager.stop('hans');
		soundManager.stop('marley');
		soundManager.play('death');
	}
	
	function playMarleySound() {
		soundManager.mute('hans');
		soundManager.play('marley');
	}
	
	function playMoonwalkSound() {
		soundManager.mute('hans');
		soundManager.play('moonwalk');
	}
	
	function stopPowerUpSound() {
		if(!muted) {
			soundManager.unmute('hans');
			soundManager.unmute('jump');
			soundManager.unmute('death');
		}
		soundManager.stop('marley');
		soundManager.stop('moonwalk');
	}
});
