<?php
session_start();
?>

<!doctype html>

<html lang="en">
<head>
  <meta charset="utf-8">
  <link rel="icon" href="logo.png">
  <title>InterMap</title>
  <meta name="description" content="InterMap">
  <meta name="author" content="AD">
  <link rel="stylesheet" href="style.css">
  <link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Roboto:700,400&amp;subset=cyrillic,latin,greek,vietnamese">
</head>

<body>
<script src="snap/dist/snap.svg.js"></script>
<script src="jszip/dist/jszip.js"></script>
<script src="FileSaver/FileSaver.js"></script>
<script src="jscolor.js"></script>

<div id="paper">
    <svg id="svg" version="1.1" xmlns="http://www.w3.org/2000/svg"></svg>
</div>

<div id="customization">
	<div id="dNoElementSelected">
		<p id="pNoElementSelected">Click on an element to modify its properties</p>
		<div class="bar"></div>
	</div>
	<div id="dElementSelected" style="display: none;">
		<p id="pCurrentlyModifying" >Currently modifying : </p>
		<p id="pElementName"></p>
		<div class="bar"></div>
		
		<p>Default Properties : </p>
		<p> Fill : <input id="colorFill" class="jscolor {onFineChange:'updateColorFill(this)'}" value="ffffff"></p>
		<p> Stroke : <input id="colorStroke" class="jscolor {onFineChange:'updateColorStroke(this)'}" value="ffffff"></p>
		<div class="bar"></div>
		
		<p>When Hovered : </p>
		<p> Fill : <input id="colorFillHover" class="jscolor {onFineChange:'updateColorFillHover(this)'}" value="ffffff"></p>
		<p> Stroke : <input id="colorStrokeHover" class="jscolor {onFineChange:'updateColorStrokeHover(this)'}" value="ffffff"></p>
		<div class="bar"></div>
		
		<p>When Selected : </p>
		<p> Fill : <input id="colorFillSelected" class="jscolor {onFineChange:'updateColorFillSelected(this)'}" value="ffffff"></p>
		<p> Stroke : <input id="colorStrokeSelected" class="jscolor {onFineChange:'updateColorStrokeSelected(this)'}" value="ffffff"></p>
		<div class="bar"></div>
		
		<p>Info displayed : </p>
		<textarea rows="10" cols="50" placeholder="No info will be displayed" id="tInfoText"></textarea>
		<p> Position : <select id="ddPositionInfoText">
			<option value="0">Right</option>
			<option value="1">Top</option>
			<option value="2">Left</option>
			<option value="3">Bottom</option>
		</select></p>
		<p> Offset : <input type="number" id="nOffsetInfoText"> px</p>
		<p> Style : </p>
		<table>
			<tr id="trAddCustomStyle">
				<td></td>
				<td><button class="niceButton smallButton2 greenButton" onClick="showPopUpCustomStyle()">ADD CUSTOM STYLE</button></td>
			</tr>
		</table>
		<div class="bar"></div>
		
		<p>Set this element as the legend : <input type="checkbox" name="isLegend" value="" id="cIsLegend" onclick="updateCheckboxLegend()"></p>
		<p> Position : <select id="ddPositionLegend">
			<option value="0">Bottom-Right</option>
			<option value="1">Bottom-Left</option>
			<option value="2">Top-Right</option>
			<option value="3">Top-Left</option>
		</select></p>
	</div>
</div>

<div id="interface">
    <button class="niceButton orangeButton" onclick="changeTemplate()">CHANGE TEMPLATE</button>
    <button class="niceButton orangeButton">GLOBAL OPTIONS</button>
	<button class="niceButton orangeButton" onclick="showPopUpImportMap()">IMPORT MAP</button>
    <button class="niceButton orangeButton" onclick="exportMap()">EXPORT MAP</button>
	
    <div class="bar"></div>
    <button class="niceButton blueButton">ACTION 1</button>
    <button class="niceButton blueButton">ACTION 2</button>
    <button class="niceButton blueButton">ACTION 3</button>
    <button class="niceButton greenButton">+ ADD ACTION</button>
</div>

<div id="bgpopup" onClick="hidePopup()">
</div>

<div id="popUpChangeTemplate" class="popup">
	<h3>Change the template of your interactive map</h3>
	<table>
		<tr>
			<td><h3>Earth</h3></td>
			<td><img src="thumbnails/test.png" alt="Earth" style="width:256px;height:128px;"></td>
			<td>Map of the entire Earth, showing borders and lakes.</td>
			<td><button class="niceButton smallButton2 greenButton" onClick="loadTemplate('test.svg')">SELECT</button></td>
		</tr>
		<tr>
			<td><h3>Test</h3></td>
			<td><img src="thumbnails/test2.png" alt="Test" style="width:256px;height:128px;"></td>
			<td>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Aliquam a tincidunt nunc.</td>
			<td><button class="niceButton smallButton2 greenButton" onClick="loadTemplate('test2group.svg')">SELECT</button></td>
		</tr>
	</table>
	</br>
	</br>
	<p> Upload your own template : <input type="file" id="fileCustomTemplate"></input> <button class="niceButton smallButton2 orangeButton" onClick="loadCustomTemplate()">SELECT</button> </p>
</div>

<div id="popUpCustomStyle" class="popup">
	<h3>Upload a .svg to create a new style</h3>
	<p> The .svg must blabla </p>
	<p><input type="file" id="fileCustomStyle"></input></p>
	<p><button class="niceButton smallButton2 orangeButton" onClick="loadCustomStyle()">SELECT</button></p>
</div>

<div id="popUpImportMap" class="popup">
	<h3>Import a previously exported Inter Map</h3>
	<p> Select the .zip file exported earlier </p>
	<p><input type="file" id="fileImportMap"></input></p>
	<p><button class="niceButton smallButton2 orangeButton" onClick="loadImportedMap()">SELECT</button></p>
</div>

<div id="popUpLoading" class="popup">
	<h3>Loading ...</h3>
</div>

<script>
var zoomSpeed = 1.1;
var currentZoom = 1;

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

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

var superGroup = s.g();
superGroup.attr({
	id : "kapoueSuper"
});
var group = null;

var id = 0;
var customId = 0;
var selectedElement;

var customization = document.getElementById("customization");
var dNoElementSelected = document.getElementById("dNoElementSelected");
var dElementSelected = document.getElementById("dElementSelected");

var pCurrentlyModifying = document.getElementById("pCurrentlyModifying");
var pElementName = document.getElementById("pElementName");
var colorFill = document.getElementById("colorFill");
var colorStroke = document.getElementById("colorStroke");
var colorFillHover = document.getElementById("colorFillHover");
var colorStrokeHover = document.getElementById("colorStrokeHover");
var colorFillSelected = document.getElementById("colorFillSelected");
var colorStrokeSelected = document.getElementById("colorStrokeSelected");
var tInfoText = document.getElementById("tInfoText");
var ddPositionInfoText = document.getElementById("ddPositionInfoText");
var nOffsetInfoText = document.getElementById("nOffsetInfoText");
var trAddCustomStyle = document.getElementById("trAddCustomStyle");
var cIsLegend = document.getElementById("cIsLegend");

function initializeChild(element) {
	if (isElementFinal(element)) {
		element.data("id", "elem" + (id++));
		element.data("infoText", "");
		
		element.data("bbox", getRealBBox(element));
		element.data("parent", element.parent());
		
		element.click(clickCallback);
		element.mouseover(hoverCallback);
		element.mouseout(outCallback);
		
		element.attr({
			id: "" + element.data("id")
		});
	}
	else {
		//console.log(element.type == "g" && element.attr("id") && element.attr("id").startsWith("layer"));
		element.children().forEach(function(child) {
			initializeChild(child);
		});
	}
}

//------------------------------------------------------------------------
//Utils
//------------------------------------------------------------------------

function isElementFinal(element) {
	return element.children().length == 0 || (element.type == "g" && !(element.attr("id") && (element.attr("id").startsWith("layer") || element.attr("id").startsWith("kapoue"))));
}

function getRealBBox(element) {
	if (element.children().length == 0) {
		return element.getBBox();
	}
	else {
		var bbox = element.getBBox();
		
		bbox.x = Number.MAX_VALUE;
		bbox.y = Number.MAX_VALUE;
		
		bbox.x2 = Number.MIN_VALUE;
		bbox.y2 = Number.MIN_VALUE;
		for (var i = 0; i < element.children().length; i++) {
			var cbox = getRealBBox(element.children()[i]);
			
			if (cbox.w == 0 && cbox.h == 0) {
				continue;
			}
			
			bbox.x = Math.min(bbox.x, cbox.x);
			bbox.y = Math.min(bbox.y, cbox.y);
			
			bbox.x2 = Math.max(bbox.x2, cbox.x2);
			bbox.y2 = Math.max(bbox.y2, cbox.y2);
		}
		
		bbox.cx = (bbox.x + bbox.x2) / 2;
		bbox.cy = (bbox.y + bbox.y2) / 2;
		
		return bbox;
	}
}

//------------------------------------------------------------------------
//UI
//------------------------------------------------------------------------

var clickCallback = function(event) {
	//Changes in selected elements
	if (selectedElement && selectedElement.data("eInfoText")) {
		selectedElement.data("eInfoText").remove();
	}
	
	if (selectedElement != null) {
		animateColor(selectedElement.data("fill"), selectedElement.data("stroke"), selectedElement)
	}
	
	if (selectedElement == this) {
		dNoElementSelected.style.display = 'block';
		dElementSelected.style.display = 'none';
		
		selectedElement = null;
		return;
	}
	
	var oldSelectedElement = selectedElement;
	selectedElement = this;
	
	//Changes in UI
	dNoElementSelected.style.display = 'none';
	dElementSelected.style.display = 'block';
	
	pElementName.innerHTML = this.id;
	
	//Init color pickers
	if (!this.attr("fill") || this.attr("fill") == "none") {
		this.attr({ 
			fill: "black"
		});
	}
	
	if (!this.attr("stroke") || this.attr("stroke") == "none") {
		this.attr({ 
			stroke: "black"
		});
	}
	
	if (!this.data("fill")) {
		this.data("fill", Snap.color(this.attr("fill")).hex);
		this.data("stroke", Snap.color(this.attr("stroke")).hex);
	}
	colorFill.jscolor.fromString(Snap.color(this.data("fill")).hex.substring(1));
	colorStroke.jscolor.fromString(Snap.color(this.data("stroke")).hex.substring(1));
	
	if (!this.data("fillHover")) {
		this.data("fillHover", Snap.color(this.attr("fill")).hex);
		this.data("strokeHover", Snap.color(this.attr("stroke")).hex);
	}
	colorFillHover.jscolor.fromString(Snap.color(this.data("fillHover")).hex.substring(1));
	colorStrokeHover.jscolor.fromString(Snap.color(this.data("strokeHover")).hex.substring(1));
	
	if (!this.data("fillSelected")) {
		this.data("fillSelected", Snap.color(this.attr("fill")).hex);
		this.data("strokeSelected", Snap.color(this.attr("stroke")).hex);
	}
	colorFillSelected.jscolor.fromString(Snap.color(this.data("fillSelected")).hex.substring(1));
	colorStrokeSelected.jscolor.fromString(Snap.color(this.data("strokeSelected")).hex.substring(1));
	
	animateColor(this.data("fillSelected"), this.data("strokeSelected"), this);
	
	//Init textArea
	if (!selectedElement.data("offsetInfoText") && selectedElement.data("offsetInfoText") != 0) {
		selectedElement.data("infoText", "");
		selectedElement.data("offsetInfoText", 0);
		selectedElement.data("positionInfoText", 0);
		selectedElement.data("styleInfoText", "Classic");
	}
	
	tInfoText.value = selectedElement.data("infoText");
	nOffsetInfoText.value = selectedElement.data("offsetInfoText");
	ddPositionInfoText.value = selectedElement.data("positionInfoText");
	
	var styles = Object.keys(infoTextStyles);
	for (var i = 0; i < styles.length; i++) {
		document.getElementById("style" + styles[i]).innerHTML = styles[i];
	}
	
	document.getElementById("style" + selectedElement.data("styleInfoText")).innerHTML = "<u><b>" + selectedElement.data("styleInfoText") + "</b></u>";
	
	infoTextCallback();
	
	//Center camera on objects
	if (selectedElement.data("eInfoText") && selectedElement.data("infoText").length > 0) {
		var selBox = getRealBBox(selectedElement);
		var infoBox = selectedElement.data("eInfoTextBBox");
		
		var mat = selectedElement.transform().globalMatrix;
		var m = new Snap.Matrix();
			
		var tX, tY;
		var scaleX = 0.9 * paper.getBoundingClientRect().width;
		var scaleY = 0.9 * paper.getBoundingClientRect().height;
		switch (selectedElement.data("positionInfoText")) {
			default : //right
				tX = (mat.a * selBox.x + mat.e  +  infoBox.x2) / 2;
				tY = mat.d * selBox.cy + mat.f;
				scaleX /= (infoBox.x2 - (mat.a * selBox.x + mat.e));
				scaleY /= Math.max(mat.d * selBox.h, infoBox.h);
			break;
			case 1 : //top
				tX = mat.a * selBox.cx + mat.e;
				tY = (mat.d * selBox.y2 + mat.f  +  infoBox.y) / 2;
				scaleX /= Math.max(mat.a * selBox.w, infoBox.w);
				scaleY /= (- infoBox.y + (mat.d * selBox.y2 + mat.f));
			break;
			case 2 : //left
				tX = (mat.a * selBox.x2 + mat.e  +  infoBox.x) / 2;
				tY = mat.d * selBox.cy + mat.f;
				scaleX /= (- infoBox.x + (mat.a * selBox.x2 + mat.e));
				scaleY /= Math.max(mat.d * selBox.h, infoBox.h);
			break;
			case 3 : //bottom
				tX = mat.a * selBox.cx + mat.e;
				tY = (mat.d * selBox.y + mat.f  +  infoBox.y2) / 2;
				scaleX /= Math.max(mat.a * selBox.w, infoBox.w);
				scaleY /= (infoBox.y2 - (mat.d * selBox.y + mat.f));
			break;
		}
		
		m.translate(-tX, -tY);
		m.translate(paper.getBoundingClientRect().width / 2,
					paper.getBoundingClientRect().height / 2);
		
		var scale = Math.min(scaleX, scaleY);
		m.scale(scale, scale, tX, tY);
		
		group.animate({ transform: m}, 1000);
	}
	
	//Legend
	if (!this.data("isLegend")) {
		this.data("isLegend", false);
		this.data("positionLegend", 0);
	}
	
	cIsLegend.checked = this.data("isLegend");
	ddPositionLegend.value = selectedElement.data("positionLegend");
};

var hoverCallback = function(event) {
	if (this.data("fillHover")) {
		animateColor(this.data("fillHover"), this.data("strokeHover"), this)
	}
}

var outCallback = function(event) {
	if (selectedElement != this) {
		if (this.data("fill")) {
			animateColor(this.data("fill"), this.data("stroke"), this)
		}
	}
	else {
		if (this.data("fillSelected")) {
			animateColor(this.data("fillSelected"), this.data("strokeSelected"), this)
		}
	}
}

var infoTextCallback = function(event) {
	selectedElement.data("infoText", tInfoText.value);
	selectedElement.data("offsetInfoText", Number(nOffsetInfoText.value));
	selectedElement.data("positionInfoText", ddPositionInfoText.selectedIndex);
	
	if (selectedElement == null) { //if the selectedElement has changed while loading
		return;
	}
	
	if (selectedElement.data("eInfoText")) {
		selectedElement.data("eInfoText").remove();
		selectedElement.data("eInfoText", null);
	}
	
	if (selectedElement.data("infoText").length == 0) {
		return;
	}
	
	var f = Snap.parse(infoTextStyles[selectedElement.data("styleInfoText")]);
	
	f.node.getElementById("foreignInfoText").innerHTML = '<p xmlns="http://www.w3.org/1999/xhtml" class="infoText">' + selectedElement.data("infoText") + '</p>';
	
	var groupInfoText = s.g();
	groupInfoText.append(f);
	
	group.append(groupInfoText);
	
	var m = new Snap.Matrix();
	m.add(selectedElement.transform().globalMatrix);
	var bbox = getRealBBox(selectedElement);
	var infoBbox = groupInfoText.getBBox();
	switch (selectedElement.data("positionInfoText")) {
		default : //right
			m.translate((bbox.x2 - infoBbox.x + selectedElement.data("offsetInfoText")), 
						 bbox.cy - infoBbox.cy);
		break;
		case 1 : //top
			m.translate((bbox.cx - infoBbox.cx), 
						 bbox.y - infoBbox.y2 - selectedElement.data("offsetInfoText"));
		break;
		case 2 : //left
			m.translate((bbox.x - infoBbox.x2 - selectedElement.data("offsetInfoText")), 
						 bbox.cy - infoBbox.cy);
		break;
		case 3 : //bottom
			m.translate((bbox.cx - infoBbox.cx), 
						 bbox.y2 - infoBbox.y + selectedElement.data("offsetInfoText"));
		break;
	}
	
	groupInfoText.transform(m);
	
	selectedElement.data("eInfoText", groupInfoText);
	selectedElement.data("eInfoTextBBox", groupInfoText.getBBox());
};

var positionLegendCallback = function(event) {
	selectedElement.data("positionLegend", ddPositionLegend.selectedIndex);
	
	updateLegend(selectedElement);
};


if (tInfoText.addEventListener) {
	tInfoText.addEventListener('input', infoTextCallback, false);
	ddPositionInfoText.addEventListener('input', infoTextCallback, false);
	nOffsetInfoText.addEventListener('input', infoTextCallback, false);
	ddPositionLegend.addEventListener('input', positionLegendCallback, false);
}
else if (area.attachEvent) {
	tInfoText.attachEvent('onpropertychange', infoTextCallback);
	ddPositionInfoText.attachEvent('onpropertychange', infoTextCallback);
	nOffsetInfoText.attachEvent('onpropertychange', infoTextCallback);
	ddPositionLegend.attachEvent('onpropertychange', positionLegendCallback);
}

//------------------------------------------------------------------------
//Updates
//------------------------------------------------------------------------

function updateColorFill(color) {
	selectedElement.data("fill", "#" + color);
}

function updateColorStroke(color) {
	selectedElement.data("stroke", "#" + color);
}

function updateColorFillHover(color) {
	selectedElement.data("fillHover", "#" + color);
}

function updateColorStrokeHover(color) {
	selectedElement.data("strokeHover", "#" + color);
}

function updateColorFillSelected(color) {
	setColorFill("#" + color, selectedElement);
	
	selectedElement.data("fillSelected", "#" + color);
}

function updateColorStrokeSelected(color) {
	setColorStroke("#" + color, selectedElement);
	
	selectedElement.data("strokeSelected", "#" + color);
}

function updateCheckboxLegend() {
	selectedElement.data("isLegend", cIsLegend.checked);
	
	updateLegend(selectedElement);
}

function updateLegend(element) {
	var bbox = element.data("bbox");
	
	element.remove();
	if (element.data("isLegend")) {
		
		var legendGroup = s.g();
		superGroup.append(legendGroup);
		legendGroup.attr({
			id : "kapoueLegend" + element.attr("id")
		});
		legendGroup.append(element);
		
		var m = new Snap.Matrix();
		m.add(element.transform().localMatrix.invert());
		switch (element.data("positionLegend")) {
			default : //bottom right
				m.translate(-bbox.x2 + paper.getBoundingClientRect().width, 
							-bbox.y2 + paper.getBoundingClientRect().height);
			break;
			case 1 : //bottom left
				m.translate(-bbox.x, 
							-bbox.y2 + paper.getBoundingClientRect().height);
			break;
			case 2 : //top right
				m.translate(-bbox.x2 + paper.getBoundingClientRect().width, 
							-bbox.y);
			break;
			case 3 : //top left
				m.translate(-bbox.x, 
							-bbox.y);
			break;
		}
		legendGroup.transform(m)
		
		element.data("legendGroup", legendGroup);
	}
	else {
		element.data("parent").append(element);
		
		if (element.data("legendGroup")) {
			element.data("legendGroup").remove();
		}
	}
}

function printBBox(element) {
	if (element.data("bbox")) {
		console.log(element.data("bbox"));
	}
	else {
		console.log(getRealBBox(element));
	}
	
	element.children().forEach(function(child) {
		printBBox(child);
	});
}

function setColorFill(color, element) {
	element.attr({
		fill: color
	});
	
	element.attr({ 
		style: element.attr('style') + ';fill: ' + color
	});
	
	element.children().forEach(function(child) {
		if (child.type != "#text") {
			setColorFill(color, child);
		}
	});
}

function setColorStroke(color, element) {
	element.attr({
		stroke: color
	});
	
	element.attr({ 
		style: element.attr('style') + ';stroke: ' + color
	});
	
	element.children().forEach(function(child) {
		if (child.type != "#text") {
			setColorStroke(color, child);
		}
	});
}

function animateColor(colorFill, colorStroke, element) {
	var fromFill = Snap.color(Snap.color(element.attr("fill")).hex)
	var toFill = Snap.color(colorFill)
	
	var fromStroke = Snap.color(Snap.color(element.attr("stroke")).hex)
	var toStroke = Snap.color(colorStroke)
	
	Snap.animate([fromFill.r, fromFill.g, fromFill.b, fromStroke.r, fromStroke.g, fromStroke.b], [toFill.r, toFill.g, toFill.b, toStroke.r, toStroke.g, toStroke.b], function (val) {
		var fillColor = "rgb(" + Math.round(val[0]) + "," + Math.round(val[1]) + "," + Math.round(val[2]) + ")";
		var strokeColor = "rgb(" + Math.round(val[3]) + "," + Math.round(val[4]) + "," + Math.round(val[5]) + ")";
		
		element.attr({ //removes the old values
			fill : fillColor,
			stroke : strokeColor
		});
		
		element.attr({
			style :  element.attr("style") + ";fill: " + fillColor + ";stroke: " + strokeColor
		});
	}, 200);
	
	element.children().forEach(function(child) {
		if (child.type != "#text") {
			animateColor(colorFill, colorStroke, child);
		}
	});
}

//------------------------------------------------------------------------
// Change template
//------------------------------------------------------------------------

function changeTemplate() {
	showPopUpChangeTemplate();
}

function loadTemplate(fileName) {
	initLoad();
	Snap.load(fileName, function (f) {
		loadFragment(f, true);
	});
}

function loadCustomTemplate() {
	initLoad();
	var file = document.getElementById("fileCustomTemplate").files[0];
	if (file) {
		var reader = new FileReader();
		reader.readAsText(file, "UTF-8");
		reader.onload = function (evt) {
			loadFragment(Snap.parse(evt.target.result), true);
		}
		reader.onerror = function (evt) {
			console.log("error reading file");
		}
	}
	else {
		hidePopup();
	}
}

function loadImportedTemplate() {
	initLoad();
	loadFragment(Snap.parse(newData.map), false);
}

function initLoad() {
	showPopUpLoading();
	
	dNoElementSelected.style.display = 'block';
	dElementSelected.style.display = 'none';
	
	selectedElement = null;
	
	if (group) {
		group.remove();
	}
	
	group = s.g();
	superGroup.append(group);
	group.attr({
		id : "kapoueMap"
	});
	group.drag();
	
}

function loadFragment(f, shouldInit) {
	group.append(f);
	if (shouldInit) {
		initializeChild(group);
	}
	
	var box = group.getBBox();
	var m = new Snap.Matrix();
	m.translate(-box.cx + paper.getBoundingClientRect().width / 2,
				-box.cy + paper.getBoundingClientRect().height / 2);
	
	var scaleX = 0.9 * paper.getBoundingClientRect().width / box.w;
	var scaleY = 0.9 * paper.getBoundingClientRect().height / box.h;
	var scale = Math.min(scaleX, scaleY);
	m.scale(scale, scale, box.cx, box.cy);
	group.transform(m);
	
	hidePopup();
}

//------------------------------------------------------------------------
// InfoText Style
//------------------------------------------------------------------------

var infoTextStyles = new Object();
loadStyle("Classic");
loadStyle("Modern");
loadStyle("Test");

function loadStyle(name) {
	Snap.load("styles/style" + name + ".svg", function (f) {
		var groupInfoText = s.g();
		groupInfoText.add(f);
		infoTextStyles[name] = groupInfoText.innerSVG().toString();
		groupInfoText.remove();
	});
	
	addStyle(name);
}

function setStyle(name) {
	document.getElementById("style" + selectedElement.data("styleInfoText")).innerHTML = selectedElement.data("styleInfoText");
	document.getElementById("style" + name).innerHTML = "<u><b>" + name + "</b></u>";
	
	selectedElement.data("styleInfoText", name);
	
	infoTextCallback();
}

function loadCustomStyle() {
	var file = document.getElementById("fileCustomStyle").files[0];
	if (file) {
		var reader = new FileReader();
		reader.readAsText(file, "UTF-8");
		reader.onload = function (evt) {
			var name = "Custom" + (++customId);
			
			var f = Snap.parse(evt.target.result);
			
			var toBeReplaced = f.select("#TOBEREPLACED");
			var x = toBeReplaced.attr("x");
			var y = toBeReplaced.attr("y");
			var width = toBeReplaced.attr("width");
			var height = toBeReplaced.attr("height");
			var parent = toBeReplaced.parent();
			
			toBeReplaced.remove();
			
			parent.add(Snap.parse('<foreignObject x="' + x + '" y="' + y + '" width="' + width + '" height="' + height + '" id="foreignInfoText"></foreignObject>'));
			
			var groupInfoText = s.g();
			groupInfoText.add(f);
			infoTextStyles[name] = groupInfoText.innerSVG().toString();
			groupInfoText.remove();
			
			//Add the new style in the table
			addStyle(name);
			setStyle(name);
	
			infoTextCallback();
			
			hidePopup();
		}
		reader.onerror = function (evt) {
			console.log("error reading file");
		}
	}
	else {
		hidePopup();
	}
}

function addStyle(name) {
	var newTr = document.createElement("tr");
	
	newTr.innerHTML = "<td id='style" + name + "'>" + name + "</td><td><button id='button" + name + "' class='niceButton smallButton2 imageButton' style='background-image: url(thumbnails/test.png)'></button></td>";
	trAddCustomStyle.parentElement.insertBefore(newTr, trAddCustomStyle);
	document.getElementById("button" + name).onclick = function() { 
		setStyle(name);
	};
}

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

var bgPopup = document.getElementById("bgpopup");
var popUpChangeTemplate = document.getElementById("popUpChangeTemplate");
var popUpCustomStyle = document.getElementById("popUpCustomStyle");
var popUpImportMap = document.getElementById("popUpImportMap");
var popUpLoading = document.getElementById("popUpLoading");

loadTemplate('test2group.svg'); //must load after popup init

function hidePopup() {
    bgPopup.style.visibility = "hidden";
    popUpChangeTemplate.style.visibility = "hidden";
    popUpCustomStyle.style.visibility = "hidden";
    popUpImportMap.style.visibility = "hidden";
    popUpLoading.style.visibility = "hidden";
}

function showPopUpChangeTemplate() {
    bgPopup.style.visibility = "visible";
    popUpChangeTemplate.style.visibility = "visible";
    popUpCustomStyle.style.visibility = "hidden";
    popUpImportMap.style.visibility = "hidden";
    popUpLoading.style.visibility = "hidden";
}

function showPopUpLoading() {
    bgPopup.style.visibility = "visible";
    popUpChangeTemplate.style.visibility = "hidden";
    popUpCustomStyle.style.visibility = "hidden";
    popUpImportMap.style.visibility = "hidden";
    popUpLoading.style.visibility = "visible";
}

function showPopUpCustomStyle() {
    bgPopup.style.visibility = "visible";
    popUpChangeTemplate.style.visibility = "hidden";
    popUpCustomStyle.style.visibility = "visible";
    popUpImportMap.style.visibility = "hidden";
    popUpLoading.style.visibility = "hidden";
}

function showPopUpImportMap() {
    bgPopup.style.visibility = "visible";
    popUpChangeTemplate.style.visibility = "hidden";
    popUpCustomStyle.style.visibility = "hidden";
    popUpImportMap.style.visibility = "visible";
    popUpLoading.style.visibility = "hidden";
}

//------------------------------------------------------------------------
//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);
		
		currentZoom *= zoomSpeed;
	}
	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);
		
		currentZoom /= zoomSpeed;
	}
}

//------------------------------------------------------------------------
// Download data
//------------------------------------------------------------------------

function downloadFile(data, filename, type) {
    var file = new Blob([data], {type: type});
    if (window.navigator.msSaveOrOpenBlob) // IE10+
        window.navigator.msSaveOrOpenBlob(file, filename);
    else { // Others
        var a = document.createElement("a"),
                url = URL.createObjectURL(file);
        a.href = url;
        a.download = filename;
        document.body.appendChild(a);
        a.click();
        setTimeout(function() {
            document.body.removeChild(a);
            window.URL.revokeObjectURL(url);  
        }, 0); 
    }
}

//------------------------------------------------------------------------
// Export / Import map
//------------------------------------------------------------------------
var savedData;
var newData;

function gatherInfoTexts(element) {
	if (isElementFinal(element)) {
		if (element.attr("id") && element.data("fill")) {//the element is a valid element that has been modified
			//Reset the color in the svg
			setColorFill(element.data("fill"), element);
			setColorStroke(element.data("stroke"), element);
			
			if (element.data("eInfoText")) {
				element.data("eInfoText").remove();
			}
			
			if (element.data("isLegend")) {
				element.remove();
				element.data("parent").append(element);
				if (element.data("legendGroup")) {
					element.data("legendGroup").remove();
				}
			}
			
			//Construct the data object
			var elementData = new Object();
			elementData.fill = element.data("fill");
			elementData.stroke = element.data("stroke");
			elementData.fillHover = element.data("fillHover");
			elementData.strokeHover = element.data("strokeHover");
			elementData.fillSelected = element.data("fillSelected");
			elementData.strokeSelected = element.data("strokeSelected");
			
			elementData.isLegend = element.data("isLegend");
			elementData.positionLegend = element.data("positionLegend");
			
			//If an info text is set
			if (element.data("infoText") && element.data("infoText").length > 0) {
				elementData.infoText = element.data("infoText").replace(/\r?\n|\r/g, "");
				elementData.offsetInfoText = element.data("offsetInfoText");
				elementData.positionInfoText = element.data("positionInfoText");
				elementData.styleInfoText = element.data("styleInfoText");
			}
			
			savedData.elements[element.attr("id")] = elementData;
		}
	}
	else {
		element.children().forEach(function(child) {
			gatherInfoTexts(child);
		});
	}
}

/*function afterGatherInfoTexts(element) {
	if (isElementFinal(element)) {
		if (element.attr("id") && element.data("fill")) {//the element is a valid element that has been modified
			if (element.data("isLegend")) {
				element.remove();
				element.data("parent").append(element);
				if (element.data("legendGroup")) {
					element.data("legendGroup").remove();
				}
			}
		}
	}
	else {
		element.children().forEach(function(child) {
			afterGatherInfoTexts(child);
		});
	}
}*/

function exportMap() {
	dNoElementSelected.style.display = 'block';
	dElementSelected.style.display = 'none';
	
	selectedElement = null;
	
	savedData = {elements : new Object()};
	gatherInfoTexts(superGroup);
	
	//var styles = Object.keys(infoTextStyles);
	savedData.styles = infoTextStyles;
	
	savedData.map = group.innerSVG();
	
	var zip = new JSZip();
	//zip.file("autoMap.svg", group.innerSVG());
	zip.file("autoData.json", "var savedData = " + JSON.stringify(savedData) + ";");
	
	
	/*for (var i = 0; i < styles.length; i++) {
		zip.file("styles/style" + styles[i] + ".svg", infoTextStyles[styles[i]]);
	}*/
	
	zip.generateAsync({type:"blob"}).then(function(content) {
		saveAs(content, "inter.zip");
	});
}

function loadImportedMap() {
	var file = document.getElementById("fileImportMap").files[0];
	if (file) {
		JSZip.loadAsync(file).then(function(zip) {
			showPopUpLoading();
			
			//Map & Data & Styles
			zip.file("autoData.json").async("string")
			.then(function success(content) {
				newData = JSON.parse(content.slice(16, -1));
				
				loadImportedTemplate();
				
				initializeImportedChild(group);
				
				infoTextStyles = newData.styles;
				
				//reconstruct style table
				var parent = trAddCustomStyle.parentElement;
				parent.innerHTML = "";
				parent.appendChild(trAddCustomStyle);
				
				var styles = Object.keys(infoTextStyles);
				for (var i = 0; i < styles.length; i++) {
					addStyle(styles[i]);
				}
			}, function error(e) {
				console.log("Cannot load the data");
			});
			
			hidePopup();
		});
	}
	else {
		hidePopup();
	}
}

function initializeImportedChild(element) {
	
	if (isElementFinal(element)) {
		element.click(clickCallback);
		element.mouseover(hoverCallback);
		element.mouseout(outCallback);
			
		if (newData.elements[element.attr("id")]) {
			element.data("id", element.attr("id"));
			
			var elementData = newData.elements[element.attr("id")];
			
			element.data("fill", elementData.fill);
			element.data("stroke", elementData.stroke);
			element.data("fillHover", elementData.fillHover);
			element.data("strokeHover", elementData.strokeHover);
			element.data("fillSelected", elementData.fillSelected);
			element.data("strokeSelected", elementData.strokeSelected);
			
			element.data("isLegend", elementData.isLegend);
			element.data("positionLegend", elementData.positionLegend);
			
			if (elementData.infoText) {
				element.data("infoText", elementData.infoText);
				element.data("offsetInfoText", elementData.offsetInfoText);
				element.data("positionInfoText", elementData.positionInfoText);
				element.data("styleInfoText", elementData.styleInfoText);
			}
		}
	}
	else {
		element.children().forEach(function(child) {
			initializeImportedChild(child);
		});
	}
}

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