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

$buildings = getBuildingsList();
$resources = getResourcesList();
$terrains = getTerrainsList();

$regionResources = simulate($_SESSION['regionId']);
?>
<div id="bgpopup" onClick="hidePopup()">
</div>
<div id="popUpResources" class="popup">
    <p class="bigText"> Resources </p>
    <table class="tab">
    
    <?
    $regionResources["all"] = [];
    
    foreach ($regionResources["current"] as $key => $amount) {
        $regionResources["all"][$key] = true;
    }
    foreach ($regionResources["gained"] as $key => $amount) {
        $regionResources["all"][$key] = true;
    }
    foreach ($regionResources["populationConsumption"] as $key => $amount) {
        $regionResources["all"][$key] = true;
    }
    
    //Trade gains
    $regionResources["tradeGains"] = [];
    $req = $bdd->prepare('SELECT * FROM cTransports WHERE regionEnd = ?');
    $req->execute(array($_SESSION['regionId']));

    while ($data = $req->fetch()) {
        $regionResources["tradeGains"][$data['resource']] += $data['amount'] / (2 * $data['time']);
    }
    
    $req = $bdd->prepare('SELECT * FROM cTransports WHERE regionStart = ?');
    $req->execute(array($_SESSION['regionId']));

    while ($data = $req->fetch()) {
        $regionResources["tradeGains"][$data['resource']] -= $data['amount'] / (2 * $data['time']);
    }
    
    foreach ($regionResources["all"] as $key => $useless) {
        
        $txt = "<tr><td> " . $resources[$key]["longName"] . "</td>";
        $txt = $txt . "<td> " . intval($regionResources["current"][$key]) . " tons</td>";
        $txt = $txt . "<td>" . prodPerHour($regionResources["gained"][$key] + $regionResources["populationConsumption"][$key] + $regionResources["tradeGains"][$key]) . " tons/h</td></tr>";
        
        echo $txt;
    }
    ?>
    
    </table>
</div>
<div id="popUpInfluence" class="popup">
    <p class="bigText"> Influence </p>
    <table class="tab">
    
    <?
    $regionResources["all"] = [];
    
    foreach ($regionResources["currentInfluences"] as $key => $amount) {
        $regionResources["all"][$key] = true;
    }
    foreach ($regionResources["gainedInfluences"] as $key => $amount) {
        $regionResources["all"][$key] = true;
    }
    
    $txt = "<th><td> Pseudo </td>";
    $txt = $txt . "<td> Current influence </td>";
    $txt = $txt . "<td> Gains </td></th>";
    
    echo $txt;
    
    foreach ($regionResources["all"] as $key => $useless) {
        
        $txt = "<tr><td></td><td> " . $key . "</td>";
        $txt = $txt . "<td> " . intval($regionResources["currentInfluences"][$key]) . " / 100 </td>";
        $txt = $txt . "<td>" . prodPerHour($regionResources["gainedInfluences"][$key]) . " per hour</td></tr>";
        
        echo $txt;
    }
    ?>
    
    </table>
</div>
<div id="popUpAgriculture" class="popup">
    <p class="bigText"> Agriculture </p>
    <table class="tab">
    
    <?
    
    $txt = "<th><td> Plant </td>";
    $txt = $txt . "<td> Efficiency in this region </td></th>";
    
    echo $txt;
    
    foreach ($regionResources["agricultureEfficiency"] as $key => $ratio) {
        $txt = "<tr><td></td><td> " . $resources[$key]["longName"] . "</td>";
        $txt = $txt . "<td> " . intval($ratio * 100) . " %</td></tr>";
        
        echo $txt;
    }
    ?>
    
    </table>
</div>
<div id="popUpMineral" class="popup">
    <p class="bigText"> Common minerals </p>
    <table class="tab">
    
    <?
    
    $txt = "<th><td> Mineral </td>";
    $txt = $txt . "<td> Efficiency in this region </td></th>";
    
    echo $txt;
    
    foreach ($regionResources["mineralEfficiency"] as $key => $ratio) {
        $txt = "<tr><td></td><td> " . $resources[$key]["longName"] . "</td>";
        $txt = $txt . "<td> " . intval($ratio * 100) . " %</td></tr>";
        
        echo $txt;
    }
    ?>
    
    </table>
</div>
<div id="popUpPopulation" class="popup">
    <p class="bigText"> Population </p>
    <?
    $txt = "<p> Current population : " . $regionResources["population"] . "</p>";
    $txt = $txt . "<p> Population growth : " . addPlus($regionResources["populationGrowth"]) . " per hour</p>";
    echo $txt;
    ?>
    <p class="bigText"> Happiness </p>
    
    <?
    $txt = $txt . "<br>";
    $txt = "<p> Current happiness : " . $regionResources["happiness"] . "%</p>";
    $txt = $txt . "<p> Happiness growth : " . addPlus($regionResources["happinessGrowth"]) . "% per hour</p>";
    echo $txt;
    ?>
</div>
<div id="regionInfo">
</div>
<div id="regionInterface">
    <?
    if ($regionResources['owner'] != 0) {
        ?>
        <button id="resourcesButton" class="niceButton2 greenButton" onclick="displayResources()">Resources</button>
        <?
    }
    else {
        ?>
        <button id="influenceButton" class="niceButton2 greenButton" onclick="displayInfluence()">Influence</button>
        <?
    }
    ?>
    <button id="agricultureButton" class="niceButton2 greenButton" onclick="displayAgriculture()">Agriculture</button>
    <button id="depositsButton" class="niceButton2 greenButton" onclick="displayMinerals()">Minerals</button>
    <button id="ppulationButton" class="niceButton2 greenButton" onclick="displayPopulation()">Population</button>
    
    <form>
        <input type="radio" name="mapMode" value="terrain" checked onchange="setHexaTerrain()">Terrain<br>
        <input type="radio" name="mapMode" value="deposits" onchange="setHexaDeposits()">Deposits<br>
    </form>
</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 stageShare = 0.8;
var popupShareX = 0.5;
var popupShareY = 0.4;
var popupOffsetX = 0.25;
var popupOffsetY = 0.2;

var hexaWidth = 400;
var hexaHeight = 353;
var buildingShareX = 0.6;
var buildingShareY = 0.6;

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

var fluxWidth = 120;
var fluxHeight = 40;
var fluxSpeed = 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';
document.getElementById("main").style.width = paperWidth + 'px';
document.getElementById("main").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);

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

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

function hidePopup() {
    bgPopup.style.visibility = "hidden";
    
    if (popUpVisible != 0) {
        popUpVisible.style.visibility = "hidden";
    }
}

function setPopUpVisible() {
    bgPopup.style.visibility = "visible";
    
    if (popUpVisible != 0) {
        popUpVisible.style.visibility = "visible";
    }
}

function displayResources() {
    popUpVisible = document.getElementById("popUpResources");
    setPopUpVisible();
}

function displayInfluence() {
    popUpVisible = document.getElementById("popUpInfluence");
    setPopUpVisible();
}

function displayAgriculture() {
    popUpVisible = document.getElementById("popUpAgriculture");
    setPopUpVisible();
}

function displayMinerals() {
    popUpVisible = document.getElementById("popUpMineral");
    setPopUpVisible();
}

function displayPopulation() {
    popUpVisible = document.getElementById("popUpPopulation");
    setPopUpVisible();
}

//------------------------------------------------------------------------
//Hexa
//------------------------------------------------------------------------

var hexas = [];
<?

$hexas = [];
for ($i = -1; $i <= 1; $i++) {
    for ($j = -1; $j <= 1; $j++) {
        if (($i == 1 && $j == -1) || ($i == -1 && $j == 1)) {
            //do nothing
        }
        else {
            $regionId = getRegionId(getRegionX($_SESSION['regionId']) + $i, getRegionY($_SESSION['regionId']) + $j);
        
            $req = $bdd->prepare('SELECT cTerritories.id AS ID, cTerritories.type AS TTYPE, cBuildings.type AS BTYPE, cBuildings.production AS PROD, cBuildingConstructions.type AS BCTYPE, cBuildingConstructions.timeFinished AS TIME, cDeposits.resource AS DEPR, cDeposits.concentration AS DEPC FROM cTerritories LEFT JOIN cBuildings on cTerritories.id = cBuildings.territory LEFT JOIN cBuildingConstructions on cTerritories.id = cBuildingConstructions.territory LEFT JOIN cDeposits on cTerritories.id = cDeposits.territory WHERE cTerritories.id >= ? AND cTerritories.id <= ?');
            $req->execute(array(getMinTerritoryId($regionId), getMaxTerritoryId($regionId)));
            while ($data = $req->fetch()) {
                $isBorder = false;
                $isGrayed = true;
                $x = getTerritoryXInRegion($data['ID'], $regionId);
                $y = getTerritoryYInRegion($data['ID'], $regionId);
                
                if ($i == -1 && $j == -1 && $x == getRegionWidth() - 1 && $y == getRegionHeight() - 1) {
                    $isBorder = true;
                }
                else if ($i == -1 && $j == 0 && $x == getRegionWidth() - 1){
                    $isBorder = true;
                }
                else if ($i == -1 && $j == 1){
                    //none
                }
                else if ($i == 0 && $j == -1 && $y == getRegionHeight() - 1){
                    $isBorder = true;
                }
                else if ($i == 0 && $j == 0){
                    $isBorder = true;
                    $isGrayed = false;
                }
                else if ($i == 0 && $j == 1 && $y == 0){
                    $isBorder = true;
                }
                else if ($i == 1 && $j == -1){
                    //none
                }
                else if ($i == 1 && $j == 0 && $x == 0){
                    $isBorder = true;
                }
                else if ($i == 1 && $j == 1 && $x == 0 && $y == 0){
                    $isBorder = true;
                }
                
                if ($isBorder) {
                    $hex = [
                        "id" => $data['ID'],
                        "building" => nullIsZero($data['BTYPE']),
                        "production" => nullIsZero($data['PROD']),
                        "buildingConstruction" => nullIsZero($data['BCTYPE']),
                        "timeFinished" => nullIsZero($data['TIME']),
                        "depositResource" => nullIsZero($data['DEPR']),
                        "terrain" => $data['TTYPE'],
                        "isGrayed" => $isGrayed,
                        "index" => count($hexas)
                    ];
                    
                    $hexas[$data['ID']] = $hex;
                    
                    ?>
                    addHexa(<? echo $data['ID'];?>, 
                            <? echo $x + $i * getRegionWidth();?>, 
                            <? echo $y + $j * getRegionHeight();?>, 
                            <? echo $terrains[$data['TTYPE']]["color"];?>, 
                            <? echo "'" . $terrains[$data['TTYPE']]["longName"] . "'";?>, 
                            <? echo nullIsZero($data['BTYPE']);?>, 
                            <? echo "'" . $buildings[nullIsZero($data['BTYPE'])]['longName'] . "'";?>, 
                            <? echo $resources[nullIsZero($data['DEPR'])]['color'];?>, 
                            <? echo "'" . $resources[nullIsZero($data['DEPR'])]['longName'] . "'";?>, 
                            <? echo nullIsZero($data['DEPC']);?>, 
                            <? if (!$isGrayed) echo "true"; else echo "false";?>);
                    <?
                }
            }
        }
        
    }
}
?>

function addHexa(id, x, y, terrainColor, terrainName, buildingType, buildingName, depositColor, depositName, depositConcentration, interactable) {
    var scaleX = hexaWidth / 400;
    var scaleY = hexaHeight / 353;
    
    var offsetX = hexaWidth * 0.75 * x;
    var offsetY = hexaHeight * y;
    
    if (Math.abs(x) % 2 == 1) {
        offsetY += hexaHeight / 2;
    }
    
    var pol = s.polygon(99 * scaleX + offsetX, 0 * scaleY + offsetY, 299 * scaleX + offsetX, 0 * scaleY + offsetY, 399 * scaleX + offsetX, 176 * scaleY + offsetY, 299 * scaleX + offsetX, 353 * scaleY + offsetY, 99 * scaleX + offsetX, 353 * scaleY + offsetY, 0 * scaleX + offsetX, 176 * scaleY + offsetY);
    pol.attr({ stroke: 'white', 'strokeWidth': "2px", fill: terrainColor});
    pol.isBeingHovered = false;
    pol.currentScale = 1;
    pol.centerX = offsetX + hexaWidth/2;
    pol.centerY = offsetY + hexaHeight/2;
    pol.buildingType = buildingType;
    pol.building = 0;
    
    pol.id = id;
    
    pol.fluxes = [];
    
    pol.terrainColor = terrainColor;
    pol.depositColor = depositColor;
    
    pol.terrainName = terrainName;
    pol.buildingName = buildingName;
    pol.depositName = depositName;
    pol.depositConcentration = depositConcentration;
    
    pol.group = s.g();
    pol.group.append(pol);
    
    if (!interactable) {
        pol.attr({"pointerEvents": "none"});
        
        //var stripe = s.polygon(82 * scaleX + offsetX, 324 * scaleY + offsetY, 99 * scaleX + offsetX, 353 * scaleY + offsetY, 134 * scaleX + offsetX, 353 * scaleY + offsetY, 318 * scaleX + offsetX, 30 * scaleY + offsetY, 299 * scaleX + offsetX, 0 * scaleY + offsetY, 264 * scaleX + offsetX, 0 * scaleY + offsetY);
        var stripe = s.polygon(38 * scaleX + offsetX, 238 * scaleY + offsetY, 63 * scaleX + offsetX, 281 * scaleY + offsetY, 363 * scaleX + offsetX, 107 * scaleY + offsetY, 338 * scaleX + offsetX, 65 * scaleY + offsetY);

        stripe.attr({fill: "#b3c7cb"});
        pol.group.append(stripe);
    }
    
    group.append(pol.group);
    hexas.push(pol);
    
    
    pol.hover(function(){
        pol.isBeingHovered = true;
        var txt = "<p> " + pol.terrainName + "</p>" + "<p> " + pol.buildingName + "</p>";
        if (pol.depositConcentration > 0 ) {
            txt += "<p> " + pol.depositName + " (" + pol.depositConcentration + "%) </p>";
        }
        setInfo(txt);
    }, function() {
        pol.isBeingHovered = false;
        removeInfo();
    });
    
    pol.click(function(){
        popUpVisible = document.getElementById("popupHexa" + pol.id);
        setPopUpVisible();
    });
}

function setHexaTerrain() {
    for (var i = 0; i < hexas.length; i++) {
        hexas[i].attr({fill: hexas[i].terrainColor});
    }
}

function setHexaDeposits() {
    for (var i = 0; i < hexas.length; i++) {
        hexas[i].attr({fill: hexas[i].depositColor});
    }
}

//Center group
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.translate(-group.getBBox().x * scale, -group.getBBox().y * scale);
t.scale(scale);
t.translate((paperWidth - scale * width) / (2 * scale), ((paperHeight-50) - scale * height) / (2 * scale));
group.transform(t);

//------------------------------------------------------------------------
//Buildings
//------------------------------------------------------------------------

<?

foreach($buildings as $index => $building) {
    if ($index != 0) {
        ?>
        var cou = Snap.load("resources/buildings/<? echo $building["shortName"];?>.svg", function (f) {
            var smallGroup = s.g();
            smallGroup.append(f);
            
            smallGroup.attr({"pointerEvents": "none"});
            
            var width = smallGroup.getBBox().w;
            var height = smallGroup.getBBox().h;
            
            var scaleX = hexaWidth * buildingShareX / width;
            var scaleY = hexaHeight * buildingShareY / height;
            var scale = Math.min(scaleX, scaleY);
            
            var t = new Snap.Matrix();
            t.scale(scale);
            smallGroup.transform(t);
            
            for (var i = 0; i < hexas.length; i++) {
                if (hexas[i].buildingType == <? echo $index;?>) {
                    var g = smallGroup.clone();
                    hexas[i].building = g;
                    
                    var t = new Snap.Matrix();
                    t.translate(hexas[i].centerX - (scale * width) / 2, hexas[i].centerY - (scale * height) / 2);
                    t.add(g.transform().localMatrix);
                    g.transform(t);
                    
                    hexas[i].group.append(g);
                }
            }
            
            smallGroup.remove();
        });
        <?
            
    }
}

?>

//------------------------------------------------------------------------
//Building interaction
//------------------------------------------------------------------------

var fluxes = [];
var popUpVisible = 0;
<?

$fluxes = [];
$popUpsHexaTxt = "";
foreach ($hexas as $id => $hex){
    $nei = getNeighbourgs($id);
    
    $txt = "<div class='popup' id='popupHexa" . $id . "'>";
    
    $txt = $txt . "<br>";
    
    if ($hex["building"] != 0) { //buildings pop up
        $txt = $txt . "<p class='bigText'>" . $buildings[$hex["building"]]['longName'] . "</p>";
        
        if ($hex["production"] != 0) {
            $resourceProduced = $resources[$hex['production']]['shortName'];
            
            $page = '"changeProduction.php?territory=' . $id . '&productionIndex="';
            $selectId = '"select' . $id . '"';
            $txt = $txt . "<p> Current production : <select id='select" . $id . "'class='black' onchange='window.location.replace(" . $page . " + document.getElementById(" . $selectId . ").selectedIndex)'>";
            
            $optionIndex = 0;
            $count = 0;
            foreach($buildings[$hex["building"]]["production"] as $key => $resource) {
                $txt = $txt . "<option value='" . $key . "'>" . $resources[$key]["longName"] . "</option>";

                if ($key == $resourceProduced) {
                    $optionIndex = $count;
                }
                $count ++;
            }
            
            $txt = $txt . "</select> " . $buildings[$hex["building"]]["production"][$resourceProduced]['amount'] * $regionResources["buildingsEfficiency"][$id] . " tons/h</p>";

            $txt = $txt . "<script> document.getElementById('select" . $id . "').selectedIndex = " . $optionIndex . "</script>";
            
            $txt = $txt . "<p> Required resources : ";
            
            foreach($buildings[$hex["building"]]["production"][$resourceProduced]['resourcesNeeded'] as $key => $resourceNeeded) {
                $txt = $txt . "<br>" . $resources[$key]['longName'] . " : " . $resourceNeeded . " tons/h";
            }
            
            $txt = $txt . "</p>";
        }
    }
    else if ($hex["buildingConstruction"] != 0) { //construction pop up
        $txt = $txt . "<p>" . $buildings[$hex["buildingConstruction"]]['longName'] . " in construction</p>";
        $txt = $txt . "<p> Time remaining : " . timeToString($hex['timeFinished'] - time(), ", ") . "</p>";
    }
    else { //constructions pop up
        $txt = $txt . "<p>Construct a building : </p>";
    }
    
    $nearTerrains = [];
    $nearBuildings = [];
    foreach ($nei as $idNei) {
        if (array_key_exists($idNei, $hexas)) {
            
            //Near terrain / building
            $nearTerrains[$terrains[$hexas[$idNei]['terrain']]['type']] ++;
            $nearBuildings[$buildings[$hexas[$idNei]['building']]['shortName']] ++;
            
            //Bonus/Malus fluxes
            if ($hex["building"] != 0 && $hexas[$idNei]["building"] != 0) {
                $bonusMalus = buildingBonuses($buildings[$hex["building"]]["color"], $buildings[$hexas[$idNei]["building"]]["color"]);
            
                $val = 0;
                foreach ($bonusMalus as $changes){
                    $val += $changes;
                }
                
                if ($val != 0) {
                    $i = $hex["index"] * count($hexas) + $hexas[$idNei]["index"];
                    $j = $hexas[$idNei]["index"] * count($hexas) + $hex["index"];
                    
                    $txtFlux = "";
                    
                    if ($bonusMalus["production"] != 0) {
                        $txtFlux = $txtFlux . "<p> Building production : " . (addPlus($bonusMalus["production"] * 100)) . " % </p>";
                    }
                    if ($bonusMalus["happiness"] != 0) {
                        $txtFlux = $txtFlux . "<p> Region happiness : " . (addPlus($bonusMalus["happiness"])) . " % </p>";
                    }
                    
                    $fluxes[$i] = [
                        "hexa1" => $hex["index"],
                        "hexa2" => $hexas[$idNei]["index"],
                        "color" => getFluxColor($val),
                        "text" => "'<p>" . $buildings[$hex["building"]]["longName"] . " >> " . $buildings[$hexas[$idNei]["building"]]["longName"] . "</p>" . $txtFlux . "'"
                    ];
                    
                    if (array_key_exists($j, $fluxes)) {
                        $fluxes[$i]["total"] = 2;
                        $fluxes[$j]["total"] = 2;
                    }
                    else {
                        $fluxes[$i]["total"] = 1;
                    }
                }
            }
        }
    }
    
    if ($hex["building"] == 0 && $hex["buildingConstruction"] == 0) {
        $txt = $txt . "<table class='tab'>";
        foreach ($buildings as $key => $building){
            if ($key > 0) {
                if (array_key_exists($terrains[$hex["terrain"]]['type'], $building["construction"]["terrains"])) { // good terrain
                
                    $goodNeiTerrain = true;
                    
                    foreach($building["construction"]["nearTerrains"] as $terr => $amount) {
                        if ($nearTerrains[$terr] < $amount) {
                            $goodNeiTerrain = false;
                        }
                    }
                    
                    $goodNeiBuilding = true;
                    
                    foreach($building["construction"]["nearBuildings"] as $bui => $amount) {
                        if ($nearBuildings[$bui] < $amount) {
                            $goodNeiBuilding = false;
                        }
                    }
                    
                    $txt = $txt . "<tr> <td>" . $building["longName"] . "</td>";
                    $txt = $txt . "<td> " . timeToString($building["construction"]["time"], "<br>") . "</td>";
                    
                    $txt = $txt . "<td> ";
                    $first = true;
                    $enoughResources = true;
                    foreach ($building["construction"]["resources"] as $key2 => $amount){
                        
                        if (!$first) {
                            $txt = $txt . "<br>";
                        }
                        
                        $txt = $txt . $resources[$key2]["longName"] . " : " . $amount . " tons";
                        $first = false;
                        
                        if (resourcesInRegion($_SESSION['regionId'], getResourceId($key2)) < $amount) {
                            $enoughResources = false;
                        }
                    }
                    
                    $txt = $txt . "</td>";
                    
                    if (!$goodNeiTerrain) {
                        $txt = $txt . "<td> <p> Not good adjacent terrains </p> </td>";
                    }
                    else if (!$goodNeiBuilding) {
                        $txt = $txt . "<td> <p> Not good adjacent buildings </p> </td>";
                    } 
                    else if (!$enoughResources) {
                        $txt = $txt . "<td> <p> Not enough resources </p> </td>";
                    }
                    else {
                        $page = '"constructBuilding.php?territory=' . $id . '&building=' . $key . '"';
                        $txt = $txt . "<td> <button onclick='window.location.replace(" . $page . ")'> Construct </button> </td>";
                    }
                    
                    $txt = $txt . "</tr>";
                    
                       
                }
            }
        }
        $txt = $txt . "</table>";
    }        
    
    
    $txt = $txt . "<br>";
    $txt = $txt . "</div>";
    
    if (!$hex['isGrayed']) {
        $popUpsHexaTxt = $popUpsHexaTxt . $txt . "\n";
    }
}

foreach ($fluxes as $id => $flux){
    ?>
    createFlux(<? echo $flux["hexa1"];?>, <? echo $flux["hexa2"];?>, <? echo $flux["color"];?>, <? echo $flux["total"];?>, <? echo $flux["text"];?>);
    <?
}

?>
function createFlux(indexHexa1, indexHexa2, color, total, text) {
    
    var px1 = hexas[indexHexa1].centerX;  //points coordinates
    var px2 = hexas[indexHexa2].centerX;
    var py1 = hexas[indexHexa1].centerY;
    var py2 = hexas[indexHexa2].centerY;
    
    var x = px1 - fluxWidth / 2;
    var y = py1 - fluxHeight / 2;
    
    var g = group.g();
    
    g.arrows = [];
    
    for (var i = 0; i < 4; i++) {
        var arrow = addArrow(x + 30 * i, y, g);
        
        arrow.attr({fill: color});
        arrow.x = 30 * i;
        g.arrows.push(arrow);
    }
    
    var rect = g.rect(x, y, fluxWidth, fluxHeight);
    g.baseRect = rect;
    rect.attr({"fill-opacity": 0});
    
    var angle = 180 + Snap.angle(px1, py1, px2, py2);
    
    var t = new Snap.Matrix();
    t.rotate(angle, x + fluxWidth / 2, y + fluxHeight / 2);
    if (total == 1) {
        t.translate(hexaHeight / 2, 0);
    }
    else {
        t.translate(hexaHeight / 2, - fluxHeight * 0.8);
    }
    
    t.add(g.transform().localMatrix);
    g.transform(t);
    
    g.isBeingHovered = false;
    g.currentScale = 1;
    g.centerX = px1 + Math.cos(Snap.rad(angle)) * hexaHeight / 2;
    g.centerY = py1 + Math.sin(Snap.rad(angle)) * hexaHeight / 2;
    g.hover(function(){
        g.isBeingHovered = true;
        setInfo(g.text)
    }, function() {
        g.isBeingHovered = false;
        removeInfo();
    });
    
    g.indexHexa1 = indexHexa1;
    g.indexHexa2 = indexHexa2;
    g.text = text;
    
    fluxes.push(g);
    
    hexas[indexHexa1].fluxes.push(g);
    
    hexas[indexHexa2].fluxes.push(g);
    group.append(g);
    //hexas[indexHexa2].group.append(g);
    //group.append(hexas[indexHexa2].group);
    return g;
}

function addArrow(x, y, g) {
    var points = [0, 0, 10, 0, 30, fluxHeight / 2, 10, fluxHeight, 0, fluxHeight, 20, fluxHeight / 2];
    
    for (var i = 0; i < points.length; i++) {
        if (i % 2 == 0) {
            points[i] += x;
        }
        else {
            points[i] += y;
        }
    }
    var arrow = g.polygon(points);
    return arrow;
}

function arrowAlpha(x) {
    if (x < 0) {
        return (-20 - x) / (-20);
    }
    else if (x > fluxWidth - 40) {
        return (fluxWidth - 20 - x) / (20);
    }
    return 1;
}
//------------------------------------------------------------------------
//Interface
//------------------------------------------------------------------------

function setInfo(txt) {
    document.getElementById("regionInfo").innerHTML = txt;
    document.getElementById("regionInfo").style.display = "initial";
}

function removeInfo() {
    document.getElementById("regionInfo").style.display = "none";
}

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

function draw() {
    window.requestAnimationFrame(draw);
    //Hexas
    for (var i = 0; i < hexas.length; i++) {
        if (hexas[i].isBeingHovered && hexas[i].currentScale < 1.3) {
            for (var j = 0; j < hexas[i].fluxes.length; j++) {
                hexas[i].group.append(hexas[i].fluxes[j]);
            }
            group.append(hexas[i].group);
            
            hexas[i].currentScale *= scaleFactor;
            
            t = new Snap.Matrix();
            t.scale(scaleFactor, scaleFactor, hexas[i].centerX, hexas[i].centerY);
            t.add(hexas[i].group.transform().localMatrix);
            hexas[i].group.transform(t);
            
            hexas[i].attr({'strokeWidth': (4 * hexas[i].currentScale) + "px"});
        }
        else if (!hexas[i].isBeingHovered && hexas[i].currentScale > 1){
            hexas[i].currentScale /= scaleFactor;
            
            t = new Snap.Matrix();
            t.scale(1/scaleFactor, 1/scaleFactor, hexas[i].centerX, hexas[i].centerY);
            t.add(hexas[i].group.transform().localMatrix);
            hexas[i].group.transform(t);
            
            hexas[i].attr({'strokeWidth': (2 * hexas[i].currentScale) + "px"});
        }
    }
    
    //Fluxes hover
    for (var i = 0; i < fluxes.length; i++) {
        if (fluxes[i].isBeingHovered && fluxes[i].currentScale < 2) {
            
            fluxes[i].currentScale *= scaleFactor;
            
            t = new Snap.Matrix();
            t.scale(scaleFactor, scaleFactor, fluxes[i].centerX, fluxes[i].centerY);
            t.add(fluxes[i].transform().localMatrix);
            fluxes[i].transform(t);
        }
        else if (!fluxes[i].isBeingHovered && fluxes[i].currentScale > 1){
            fluxes[i].currentScale /= scaleFactor;
            
            t = new Snap.Matrix();
            t.scale(1/scaleFactor, 1/scaleFactor, fluxes[i].centerX, fluxes[i].centerY);
            t.add(fluxes[i].transform().localMatrix);
            fluxes[i].transform(t);
        }
    }
    
    //Fluxes arrows
    /*for (var i = 0; i < fluxes.length; i++) {
        for (var j = 0; j < fluxes[i].arrows.length; j++) {
            fluxes[i].arrows[j].x += fluxSpeed;
            
            if (fluxes[i].arrows[j].x > fluxWidth - 20) {
                fluxes[i].arrows[j].x = - 20;
                var t = new Snap.Matrix();
                t.translate(-fluxWidth, 0);
                t.add(fluxes[i].arrows[j].transform().localMatrix);
                fluxes[i].arrows[j].transform(t);
            }
            else {
                var t = new Snap.Matrix();
                t.translate(fluxSpeed, 0);
                t.add(fluxes[i].arrows[j].transform().localMatrix);
                fluxes[i].arrows[j].transform(t);
            }
            fluxes[i].arrows[j].attr({"fill-opacity": arrowAlpha(fluxes[i].arrows[j].x)});
            
        }
    }*/
    
    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>
<?
echo $popUpsHexaTxt;
?>
<?php include("bottom.php"); ?>