<?
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 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.7;

<?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 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");

//Read file
$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);
    
	
	<?php
}
fclose($file);

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

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

for ($i = 0; $i < count($idsHidden); $i ++) {
	?>
    
    var cou = Snap.load("countries-svg/"<?php echo ' + countries[' . $idsHidden[$i] . '].shortName + '; ?>".svg", function (f) {
        
        var newGroup = s.g();
        
        newGroup.append(f);
        
        <?
        if (!$rotated) {
            ?>
            var width = newGroup.getBBox().w;
            var height = newGroup.getBBox().h;
            var scaleX = window.innerWidth * windowShare * stageShare / width;
            var scaleY = window.innerHeight * windowShare * stageShare / height;
            var scale = Math.min(scaleX, scaleY);
            
            newGroup.selectAll("path").attr({style : "fill:#edae7f;fill-opacity:1;stroke:#ffffff;stroke-width:" + (15 / scale)});
            console.log(countries[<?php echo $idsHidden[$i]; ?>].names[0] + " : " + (15 / scale));
            
            var t = new Snap.Matrix();
            t.scale(scale);
            t.translate(-countries[<?php echo $idsHidden[$i]; ?>].x, -(-countries[<?php echo $idsHidden[$i]; ?>].y-height + 417) - 16);
            t.translate((window.innerWidth * windowShare - scale * width) / (2 * scale), (window.innerHeight * windowShare - scale * height) / (2 * scale));
            newGroup.transform(t);
            <?
        }
        else {
            ?>
            var angle = Math.random() * 360;
            var rad = angle * Math.PI / 180.0;
        
            var x1 = newGroup.getBBox().x * Math.cos(rad) - newGroup.getBBox().y * Math.sin(rad);
            var y1 = newGroup.getBBox().x * Math.sin(rad) + newGroup.getBBox().y * Math.cos(rad);
            
            var x2 = newGroup.getBBox().x * Math.cos(rad) - newGroup.getBBox().y2 * Math.sin(rad);
            var y2 = newGroup.getBBox().x * Math.sin(rad) + newGroup.getBBox().y2 * Math.cos(rad);
            
            var x3 = newGroup.getBBox().x2 * Math.cos(rad) - newGroup.getBBox().y * Math.sin(rad);
            var y3 = newGroup.getBBox().x2 * Math.sin(rad) + newGroup.getBBox().y * Math.cos(rad);
            
            var x4 = newGroup.getBBox().x2 * Math.cos(rad) - newGroup.getBBox().y2 * Math.sin(rad);
            var y4 = newGroup.getBBox().x2 * Math.sin(rad) + newGroup.getBBox().y2 * Math.cos(rad);
            
            
            
            var xMin = Math.min(x1, x2, x3, x4);
            var xMax = Math.max(x1, x2, x3, x4);
            
            var yMin = Math.min(y1, y2, y3, y4);
            var yMax = Math.max(y1, y2, y3, y4);
        
        
            var width = newGroup.getBBox().w;
            var height = newGroup.getBBox().h;
            var scaleX = window.innerWidth * windowShare * stageShare / width;
            var scaleY = window.innerHeight * windowShare * stageShare / height;
            var scale = Math.min(scaleX, scaleY); // scale for stroke width
            
            newGroup.selectAll("path").attr({style : "fill:#edae7f;fill-opacity:1;stroke:#ffffff;stroke-width:" + (15 / scale)});
            
             var rWidth = xMax - xMin;
            var rHeight = yMax - yMin;
            var scaleX = window.innerWidth * windowShare * stageShare / rWidth;
            var scaleY = window.innerHeight * windowShare * stageShare / rHeight;
            var scale = Math.min(scaleX, scaleY); //'real' scale
            
            var t = new Snap.Matrix();
            t.scale(scale);
            t.translate(-countries[<?php echo $idsHidden[$i]; ?>].x, -(-countries[<?php echo $idsHidden[$i]; ?>].y-height + 417) - 16);
            t.translate((window.innerWidth * windowShare - scale * width) / (2 * scale), (window.innerHeight * windowShare - scale * height) / (2 * scale));
            newGroup.transform(t);
            
            var t = new Snap.Matrix();
            t.rotate(angle, window.innerWidth * windowShare / 2, window.innerHeight * windowShare / 2);
            t.add(newGroup.transform().localMatrix);
            newGroup.transform(t);
            <?
        }
        ?>
        newGroup.attr({ visibility: "hidden" });
        
        countries[<?php echo $idsHidden[$i]; ?>].path = newGroup;
        newGroup.drag();
        s.append(newGroup);
        count ++;
        
        checkAllLoaded();
    });
    
    <?php
}

?>


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(15);
		<?php
	}
}

?>


function checkAllLoaded() {
    if (count == <?php echo $hiddenCount; ?>) {
        changeMode(1);
    }
}

function nextCountry() {
    document.getElementById("countryName").focus();
    setVisibility("hidden");
    
    currentIndexHidden++;
    
    if (currentIndexHidden >= hiddenCount) {
        sendData();
    }
    else {
        countries[idsHidden[currentIndexHidden]].path.attr({ visibility: "visible" });
        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++) {
        if (typeof countries[i].path !== 'undefined') {
            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(countries[idsHidden[currentIndexHidden]].path.transform().localMatrix);
        countries[idsHidden[currentIndexHidden]].path.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(countries[idsHidden[currentIndexHidden]].path.transform().localMatrix);
        countries[idsHidden[currentIndexHidden]].path.transform(t);
	}
}

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