/*
 * trajectory.js
 * Builds on the example in arrow.js. This example shows how to
 * calculate and draw the trajectory path of the arrow.
 */
  
var tmp = null;

// Reference to canvas context
var ctx = false;

// Update frequency
var fHz = 1000/60;

// Canvas size
var canvas_size = {x: 10, y: 10};

// Reference to the interval, used to
// clear it at reset.
var interval = null;

// Box2D World
var world = null;

// Pixel-to-Meter ratio
var PTM_RATIO = 30.0;

var initialised = false;

var game_number = null;
var award_position = null;
var move = null;
var movements = null;
var win = false;
var playerSprite = document.getElementById("player");
var playerPosition = {x: 50, y: 30};
var prize = document.getElementById("award");
var currentPosition = null;
var targetPosition = null;
var labyrinthPlayer = null;
var end_simulation = false;
var show_response = false;

var stepsSound =document.getElementById('steps');
var winSound =document.getElementById('win');
var loseSound =document.getElementById('game-over');

var startValue = 180000; // 3 mins in milliseconds
var time = new Date(startValue);
var interv = null;
var timeFinish = false;

function done(){
    end_simulation = true;
    win = false;
}
function startTimer(){
    displayTime();
    interv = setInterval(function(){
        time = new Date(time - 1000);
        if(time<=0){
            done();
            clearInterval(interv);
            timeFinish = true;
        }
        displayTime();
    }, 1000);
}

function displayTime(){
    $(".time").text(fillZeroes(time.getMinutes(), true) + ":" + fillZeroes(time.getSeconds(),false));
}

function fillZeroes(t, min){
    t = t+"";
    if(t.length==1){
        return "0" + t;
    }else if(t.length==2 && min){
    		return "0" + t.substr(1); 
    }
		else{
        return t
    };
}

/*
 * createMap
 * Draws the static and dynamic bodies used.
 */
function createMap(){
	// Wall thickness
	var wt = 5;
	// Platform thickness
	var pt = 5;
	// Platform width
	var pw = 5;

	// Left wall
	tmp = createBox(p2b(wt), 
			  p2b(canvas_size.y/2), 
			  p2b(wt), 
			  p2b(canvas_size.y/2), 
			  b2Body.b2_staticBody);
	tmp.SetUserData("Left wall");
			  
	// Right wall
	tmp = createBox(p2b(wt), 
			  p2b(canvas_size.y/2), 
			  p2b(canvas_size.x - wt), 
			  p2b(canvas_size.y/2), 
			  b2Body.b2_staticBody);
	tmp.SetUserData("Right wall");
			  
	// Ground
	tmp = createBox(p2b(canvas_size.x / 2), 
			  p2b(wt), 
			  p2b(canvas_size.x / 2), 
			  p2b(canvas_size.y - wt), 
			  b2Body.b2_staticBody);
	tmp.SetUserData("Ground");
	
	// Ceiling
	tmp = createBox(p2b(canvas_size.x / 2), 
			  p2b(wt), 
			  p2b(canvas_size.x / 2), 
			  p2b(wt), 
			  b2Body.b2_staticBody);
			  
	tmp.SetUserData("Ceiling");

	// Camino
	tmp = createBox(p2b(wt*2),
					p2b(200),
					p2b(100),
					p2b(wt),
					b2Body.b2_dinamicBody);

	tmp = createBox(p2b(200),
					p2b(2*wt),
					p2b(wt),
					p2b(300),
					b2Body.b2_dinamicBody);

	tmp = createBox(p2b(2*wt),
					p2b(200),
					p2b(200),
					p2b(wt+350),
					b2Body.b2_dinamicBody);

	tmp = createBox(p2b(100),
					p2b(2*wt),
					p2b(wt+200),
					p2b(wt+75),
					b2Body.b2_dinamicBody);

	tmp = createBox(p2b(50),
					p2b(2*wt),
					p2b(350),
					p2b(160),
					b2Body.b2_dinamicBody);

	tmp = createBox(p2b(50),
					p2b(2*wt),
					p2b(wt+350),
					p2b(300),
					b2Body.b2_dinamicBody);

	tmp = createBox(p2b(2*wt),
					p2b(75),
					p2b(300),
					p2b(wt+225),
					b2Body.b2_dinamicBody);

	tmp = createBox(p2b(20),
					p2b(20),
					p2b(award_position.x),
					p2b(award_position.y),
					b2Body.b2_dinamicBody);
	tmp.SetUserData("Prize");
}

function createPlayer(){
	player = createBox(p2b(15), 
			  p2b(15), 
			  p2b(playerPosition.x), 
			  p2b(playerPosition.y), 
			  b2Body.b2_dinamicBody);
	player.SetUserData("Player");
	return player
}


/*
 * preventDefault
 * Used to prevent the default behavior of
 * double clicks and select start events.
 */
function preventDefault(event){
	if (event.preventDefault)
		event.preventDefault();
	else
		event.returnValue= false;
	return false;
}

/*
 * reset
 * Resets the demo.
 */
function reset() {
	window.location.reload();
}

function checkPosition (position) {	
	var body = world.GetBodyList();
	while(body != null){
		var fixture = body.GetFixtureList();
		if(fixture){
			var top_left_corner = new b2Vec2(position.x - p2b(10), position.y + p2b(10));
			var bottom_left_corner = new b2Vec2(position.x - p2b(10), position.y - p2b(10));
			var top_right_corner = new b2Vec2(position.x + p2b(10), position.y + p2b(10));
			var bottom_right_corner = new b2Vec2(position.x + p2b(10), position.y - p2b(10));
			var test_point = fixture.TestPoint(top_left_corner) || fixture.TestPoint(bottom_left_corner) || 
						fixture.TestPoint(top_right_corner) || fixture.TestPoint(bottom_right_corner); 
			if(test_point){
				var userData = body.GetUserData();
				if(userData == 'Prize'){
					end_simulation = true;
					win = true;
					return true;
				}else{
					if(userData != 'Player'){
						end_simulation = true;
						win = false;
						return false;
					}
				}
			};
		};
		body = body.GetNext();
	}	
	return true;
}

/*
 * update
 * The main update function
 */
function update(){

	// Update the world simulation
	world.Step(
		  1/60,      //frame-rate
		  10,       //velocity iterations
		  10       //position iterations
	);

  if(movements && !end_simulation){
		if(move < movements.length){
			if(!targetPosition) {
				currentPosition = labyrinthPlayer.GetPosition();
			  targetPosition = new b2Vec2(currentPosition.x + p2b(movements[move].x),currentPosition.y + p2b(movements[move].y));
			}else if(targetPosition && !targetPosition.x && !targetPosition.y){
				currentPosition = null;
				targetPosition = null;
	      move++;
			}else{
				if(targetPosition.x){
					if(movements[move].x >= 0){
						if(currentPosition.x < targetPosition.x){
							currentPosition.x+=0.02
						}else if(currentPosition.x >= targetPosition.x){
							targetPosition.x = null
						}
					}
				}
				if(targetPosition.y){
					if(movements[move].y >= 0){
						if(currentPosition.y < targetPosition.y){
							currentPosition.y+=0.02
						}else if(currentPosition.y >= targetPosition.y){
							targetPosition.y = null
						}
					}
				}
				if(targetPosition.x){
					if(movements[move].x < 0){
						if(currentPosition.x > targetPosition.x){
							currentPosition.x-=0.02
						}else if(currentPosition.x <= targetPosition.x){
							targetPosition.x = null
						}
					}
				}
				if(targetPosition.y){
					if(movements[move].y < 0){
						if(currentPosition.y > targetPosition.y){
							currentPosition.y-=0.02
						}else if(currentPosition.y <= targetPosition.y){
							targetPosition.y = null
						}
					}
				}
				if(checkPosition(currentPosition)){ 
					labyrinthPlayer.SetPosition(currentPosition); 
					stepsSound.play();
				}
			}
	  }
	}
  // Draw debug data on the canvas
	world.DrawDebugData();
	ctx.save();	
	ctx.drawImage(prize,award_position.x-20,award_position.y-20);
	if(currentPosition){ playerPosition = {x: b2p(currentPosition.x),y: b2p(currentPosition.y)} }
	var playerSpritePos = playerPosition;
	ctx.drawImage(playerSprite,playerSpritePos.x-15,playerSpritePos.y-15);
	ctx.restore();

	if(end_simulation){
		movements = null;
		alert_result();
	}

 	//golfPlayer.update();
	world.ClearForces();
}


/*
 * 
 *
 */
function alert_result(){
	if(win){
		document.getElementById('perdiste').style.display = 'none';  
		document.getElementById('ganaste').style.display = 'block';
		document.getElementById('sin_tiempo').style.display = 'none'; 
		if(winSound) { winSound.play(); }
		winSound = null;
	}else{
    if(timeFinish){
			document.getElementById('perdiste').style.display = 'none';
			document.getElementById('ganaste').style.display = 'none';
			document.getElementById('sin_tiempo').style.display = 'block';
    }else{
			document.getElementById('perdiste').style.display = 'block';
			document.getElementById('ganaste').style.display = 'none';
			document.getElementById('sin_tiempo').style.display = 'none';
    }  
		if(loseSound) { loseSound.play(); }
		loseSound = null;
	}
  clearInterval(interv);
  time = new Date(startValue);
  displayTime();
}

function generateGameNumber() {
    return Math.floor((Math.random() * 2) + 1);
}

/*
 * init
 * Initialises the demo.
 */
function init(){
	/* 
	 * Select version number and creates game input according to game number
	*/	
	game_number = generateGameNumber();
  award_position = {x: 350, y: 350};
  if (game_number == 2) { 
  	award_position = {x: 140, y: 40};
  }
	//
	// Create the box2d world
	///
	
	world = new b2World(
						new b2Vec2(0, 10),   //gravity
						true                 //allow sleep
					   );
	//
	// Configure debug draw
	//
	setDebugDraw(world);
	
	var canvas = document.getElementById('canvas');
				
	ctx = canvas.getContext('2d');
	
	canvas_size.x = canvas.width;
	canvas_size.y = canvas.height;
	
	var start = document.getElementById('start_btn');
	start.addEventListener('click', function(e) {
		if(!interv){startTimer()};
		var xsMovements = document.getElementsByName('x[]');
		var ysMovements = document.getElementsByName('y[]');
		movements = new Array();
		for(var i = 0; i < xsMovements.length; i++){
			movements[i] = {x: parseInt(xsMovements[i].value*20), y: parseInt(ysMovements[i].value*20)}
		}
		if( movements.length != 0){       		    	
			currentPosition = null;
			targetPosition = null;
			end_simulation=false;
			move = 0;
		}
	}, false);

	// Create event listeners
	canvas.addEventListener('selectstart', 
							function(e){preventDefault(e);}, 
							false);
	canvas.addEventListener('dblclick', 
							function(e){preventDefault(e);}, 
							false);

	// The reset button.
	var reset_btn = document.getElementById('reset_btn');
	reset_btn.addEventListener('click', 
							function(e) { reset(); }, 
							false);
	
	
	createMap();
	labyrinthPlayer = createPlayer();
	interval = window.setInterval(update, fHz);
}

