//  Copyright (2010-2013) Cédric Coussinet (cedric.coussinet@nomoseed.net)
//
//  This program is free software: you can redistribute it and/or modify
//  it under the terms of the GNU General Public License as published
//  by the Free Software Foundation, version 2 of the License.
//
//  This program is distributed in the hope that it will be useful,
//  but WITHOUT ANY WARRANTY; without even the implied warranty of
//  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
//  GNU General Public License for more details.
//
//  You should have received a copy of the GNU General Public License
//  along with this program. If not, see <http://www.gnu.org/licenses/>

var hueType = new RegExp("([3]?[0-5]?[0-9])|([0-2]?[0-9]?[0-9])|360","i");

var h = 170;

var worldsquareSVG;
var slabControl;
var textHue;
var lastHue = 50;
var rangeHue;
var textSpheresNbr;
var slabCurrent;
var slabEvent;
var slabCurrentId;
var slabCurrentUse;
var slabs;
var moveControl;

var clickDelay = 250;     // doubleclick time
var eventClick = null;    // handle of click setTimeOut

function onClickSphere() {
	slabEvent = event;
	if (event.detail==1)
		eventClick = setTimeout("singleClickSphere()", clickDelay);
	else
		doubleClickSphere();
}

function singleClickSphere() {
	slabCurrent = slabEvent.target.correspondingUseElement.parentNode;
	slabCurrentUse = slabCurrent.childNodes[0];
	lastHue = slabCurrentUse.getAttribute("fill").substring(4).split(",")[0];
	slabCurrentId = slabCurrent.getAttribute("id").replace('x','');
	document.getElementById("sphere_radio").checked="checked";
	textSpheresNbr.value = nomoSDK.getSpheresNbrAgent(slabCurrentId);
	showSlabControl();
}
 
function doubleClickSphere() {
	if (eventClick != null) {
		clearTimeout( eventClick );
		eventClick = null;
	}
	nomoSDK.suppSphere(slabEvent.target.correspondingUseElement.parentNode.getAttribute("id").replace('x',''));
}

function mouseDownAgent() {
	if (event.detail == 1){
		slabs.addEventListener("mouseup", mouseUpMoveControl, false);
		slabs.addEventListener("mouseover", mouseOverMoveControl, false);
		window.addEventListener("mouseup", removeMoveControl, false);
		slabCurrent = event.target.correspondingUseElement.parentNode.parentNode;
		slabCurrentId = slabCurrent.getAttribute("id").replace('x','');
		var coord = slabCurrent.getAttribute("transform").replace("translate (","").replace(")","").split(", ");
		moveControl.setAttribute("x1", coord[0]);
		moveControl.setAttribute("y1", coord[1]);
		moveControl.setAttribute("x2", coord[0]);
		moveControl.setAttribute("y2", coord[1]);
	}
}

function mouseOverMoveControl(){
	var target = event.target.correspondingUseElement;
	if (target.getAttribute("x") != null)
		if (target.getAttribute("x") != null || target.getAttribute("y") != null ){
			moveControl.setAttribute("x2", Number(target.getAttribute("x")));
			moveControl.setAttribute("y2", Number(target.getAttribute("y")) - 16);
			moveControl.setAttribute("visibility", "visible");
			return;
		}
	moveControl.setAttribute("visibility", "hidden");
}

function removeMoveControl(){
	slabs.removeEventListener("mouseup", mouseUpMoveControl, false);
	slabs.removeEventListener("mouseover", mouseOverMoveControl, false);
	moveControl.setAttribute("visibility", "hidden");
}

function mouseUpMoveControl(){
	removeMoveControl();
	var target = event.target.correspondingUseElement;
	if (target.parentNode.getAttribute("id").search('x') != -1)
		nomoSDK.moveAgent(slabCurrentId, target.parentNode.getAttribute("id").replace('x',''));
	else if (target.getAttribute("id").search('x') != -1)
		nomoSDK.moveAgent(slabCurrentId, target.getAttribute("id").replace('x',''));
	event.stopPropagation();
}

function onClickAgent(direction) {
	slabEvent = event;
	if (event.detail == 1)
		eventClick = setTimeout("singleClickAgent("+direction+")", clickDelay);
	else
		doubleClickAgent();
}
function singleClickAgent(direction) {
	slabCurrent = slabEvent.target.correspondingUseElement.parentNode.parentNode;
	slabCurrentUse = slabCurrent.childNodes[0];
	lastHue = slabCurrentUse.getAttribute("fill").substring(4).split(",")[0];
	slabCurrentId = slabCurrent.getAttribute("id").replace('x','');
	document.getElementById("agent_"+direction+"_radio").checked="checked";
	textSpheresNbr.value = nomoSDK.getSpheresNbrAgent(slabCurrentId);
	showSlabControl();
}
 
function doubleClickAgent() {
	if (eventClick != null) {
		clearTimeout( eventClick );
		eventClick = null;
	}
	nomoSDK.suppAgent(slabEvent.target.correspondingUseElement.parentNode.parentNode.getAttribute("id").replace('x',''));
}

function onClickSlab() {
	slabEvent = event;
	if (!eventClick)
		eventClick = setTimeout("singleClickSlab()", clickDelay);
	else
		doubleClickSlab();
}

function singleClickSlab() {
	eventClick = null;
	slabCurrent = slabEvent.target.correspondingUseElement;
	slabCurrentUse = slabCurrent;
	lastHue = slabCurrent.getAttribute("fill").substring(4).split(",")[0];
	slabCurrentId = slabCurrent.getAttribute("id").replace('x','');
	textSpheresNbr.value = nomoSDK.getSpheresNbrAgent();
	showSlabControl();
}
 
function doubleClickSlab() {
	if (eventClick != null) {
		clearTimeout( eventClick );
		eventClick = null;
	}
	nomoSDK.suppSlab(slabEvent.target.correspondingUseElement.getAttribute("id").replace('x',''));
}

function selectUnit(){
	nomoSDK.selectMapUnit();
}

function openUnit(name) {
	document.getElementById ("unitSelection").value = name;
	if (!hasUnit)
		showControls();
}

function reloadUnit(){
	nomoSDK.reloadMapUnit();
}

function showControls() {
	hasUnit = true;
	var unitDiv = document.getElementById ("unit");
	unitDiv.style.webkitTransitionDuration = "1s";
	unitDiv.style.right = "0px";
	var unitReloading = document.getElementById ("unitReloading");
	unitReloading.style.marginLeft = "0px";
	unitReloading.style.webkitTransitionProperty = "margin-left";
	unitReloading.style.webkitTransitionDelay = "0.3s";
	unitReloading.style.webkitTransitionDuration = "0.7s";
	unitReloading.style.pointerEvents = "all";
	var mapDiv = document.getElementById ("map");
	mapDiv.style.webkitTransitionDuration = "1s";
	mapDiv.style.left = "0px";
	var mapReloading = document.getElementById ("mapReloading");
	mapReloading.style.marginRight = "0px";
	mapReloading.style.webkitTransitionProperty = "margin-right";
	mapReloading.style.webkitTransitionDelay = "0.3s";
	mapReloading.style.webkitTransitionDuration = "0.7s";
	mapReloading.style.pointerEvents = "all";
	var actionDiv = document.getElementById ("action")
	actionDiv.style.opacity = "1";
	actionDiv.style.webkitTransitionDuration = "1s";
	worldsquareSVG.style.webkitTransitionDuration = "1s";
	h=170;
	worldsquareSVG.style.height = (window.innerHeight - h) + "px";
	slabs.setAttribute("class", "");
	setTimeout("nomoSDK.repaintMap()", 1000);
}

function selectMap(){
	nomoSDK.selectMap();
}

function showSlabControl(){
	slabCurrent.lastChild.setAttribute("begin","indefinite");
	var coord = slabCurrent.getAttribute("id").split('x');
	nomoSDK.setSlab(coord[0],coord[1], lastHue);
	textHue.value = lastHue;
	rangeHue.value = lastHue;
	slabControl.style.top = (slabEvent.clientY - 5) + "px";
	var dx = window.innerWidth - (slabEvent.clientX + 241);
	if (dx<0)
		slabControl.style.left = (slabEvent.clientX  - 5+ dx) + "px";
	else
		slabControl.style.left = (slabEvent.clientX - 5) + "px";
	slabControl.style.display = "block";
	worldsquareSVG.onmouseover = hiddenSlabControl;
	if (hasUnit)
		slabs.setAttribute("class", "spaceStable");
	slabEvent.stopPropagation();
}

function setTextHue (){
	textHue.value = rangeHue.value;
	slabCurrentUse.setAttribute("fill","hsl("+rangeHue.value+", 100%, 50%)");
	event.stopPropagation();
}

function focusTextHue()
{
	lastHue = textHue.value;
	this.addEventListener("mouseout", mouseOutTextHue, false);
	event.stopPropagation();
}

function mouseOutTextHue(evt)
{
	if (textHue.value<0 || textHue.value>360)
		textHue.value=lastHue; 
	this.blur();
	this.removeEventListener("mouseout", mouseOutTextHue, false);
	event.stopPropagation();
}

function setRangeHue (){
	rangeHue.value = textHue.value;
	slabCurrentUse.setAttribute("fill","hsl("+rangeHue.value+", 100%, 50%)");
	event.stopPropagation();
}

function focusTextSpheresNbr()
{
	this.addEventListener("mouseout", mouseOutTextSpheresNbr, false);
	event.stopPropagation();
}

function mouseOutTextSpheresNbr(evt)
{
	textSpheresNbr.value = Math.floor(Math.abs(textSpheresNbr.value)); 
	this.blur();
	this.removeEventListener("mouseout", mouseOutTextSpheresNbr, false);
	event.stopPropagation();
}

function hiddenSlabControl(){
	slabControl.style.display = "none";
	worldsquareSVG.onmouseover = "";
	slabCurrent.lastChild.beginElement();
	slabCurrent.lastChild.setAttribute("begin","mouseout");
	if (lastHue!=textHue.value){
		lastHue = textHue.value;
		nomoSDK.setHueSlab(slabCurrentId,textHue.value);
	}
	if (slabCurrent == slabCurrentUse)
		nomoSDK.setSpheresNbrAgent (textSpheresNbr.value);
	else
	{
		nomoSDK.setSpheresNbrAgent (slabCurrentId, textSpheresNbr.value);
		nomoSDK.repaintMap();
	}
	if (hasUnit)
		slabs.setAttribute("class", "");
	event.stopPropagation();
}

function addSlab(){
	var coord = event.target.correspondingUseElement.getAttribute("id").split('_');
	nomoSDK.addSlab(coord[0],coord[1]);
}

function slabBuild(){
	if (lastHue!=textHue.value){
		lastHue = textHue.value;
		nomoSDK.setHueSlab(slabCurrentId,textHue.value);
	}
	nomoSDK.setSpheresNbrAgent (textSpheresNbr.value);
	if(this.value == "space")
		nomoSDK.suppAll();
	if (this.value == "slab")
		nomoSDK.addSlab();
	if (this.value == "sphere")
		nomoSDK.addSphere();
	else if (this.value == "agent_0")
		nomoSDK.addAgent(0);
	else if (this.value == "agent_90")
		nomoSDK.addAgent(90);
	else if (this.value == "agent_180")
		nomoSDK.addAgent(180);
	else if (this.value == "agent_270")
		nomoSDK.addAgent(270);
}

window.onload = function ()
{
	document.getElementById ("unitSelection").onclick = selectUnit;
	document.getElementById ("unitReloading").onclick = reloadUnit;
	document.getElementById ("mapSelection").onclick = selectMap;
	document.getElementById ("mapReloading").onclick = reloadData;
	progressSize = document.getElementById ("progressSize");
	progressVal = document.getElementById ("progressVal");
	progressBar = document.getElementById ("progressBar");
	moveControl = document.getElementById ("moveControl");
	moveControl.setAttribute("visibility", "hidden");
	worldsquareSVG = document.getElementsByTagNameNS ("http://www.w3.org/2000/svg", "svg")[0];
	initializeForm ();
	slabControl = document.getElementById ("slabControl");
	textHue = document.getElementById ("textHue");
	textHue.onfocus = focusTextHue;
	textHue.value=70
	rangeHue = document.getElementById ("rangeHue");
	textSpheresNbr = document.getElementById ("textSpheresNbr");
	textSpheresNbr.onfocus = focusTextSpheresNbr;
	slabs = document.getElementById ("slabs");
	var forms = document.getElementsByTagName ("form");
	var slabRadio = document.getElementsByName("slab");
	for (i in slabRadio)
	{
		slabRadio[i].onclick = slabBuild;
	}
	for (i in forms)
	{
		forms[i].action = action;
	}
	if (!hasUnit)
	{
		h=40;
		document.getElementById ("unit").style.right = "-55px";
		document.getElementById ("unitReloading").style.marginLeft = "10px";
		document.getElementById ("unitReloading").style.pointerEvents = "none";
		document.getElementById ("map").style.left = "-55px";
		document.getElementById ("mapReloading").style.marginRight = "10px";
		document.getElementById ("mapReloading").style.pointerEvents = "none";
		document.getElementById ("action").style.webkitTransitionDuration = "0s";
		document.getElementById ("action").style.opacity = "0";
		slabs.setAttribute("class", "spaceStable");
	}
	else
	{
		slabs.setAttribute("class", "spaceInit");
		setTimeout("slabs.setAttribute('class', '')", 100);
	}
	worldsquareSVG.style.height = (window.innerHeight - h) + "px";
	window.onresize = function () {
		worldsquareSVG.style.webkitTransitionDuration = "0s";
		worldsquareSVG.style.height = (window.innerHeight - h) + "px";
	}
}

function start (){
	if (document.getElementById("stepsNumber").value > 1)
		document.getElementById ("starting").onclick = pause;
	else
		document.getElementById ("starting").onclick = "";
	document.getElementById ("starting").name = 'pause';
	nomoSDK.startMap ();
}