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

<div id="bgpopup" onClick="hidePopup()">
</div>
<div id="popupGoToRegion" class="popup">
    <p class="bigText" id="textName">Uncharted Land</p>
    <p id="textOwner">Owner : darkou </p>
    <br>
    <button id="goToRegionButton" class="niceButton greenButton" onclick="goToRegion()">Go to region</button>
    <p> </p>
    <p> </p>
</div>
<script src="snap/dist/snap.js"></script>
<div id="paper">
    <svg id="svg" version="1.1" xmlns="http://www.w3.org/2000/svg" style="background: #96acdc"><desc></desc><defs></defs>
    <?
    $cou = count(getTerrainsList()) - 1;
    for($i = 1; $i <=$cou; $i++) {
        echo file_get_contents("resources/map/" . $i);
    }
    echo file_get_contents("resources/map/regionContour");
    ?>
    </svg>
</div>
<script>
var windowShare = 1;
var stageShare = 0.9;
var popupShareX = 0.5;
var popupShareY = 0.4;
var popupOffsetX = 0.25;
var popupOffsetY = 0.2;

var scaleFactor = 1.05;
var movingZone = 0.1;
var moveSpeed = 20;
var zoomSpeed = 1.1;

var hexaWidth = <? echo getHexaWidth(); ?>;
var hexaHeight = <? echo getHexaHeight(); ?>;

var rectWidth = <? echo getRegionWidth() * 3 / 4; ?> * hexaWidth;
var rectHeight = <? echo getRegionHeight(); ?> * hexaHeight;

var paperWidth = window.innerWidth * windowShare;
var paperHeight = window.innerHeight * windowShare;


var s = Snap("#svg");

var paper = document.getElementById("svg");
if (paper.addEventListener) {
	paper.addEventListener("mousewheel", mouseWheelHandler, false);
	paper.addEventListener("DOMMouseScroll", mouseWheelHandler, false);
}
else {
	paper.attachEvent("onmousewheel", mouseWheelHandler);
}
paper.setAttribute("width", paperWidth + 'px');
paper.setAttribute("height", (paperHeight-50) + 'px');
document.getElementById("paper").style.width = paperWidth + 'px';
document.getElementById("paper").style.height = (paperHeight-50) + 'px';

var svgX = paper.getBoundingClientRect().left;
var svgY = paper.getBoundingClientRect().top;

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

<?
for($i = 1; $i <=$cou; $i++) {
    ?>
    var el = Snap.select("#path<? echo $i; ?>");
    group.append(el);
    <?
}
?>

var width = group.getBBox().w;
var height = group.getBBox().h;
var scaleX = paperWidth * stageShare / width;
var scaleY = (paperHeight-50) * stageShare / height;
var scale = Math.min(scaleX, scaleY);

var t = new Snap.Matrix();
t.scale(scale);
t.translate((paperWidth - scale * width) / (2 * scale), ((paperHeight-50) - scale * height) / (2 * scale));
group.transform(t);

window.requestAnimationFrame(draw);

var clickedRegionId = 0;

//------------------------------------------------------------------------
//PopUp
//------------------------------------------------------------------------

var bgPopup = document.getElementById("bgpopup");
var popupGoToRegion = document.getElementById("popupGoToRegion");
var goToRegionButton = document.getElementById("goToRegionButton");

function hidePopup() {
    bgPopup.style.visibility = "hidden";
    popupGoToRegion.style.visibility = "hidden";
    goToRegionButton.style.transitionDuration = "0s";
}

function setPopupGoToRegionVisible() {
    bgPopup.style.visibility = "visible";
    popupGoToRegion.style.visibility = "visible";
    goToRegionButton.style.transitionDuration = "0.4s";
}

function goToRegion() {
    window.location = 'changeRegion.php?id=' + clickedRegionId;
}

//------------------------------------------------------------------------
//Global Images
//------------------------------------------------------------------------

var contours = [];
<?
$req = $bdd->prepare('SELECT cRegions.id AS id, cRegions.name AS name, cUsers.primaryColor AS color, cUsers.pseudo AS pseudo FROM cRegions LEFT JOIN cUsers ON cRegions.owner = cUsers.id');
$req->execute(array());
while($data = $req->fetch()) {
    ?>
    var x = <? echo getRegionX($data['id']); ?>;
    var y = <? echo getRegionY($data['id']); ?>;
    var id = <? echo $data['id']; ?>;
    var color = <? echo "'#" . nullIsZero($data['color']) . "'"; ?>;
    var pseudo = <? echo "'" . nullIs($data['pseudo'], "None") . "'"; ?>;
    var name = <? echo "'" . $data['name'] . "'"; ?>;
    
    loadRegion(id, x, y, color, pseudo, name);
    <?
}

?>

function loadRegion(id, x, y, color, pseudo, name) {
    var contour = Snap.select("#regionContour").clone();
    t = new Snap.Matrix();
    t.translate(x*rectWidth, y*rectHeight);
    contour.transform(t);
    
    contour.isBeingHovered = false;
    contour.currentScale = 1;
    contour.centerX = x*rectWidth + rectWidth/2;
    contour.centerY = y*rectHeight + rectHeight/2;
    contour.id = id;
    
    contour.name = name;
    contour.pseudo = pseudo;
    
    var redContour = contour.clone();
    contour.redContour = redContour;
    
    group.append(contour);
    group.append(redContour);
    
    if (color != "#0") {
        contour.attr({fill: color, opacity : 0.3});
    }
    
    redContour.attr({opacity : 1, 'fillOpacity' : 0, 'strokeOpacity' : 0, stroke: 'red', 'strokeWidth': "1px", "pointerEvents": "none"});

    contours.push(contour);
    
    contour.hover(function(){
        contour.isBeingHovered = true;
    }, function() {
        contour.isBeingHovered = false;
    });
    
    contour.click(function(){
        document.getElementById("textName").innerHTML = contour.name;
        document.getElementById("textOwner").innerHTML = "Owner : " + contour.pseudo;
        setPopupGoToRegionVisible();
        clickedRegionId = contour.id;
    });
}

//------------------------------------------------------------------------
//Draw
//------------------------------------------------------------------------

function draw() {
    window.requestAnimationFrame(draw);
    
    for (var i = 0; i < contours.length; i++) {
        if (contours[i].isBeingHovered && contours[i].currentScale <= 0.99999999999999) {
            group.append(contours[i].redContour);
            
            contours[i].currentScale *= scaleFactor;
            
            t = new Snap.Matrix();
            t.scale(scaleFactor, scaleFactor, contours[i].centerX, contours[i].centerY);
            t.add(contours[i].redContour.transform().localMatrix);
            contours[i].redContour.transform(t);
            
            contours[i].redContour.attr({"strokeOpacity" : contours[i].currentScale});
        }
        else if (!contours[i].isBeingHovered && contours[i].currentScale > 0.5){
            contours[i].currentScale /= scaleFactor;
            
            t = new Snap.Matrix();
            t.scale(1/scaleFactor, 1/scaleFactor, contours[i].centerX, contours[i].centerY);
            t.add(contours[i].redContour.transform().localMatrix);
            contours[i].redContour.transform(t);
            
            contours[i].redContour.attr({"strokeOpacity" : 0});
        }
    }
    
    if (left.isDown || ak.isDown){
        left.press();
    }
    
    if (right.isDown || dk.isDown){
        right.press();
    }
    
    if (up.isDown || wk.isDown){
        up.press();
    }
    
    if (down.isDown || sk.isDown){
        down.press();
    }
}

function moveGroup(x, y) {
    t = new Snap.Matrix();
    t.translate(x * moveSpeed, y * moveSpeed);
    t.add(group.transform().localMatrix);
    group.transform(t);
}

//------------------------------------------------------------------------
//Mouse
//------------------------------------------------------------------------

var mousePos;

document.getElementById("svg").onmousemove = (function(event) {
    mousePos = {
        x: event.offsetX,
        y: event.offsetY
    };
});

//------------------------------------------------------------------------
//Keyboard
//------------------------------------------------------------------------

var left = keyboard(37);
var ak = keyboard(65);

ak.press = left.press = function() {
    moveGroup(1, 0);
};

var right = keyboard(39);
var dk = keyboard(68);

dk.press = right.press = function() {
    moveGroup(-1, 0);
};

var up = keyboard(38);
var wk = keyboard(87);

wk.press = up.press = function() {
    moveGroup(0, 1);
};

var down = keyboard(40);
var sk = keyboard(83);

sk.press = down.press = function() {
    moveGroup(0, -1);
};


function keyboard(keyCode) {
  var key = {};
  key.code = keyCode;
  key.isDown = false;
  key.isUp = true;
  key.press = undefined;
  key.release = undefined;
  //The `downHandler`
  key.downHandler = function(event) {
    if (event.keyCode === key.code) {
      key.isDown = true;
      key.isUp = false;
    }
    event.preventDefault();
  };

  //The `upHandler`
  key.upHandler = function(event) {
    if (event.keyCode === key.code) {
      key.isDown = false;
      key.isUp = true;
    }
    event.preventDefault();
  };

  //Attach event listeners
  window.addEventListener(
    "keydown", key.downHandler.bind(key), false
  );
  window.addEventListener(
    "keyup", key.upHandler.bind(key), false
  );
  return key;
}

//------------------------------------------------------------------------
//Wheel
//------------------------------------------------------------------------

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.scale(zoomSpeed, zoomSpeed, event.pageX-svgX, event.pageY-svgY);
        t.add(group.transform().localMatrix);
        group.transform(t);
	}
	else {
		var t = new Snap.Matrix();
        t.scale(1/zoomSpeed, 1/zoomSpeed, event.pageX-svgX, event.pageY-svgY);
        t.add(group.transform().localMatrix);
        group.transform(t);
	}
}
</script>
<?php include("bottom.php"); ?>