<!doctype html>

<html lang="en">
<head>
  <meta charset="utf-8">

  <title>GeoQuiz</title>
  <meta name="description" content="GeoQuiz">
  <meta name="author" content="GeoQuiz">
  <link rel="stylesheet" href="style.css">
</head>

<body>
<div id="can"></div>
<div id="interface">
	<p class="important"> Enter the missing country's name : </p>
	<input id="countryName" type="text" name="countryName" class="answerInput" onInput="checkCountry()">
	<p id="timeLeft" class="important"> 120s </p>
</div>
<script src="pixi.js-master/bin/pixi.js"></script>
<script>
var worldWidth = 1425.0;
var worldHeight = 561.0;
var worldY = 418.205;

var windowShare = 0.8;
var stageShare = 0.9;

var zoomSpeed = 1.1;

document.getElementById("countryName").focus();

var renderer = PIXI.autoDetectRenderer(window.innerWidth * windowShare, window.innerHeight * windowShare,{backgroundColor : 0x1099bb});
document.getElementById("can").appendChild(renderer.view);
if (renderer.view.addEventListener) {
	renderer.view.addEventListener("mousewheel", mouseWheelHandler, false);
	renderer.view.addEventListener("DOMMouseScroll", mouseWheelHandler, false);
}
else {
	renderer.view.attachEvent("onmousewheel", mouseWheelHandler);
}

// create the root of the scene graph
var stage = new PIXI.Container();

var group = new PIXI.Container();
group.interactive = true;

group
	.on('mousedown', onDragStart)
	.on('touchstart', onDragStart)
	.on('mouseup', onDragEnd)
	.on('mouseupoutside', onDragEnd)
	.on('touchend', onDragEnd)
	.on('touchendoutside', onDragEnd)
	.on('mousemove', onDragMove)
	.on('touchmove', onDragMove);

var scale = 150.0/90.0;
var scale2 = (window.innerWidth * windowShare) / (worldWidth / stageShare);
var shiftX = ((window.innerWidth * windowShare) - (scale2 * worldWidth)) / 2;
var shiftY = (worldY * scale) * scale2 + (((window.innerHeight * windowShare) - (scale2 * worldHeight)) / 2); 

var oldShiftX = shiftX;
var oldShiftY = shiftY;

var initTime = 0;
var initTimes = [];
var done = [];
var time = 0;
var times = [];
var idInvisible = 0;

var textSpeed = 5;
var textOffset = 500;
var textWidth = 600;

var currentIndexInvisible = 0;

var countries = [];

var loader = new PIXI.loaders.Loader();

var mode = 0; 
//0 -> loading
//1 -> game
//2 -> gg
//3 -> perdu
//4 -> sending data

<?php
include("connectServer.php");
$count = 0;
$invisibleCount = 10;
$file = fopen("data.data", "r") or die("Unable to open file!");
while(!feof($file)) {
	$count ++;

	$str = fgets($file);
	$str = trim(preg_replace('/\s\s+/', ' ', $str));
	$pieces = explode(" ", $str);
	
	$x = floatval(str_replace(",", ".", $pieces[0]));
	$y = floatval(str_replace(",", ".", $pieces[1]));
	$shortName = $pieces[2];
	
	?>
	
	var country  = {x:<?php echo $x; ?> , y:<?php echo $y; ?>, shortName:'<?php echo $shortName; ?>', names:[]};
	
	
	<?php
	for ($i = 3; $i < count($pieces); $i++) {
		?>
		country.names.push('<?php echo $pieces[$i]; ?>');
		<?php
	}
	?>
	countries.push(country);
	
	loader.add(country.shortName, 'countries/' + country.shortName + '.png');
	
	<?php
}
fclose($file);

$idsInvisible = array();

for ($i = 0; $i < $invisibleCount; $i ++) {
	array_push($idsInvisible, rand(0, $count-1));
}

$idInvisible = rand(0, $count-1);
?>
idsInvisible = [];
var invisibleCount = <?php echo $invisibleCount; ?>;

<?php

for ($i = 0; $i < $invisibleCount; $i ++) {
	?>
	idsInvisible.push(<?php echo $idsInvisible[$i]; ?>);
	<?php
}
?>

<?php

for ($i = 0; $i < $invisibleCount; $i++) {
	$idInvisible = $idsInvisible[$i];
	$req = $bdd->prepare('SELECT COUNT(*) AS C FROM gData  WHERE country = ' . $idInvisible);
	$req->execute();
	$data = $req->fetch();

	if ($data['C'] >= 5) {
		$req = $bdd->prepare('SELECT AVG(time) AS A FROM gData WHERE country = ' . $idInvisible . ' AND done = 1');
		$req->execute();
		$data = $req->fetch();
		?>
		initTimes.push(<?php echo intval($data['A']) + 5; ?>);
		<?php
	}
	else {
		?>
		initTimes.push(120);
		<?php
	}
}

?>

idInvisible = idsInvisible[0];
time = initTimes[0];
document.getElementById("timeLeft").innerHTML = time + "s";

loader.once('complete', onAssetsLoaded);
loader.load();

var ggTextStyle = {
    font : 'bold italic 72px Verdana',
    fill : '#65ce53',
    stroke : '#b6e8ae',
    strokeThickness : 5,
    dropShadow : false,
    dropShadowColor : '#000000',
    dropShadowAngle : Math.PI / 6,
    dropShadowDistance : 6,
    wordWrap : false,
    wordWrapWidth : 440
};

var ripTextStyle = {
    font : 'bold 50px Verdana',
    fill : '#ff2e27',
    stroke : '#ffa9a6',
    strokeThickness : 5,
    dropShadow : false,
    dropShadowColor : '#000000',
    dropShadowAngle : Math.PI / 6,
    dropShadowDistance : 6,
    wordWrap : false,
    wordWrapWidth : 440,
	align:"center"
};

var ggText = new PIXI.Text('Well done !', ggTextStyle);
ggText.y = renderer.height/2 - 100;
ggText.visible = false;

var ripText = new PIXI.Text('Timeout !\nThe answer was :\nYOLO', ripTextStyle);
ripText.x = renderer.width/2 - 250;
ripText.y = renderer.height/2 - 300;
ripText.visible = false;

stage.addChild(ggText);
stage.addChild(ripText);

var timer;

function onAssetsLoaded() {
	for (var i = 0; i < countries.length; i++) { 
		var texture = PIXI.Texture.fromImage('countries/' + countries[i].shortName + '.png');
		var cou = new PIXI.Sprite(texture);
		
		countries[i].sprite = cou;
		countries[i].spriteX = countries[i].x * scale;
		countries[i].spriteY = - (countries[i].y * scale + texture.height);

		cou.position.x = countries[i].spriteX;
		cou.position.y = countries[i].spriteY;
		
		if (i == idInvisible) {
			cou.visible = false;
		}
		
		group.addChild(cou);
	}
	timer = setInterval(decreaseTime, 1000);
	stage.addChild(group);
	
	group.scale.x = scale2;
	group.scale.y = scale2;
	
	group.position.x = shiftX;
	group.position.y = shiftY;
}

function decreaseTime() {
	time --;
	document.getElementById("timeLeft").innerHTML = time + "s";
	
	if (time == 0) {
		changeMode(3);
	}
}

function checkCountry() {
	var input = document.getElementById("countryName").value.toLowerCase();
	for (var i = 0; i < countries[idInvisible].names.length; i++) {
		if (input == countries[idInvisible].names[i].toLowerCase().replace("_", " ").replace("_", " ").replace("_", " ").replace("_", " ")) {
			changeMode(2);
		}
	}
}

function changeMode(newMode) {
	mode = newMode;
	if (mode == 0) {
		
	}
	else if (mode == 1) {
		ggText.visible = false;
		ripText.visible = false;
		group.visible = true;
		
		countries[idInvisible].sprite.visible = true;
		
		currentIndexInvisible++;
		idInvisible = idsInvisible[currentIndexInvisible];
		time = initTimes[currentIndexInvisible]+1;
		countries[idInvisible].sprite.visible = false;
		
		document.getElementById("countryName").value = "";
		timer = setInterval(decreaseTime, 1000);
		decreaseTime();
	}
	else if (mode == 2) {
		clearInterval(timer);
		
		done.push(true);
		times.push(time);
		group.visible = false;
		ggText.visible = true;
		ggText.x = renderer.width/2 - textOffset;
	}
	else if (mode == 3) {
		clearInterval(timer);
		
		ripText.text = 'Timeout !\nThe answer was :\n' + countries[idsInvisible[currentIndexInvisible]].names[0];
		
		done.push(false);
		times.push(time);
		group.visible = false;
		ggText.visible = false;
		ripText.visible = true;
		ggText.x = renderer.width/2 - textOffset*2;
	}
}

function mouseWheelHandler(event) {
	var delta = Math.max(-1, Math.min(1, (event.wheelDelta || -event.detail)));
	
	if ((event.wheelDelta || -event.detail) > 0) {
		scale2 *= zoomSpeed;
		
		group.scale = new PIXI.Point(scale2, scale2);
		
		group.position.x -= event.offsetX;
		group.position.y -= event.offsetY;
		
		group.position.x *= zoomSpeed;
		group.position.y *= zoomSpeed;
		
		group.position.x += event.offsetX;
		group.position.y += event.offsetY;
	}
	else {
		scale2 /= zoomSpeed;
		
		group.scale = new PIXI.Point(scale2, scale2);
		
		group.position.x -= event.offsetX;
		group.position.y -= event.offsetY;
		
		group.position.x /= zoomSpeed;
		group.position.y /= zoomSpeed;
		
		group.position.x += event.offsetX;
		group.position.y += event.offsetY;
	}
}

function onDragStart(event) {
    if (!this.dragging) {
        this.data = event.data;
        this.dragging = true;
        this.dragPoint = event.data.getLocalPosition(this.parent);
        this.dragPoint.x -= this.position.x;
        this.dragPoint.y -= this.position.y;
    }
}

function onDragEnd() {
    if (this.dragging) {
        this.dragging = false;
        this.data = null;
    }
}

function onDragMove() {
    if (this.dragging) {
        var newPosition = this.data.getLocalPosition(this.parent);
        this.position.x = newPosition.x - this.dragPoint.x;
        this.position.y = newPosition.y - this.dragPoint.y;
    }
}

function sendData() {
	var strId = "";
	for (var i = 0; i < invisibleCount-1; i++) {
		strId += idsInvisible[i] + "_";
	}
	strId += idsInvisible[invisibleCount-1];
	
	var strDone = "";
	for (var i = 0; i < invisibleCount-1; i++) {
		if (done[i]) {
			strDone += '1_';
		}
		else {
			strDone += '0_';
		}
	}
	if (done[invisibleCount-1]) {
		strDone += '1';
	}
	else {
		strDone += '0';
	}
	
	var strTime = "";
	for (var i = 0; i < invisibleCount-1; i++) {
		strTime += (initTimes[i] - times[i]) + "_";
	}
	strTime += (initTimes[invisibleCount-1] - times[invisibleCount-1]);
	window.location.replace('endG1.php?country=' + strId + '&done=' + strDone + '&time=' + strTime);
	clearInterval(timer);
}
// start animating
animate();
function animate() {
    requestAnimationFrame(animate);
	
	if (mode == 2 || mode == 3) {
		ggText.position.x += textSpeed;
		if (ggText.position.x + textWidth >= renderer.width/2 + textOffset) {
			if (currentIndexInvisible < invisibleCount-1) {
				changeMode(1);
			}
			else {
				mode = 4;
				sendData();
			}
		}
	}
	
	renderer.render(stage);
}

</script>
</body>
</html>