<?
include("top.php");
?>

<body>
<script src="snap/dist/snap.js"></script>
<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>

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

<?php

$hiddenCount = 10;

?>

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;
$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, 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 . ' AND game = ' . $game);
	$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 AND game = ' . $game);
		$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.scale(scale);
        <?
        if ($reverse) {
            ?>
            t.rotate(180);
            t.translate(-group.getBBox().w, -group.getBBox().h);
            t.translate(-shiftX/scale, -shiftY/scale);
            <?
        }
        else {
            ?>
            t.translate(shiftX/scale, shiftY/scale);
            <?
        }
        ?>
        
        t.translate(-0.418352872133255, -14.894396781921387); // base offset
        
        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() {
    if (mode == 1) {
        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(countries[idsHidden[currentIndexHidden]].names[0].replace("_", " ").replace("_", " "));
	}
}

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('insertData.php?game=<?php echo $game; ?>&country=' + strId + '&done=' + strDone + '&time=' + strTime);
	clearInterval(timer);
}

<?
include("ggOrRip.php");
?>

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>