<!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">
    <svg id="svg" version="1.1" xmlns="http://www.w3.org/2000/svg" style="background: #96acdc"><desc>Created with Snap</desc><defs></defs></svg>
</div>
<div id="interface">
	<p class="important"> Enter the missing country's name : </p>
	<input id="countryName" type="text" name="countryName" class="answerInput" onInput="checkCountryName()">
	<p id="timeLeft" class="important"> 120s </p>
</div>
<script src="Snap.svg-0.4.1\dist\snap.svg-min.js"></script>
<script>

var zoomSpeed = 1.1;
var windowShare = 0.8;
var stageShare = 0.9;

<?php

$hiddenCount = 1;

?>

var s = Snap("#svg");

var can = document.getElementById("svg");
if (can.addEventListener) {
	can.addEventListener("mousewheel", mouseWheelHandler, false);
	can.addEventListener("DOMMouseScroll", mouseWheelHandler, false);
}
else {
	can.attachEvent("onmousewheel", mouseWheelHandler);
}
can.setAttribute("width", window.innerWidth * windowShare + 'px');
can.setAttribute("height", window.innerHeight * windowShare + 'px');
var svgX = can.getBoundingClientRect().left;
var svgY = can.getBoundingClientRect().top;

var countries = [];

var group = s.g();
s.append(group);
group.drag();

//group.attr({ visibility: "hidden"});

var currentIndexHidden = -1;
var count = 0;
var timer;
var time = 120;
var mode = 0; 
//0 -> loading
//1 -> game
//2 -> gg
//3 -> perdu
//4 -> sending data

<?php
include("connectServer.php");

//World generation
$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);
	
	var cou = Snap.load("countries-svg/<?php echo $shortName; ?>.svg", function (f) {
        f.selectAll("path").attr({style : "fill:#edae7f;fill-opacity:1;stroke:#ffffff;stroke-width:1.5"});
        
        var newGroup = s.g();
        
        newGroup.append(f);
        
        countries[<?php echo $count-1; ?>].path = newGroup;
        
        group.append(newGroup);
        count ++;
        
        checkAllLoaded();
    });
    
	
	<?php
}
fclose($file);

//Hidden countries generation
$idsHidden = array();

for ($i = 0; $i < $hiddenCount; $i ++) {
	array_push($idsHidden,$i);//$idsHidden, rand(0, $count-1));
}

?>

var idsHidden = [];
var initTimes = [];
var done = [];
var times = [];
var hiddenCount = <?php echo $hiddenCount; ?>;

<?php

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


<?php

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

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

?>

function checkAllLoaded() {
    if (count == <?php echo $count; ?>) {
        var scale = (window.innerWidth * windowShare) / (group.getBBox().w / stageShare);
        var shiftX = ((window.innerWidth * windowShare) - (scale * group.getBBox().w)) / 2;
        var shiftY = ((window.innerHeight * windowShare) - (scale * group.getBBox().h)) / 2;

        var t = new Snap.Matrix();
        t.translate(-0.418352872133255*scale, -14.894396781921387*scale); // base offset
        t.scale(scale);
        t.translate(shiftX/scale, shiftY/scale);
        group.transform(t);
        
        changeMode(1);
    }
}

function nextCountry() {
    document.getElementById("countryName").focus();
    setVisibility("visible");
    
    currentIndexHidden++;
    
    if (currentIndexHidden >= hiddenCount) {
        sendData();
    }
    else {
        countries[idsHidden[currentIndexHidden]].path.attr({ visibility: "hidden" });
        time = initTimes[currentIndexHidden]+1;
        decreaseTime();
    }
}

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

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

function setVisibility(str) {
    for (var i = 0; i < countries.length; i++) {
		countries[i].path.attr({ visibility: str });
	}
}

function changeMode(newMode) {
	mode = newMode;
	if (mode == 0) {
		
	}
	else if (mode == 1) {
		nextCountry();
		
		document.getElementById("countryName").value = "";
        clearInterval(timer);
		timer = setInterval(decreaseTime, 1000);
	}
	else if (mode == 2) {
		clearInterval(timer);
		
		done.push(true);
		times.push(time);
        
        setVisibility("hidden");
        
        animateGGText();
	}
	else if (mode == 3) {
		clearInterval(timer);
		
		done.push(false);
		times.push(time);
        
        setVisibility("hidden");
        
        animateRIPText();
	}
}

function sendData() {
	var strId = "";
	for (var i = 0; i < hiddenCount-1; i++) {
		strId += idsHidden[i] + "_";
	}
	strId += idsHidden[hiddenCount-1];
	
	var strDone = "";
	for (var i = 0; i < hiddenCount-1; i++) {
		if (done[i]) {
			strDone += '1_';
		}
		else {
			strDone += '0_';
		}
	}
	if (done[hiddenCount-1]) {
		strDone += '1';
	}
	else {
		strDone += '0';
	}
	
	var strTime = "";
	for (var i = 0; i < hiddenCount-1; i++) {
		strTime += (initTimes[i] - times[i]) + "_";
	}
	strTime += (initTimes[hiddenCount-1] - times[hiddenCount-1]);
	window.location.replace('endG1.php?country=' + strId + '&done=' + strDone + '&time=' + strTime);
	clearInterval(timer);
}

function animateGGText() {
    var timing = 3000;
    var ggText = s.text(window.innerWidth * windowShare / 2, window.innerHeight * windowShare / 2, "Well done !").attr({font: '120px Verdana', opacity: 0, fill: "#94da92", stroke: "white", "text-anchor": "middle" });

    setTimeout(function() {

            Snap.animate(0, 1, function(value) { 
                ggText.attr({ 'font-size': value * 100,  opacity: Math.sqrt(value) });
            }, 
            timing, 
            Math.sqrt, 
            function() {
                ggText.remove();
                changeMode(1);
            } );
        }
    ,0)
}

function animateRIPText() {
    var timing = 3000;
    var att = {font: '100px Verdana', opacity: 0, fill: "#cb6666", stroke: "white", "text-anchor": "middle" };
    var ripText1 = s.text(window.innerWidth * windowShare / 2, window.innerHeight * windowShare / 2 - 250, "Timeout !").attr(att);
    var ripText2 = s.text(window.innerWidth * windowShare / 2, window.innerHeight * windowShare / 2 - 125, "The answer was :").attr(att);
    var ripText3 = s.text(window.innerWidth * windowShare / 2, window.innerHeight * windowShare / 2, "Botswana").attr(att);
    
    var textGroup = s.group(ripText1, ripText2, ripText3);

    setTimeout(function() {

            Snap.animate(0, 1, function(value) { 
                ripText1.attr({opacity: 0.2 + Math.sqrt(value) * 0.8 });
                ripText2.attr({opacity: 0.2 + Math.sqrt(value) * 0.8 });
                ripText3.attr({opacity: 0.2 + Math.sqrt(value) * 0.8 });
                
                var t = new Snap.Matrix();
                t.translate(window.innerWidth * windowShare / 2, window.innerHeight * windowShare / 2 - 125);
                t.rotate(0.05);
                t.translate(-window.innerWidth * windowShare / 2, -window.innerHeight * windowShare / 2 + 125);
                t.add(textGroup.transform().localMatrix);
                textGroup.transform(t);
            }, 
            timing, 
            Math.abs, 
            function() {
                ripText1.remove();
                ripText2.remove();
                ripText3.remove();
                changeMode(1);
            } );
        }
    ,100)
}

function mouseWheelHandler(event) {
	var delta = Math.max(-1, Math.min(1, (event.wheelDelta || -event.detail)));
	
	if ((event.wheelDelta || -event.detail) > 0) {
        var t = new Snap.Matrix();
        t.translate(event.pageX-svgX, event.pageY-svgY);
        t.scale(zoomSpeed);
        t.translate(-event.pageX+svgX, -event.pageY+svgY);
        t.add(group.transform().localMatrix);
        group.transform(t);
	}
	else {
		var t = new Snap.Matrix();
        t.translate(event.pageX-svgX, event.pageY-svgY);
        t.scale(1/zoomSpeed);
        t.translate(-event.pageX+svgX, -event.pageY+svgY);
        t.add(group.transform().localMatrix);
        group.transform(t);
	}
}

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