<?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>
    </svg>
</div>
<script>
var windowShare = 1;
var popupShareX = 0.5;
var popupShareY = 0.4;
var popupOffsetX = 0.25;
var popupOffsetY = 0.2;
var regionImageSize = 30;
var scaleFactor = 1.15;
var movingZone = 0.1;
var moveSpeed = 20;
var zoomSpeed = 1.1;

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();

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 rects = [];
var globalImage = s.image('resources/globalFinal.png', 0, 0, 300, 300);
group.append(globalImage);

var globalImageHD = s.image('resources/global.png', 0, 0, 300, 300);
group.append(globalImageHD);
<?
$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 rect = s.rect(x*regionImageSize, y*regionImageSize, regionImageSize, regionImageSize);
    rect.isBeingHovered = false;
    rect.currentScale = 1;
    rect.centerX = x*regionImageSize + regionImageSize/2;
    rect.centerY = y*regionImageSize + regionImageSize/2;
    rect.id = id;
    
    rect.name = name;
    rect.pseudo = pseudo;
    
    var redRect = s.rect(x*regionImageSize + regionImageSize/3, y*regionImageSize + regionImageSize/3, regionImageSize/3, regionImageSize/3);
    rect.redRect = redRect;
    
    group.append(rect);
    group.append(redRect);
    
    if (color != "#0") {
        rect.attr({fill: color, 'fillOpacity' : 0.3, "strokeOpacity" : 0});
    }
    else {
        rect.attr({'fillOpacity' : 0, "strokeOpacity" : 0});
    }
    
    redRect.attr({ stroke: 'red', 'strokeWidth': "0.5px", 'fillOpacity' : 0, "strokeOpacity" : 0, "pointerEvents": "none"});

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

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

function draw() {
    window.requestAnimationFrame(draw);
    
    for (var i = 0; i < rects.length; i++) {
        if (rects[i].isBeingHovered && rects[i].currentScale < 3.2) {
            group.append(rects[i].redRect);
            
            rects[i].currentScale *= scaleFactor;
            
            t = new Snap.Matrix();
            t.scale(scaleFactor, scaleFactor, rects[i].centerX, rects[i].centerY);
            t.add(rects[i].redRect.transform().localMatrix);
            rects[i].redRect.transform(t);
            
            rects[i].redRect.attr({"strokeOpacity" : 1});
        }
        else if (!rects[i].isBeingHovered && rects[i].currentScale > 1){
            rects[i].currentScale /= scaleFactor;
            
            t = new Snap.Matrix();
            t.scale(1/scaleFactor, 1/scaleFactor, rects[i].centerX, rects[i].centerY);
            t.add(rects[i].redRect.transform().localMatrix);
            rects[i].redRect.transform(t);
            
            rects[i].redRect.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"); ?>