//v0.9.3 (tileSort() test) (night/day test) - By Ziggy Verbeek en Kilian L
var	
	//runs timers once
	runonce = false,

	heightmap = [],
	tiles = [],
	town = [],
	spawnlocs = [],
	spawncount = 0,

	tilesMax = 500, //how many tiles are on the screen?

	//map size
	mapX = tilesMax,
	mapY = tilesMax,

	ballsmin = 1500, //how many balls (generated islands) on the map?

	//camera functionality
	camX = 0,
	camY = 0,

	//zoom mechanics
	maxzoomout = 5;
	zoomlevel = 0,
	minimalimgdraw = 16,
	zoompx = 4;

	//player cordinates
	playerX = 0,
	playerY = 0,

	//how big are the tiles?
	tileSize = 32,
	
	//tile flickering
	tileswitcher = [],
	tileswitcher[0] = true,
	TileSwitcher[1] = true,

	//town (distance is looking for towns if true then dont place a new town)
	towndistance = 15,
	townid = 0,
	minimalwoodstock = Math.floor(Math.random()*3)+1,
	minimalstonestock = 0,
	
	//npc settings
	npc = [],

	//control map / player
	movetoggle = true,

	windowX = Math.floor(window.innerWidth / tileSize)+1,
   	windowY = Math.floor(window.innerHeight / tileSize),

   	realTime = new Date();

//get canvas and draw windowsize
var canvas = document.getElementById("cvboard");

//minify canvas fot content div
canvas.height = window.innerHeight-(tileSize+tileSize+10);
canvas.width = window.innerWidth;

document.getElementById('container').appendChild(canvas);

var context = canvas.getContext('2d');

//what colors does the tiles have?
var tilecolors = [
//water (0)
"#4997FF", //"#197CFF", 

//desert (1, 2)
"#E8C916", "#E8C916", 

//plains (3, 4)
"#5BB822", "#5BB822", 

//trees (5, 6)
"#4B981C", "#4B981C", 

//hills (7, 8)
"#AFE037", "#AFE037",

//mountains (9, 10, 11, 12)
"#CCCCCC", "#CCCCCC", "#CCCCCC", "#FFFFFF",

//buildings (13, 14)
"#FFEC8E", "#5BB822",

//beautiful roads (15,9001)
"#808060", "#808060", "#808060", "#808060", "#808060", "#808060", "#808060", "#808060", "#808060", "#808060", "#808060"
];

//water has no texture thats why it is ""
var tileimgurl = [
//player
"css/icon/smile2.png", 

//desert (1, 2)
"css/icon/desert.png", "css/icon/desertplains.png", 

//plains (3, 4)
"css/icon/plains.png", "css/icon/plains2.png",

//trees (5, 6)
"css/icon/tree.png", "css/icon/tree2.png", 

//hills (7, 8)
"css/icon/hill.png", "css/icon/hill2.png", 

//mountains (9, 10, 11, 12)
"css/icon/mntn.png", "css/icon/mntn2.png", "css/icon/mntn3.png", "css/icon/snow.png",

//buildings (13, 14)
"css/icon/town.png", "css/icon/outpost.png",

// roads (15, 16)
"css/icon/road_l_hor.png", "css/icon/road_l_ver.png",

// (17, 18)
"css/icon/road_l_int.png", "css/icon/road_l_int_e.png",

// (19, 20)
"css/icon/road_l_int_n.png", "css/icon/road_l_int_s.png",

// (21, 22)
"css/icon/road_l_int_w.png", "css/icon/road_l_cur_ne.png",

// (23, 24)
"css/icon/road_l_cur_nw.png", "css/icon/road_l_cur_se.png",

// roads end (25)
"css/icon/road_l_cur_sw.png",

//test npcs (26)
"css/icon/smile3.png"
];

//what should it say when you click a tile?
var generictilename = [
"water", 

"cactus", "desert", 

"plains", "plains", 

"tree", "tree",

"hills", "hills",

"mountain", "mountain", "mountain", "mountain snow"];

//preload images
for (var i = 0; i < tileimgurl.length; i++)
{
	document.getElementById('preload').innerHTML+="<img src='"+tileimgurl[i]+"'/>"; 
}
//document.getElementById('preload').innerHTML=""; 

//our old townnames
var townnames = [];
townnames[0] = ["New ", "Old ", "Belle-", "Great ", "Fine ", "Fort ", "Grand ", "Jolly ", "Los ", "Sugary ", "Spooky ", "Lonely ", "Mystic ", "Golden ", "Port ", "San ", "Muddy ", "Snowy ", "Camp ", "Rio ", "Santa ", "Les ", "Cote des ", "El ", "Long ", "Baja ", "Grassy ", "Rosey ", "Lake ", "Hillside ", "Saint ", "Novi ", "Lone ", "Forgotten ", "Priest's ", "Shady ", "Abandoned ", "Hopeless ", "Fore ", "Virgin ", "Haunted ", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", ""];
townnames[1] = ["Babble", "Courtney", "Mansel", "Winston", "Apple", "Horse", "Otter", "Scorpion", "Banana", "Baby", "Merkel", "Dinkle", "Lumber", "Middle", "Moose", "Camel", "Glenn", "Or", "William", "Black", "White", "Yellow", "Wood", "Stone", "Iron", "Goat", "Gold", "Red", "Copper", "Mud", "John", "Dave", "Snow", "Turkey", "Red", "Cracker", "Miccous", "Mingle", "Fiddle", "Sparkle", "Cox", "Flint", "Triangle", "Gar", "Man", "Power", "Fish", "Bear", "Coffee", "Little", "Ever", "Bread", "Wheat", "Yarn", "Pannekoeken", "Cookie", "Mother", "Tallapoose", "Yazoo", "Skeleton", "Boo", "Fire", "Zulu", "Water", "Sky", "Christmas", "Thanksgiving", "Indiana", "Pine", "Oak", "Willow", "Maple", "Ogre", "Goblin", "Trollen", "Amster", "Bone", "Children", "Bingo", "Wanker", "Church", "God", "Locust", "Crab", "Fertile", "Ash", "Mattock", "Manter", "Yangle", "Work", "Butter", "Jelly", "Liberty", "Milk", "Glob", "Jack", "Duffel", "Corner", "Rabbit", "Christ", "School", "Tornado", "Tsunami", "Earthquake", "Odin", "Zeus", "Fork", "Spoon", "Machete", "Friend", "Kindle", "Chicken", "Goose", "Duck", "Croc", "Alligator", "Rock", "Scissor", "Candle", "Gust", "Chipper", "Spider", "Lady", "Gentle", "Clay", "Serb", "Windmill", "Citron", "Lemon", "Melon", "Paper", "Flash", "Frog", "Toad", "Snake", "Bell", "Ringing", "Pineapple", "Meat", "Super", "Wax", "Herb", "Almond", "Dagger", "Pilk", "Silk", "War"];
townnames[2] = [" Field", "heim", "ville", " City", " Valley", " Town", "shire", "-Pablos", " Village", "ton", "dale", "list", "ington", "-Ex", "lington", "lee", " Harbor", "ey", "moore", "loo", " Hole", " Well", " Plateau", " Swamp", "-Roche", " Rogue", " Crater", " Paradise", " Hill", " Hot", " Station", " Arm", " Coast", " Beach", "daal", " Stad", "er", "ard", "gaard", "garde", "mont", "burg", " Platte", "wood", " Park", " Springs", "green", "ery", " Sad", " Peak", " Edge", " High", "way", "craft", "fall", "clap", " Lodge", "Hope", " Chance", " Vault", "Cafe", "-Ginn", "dam", "'s Last Stand"];

//----- generation start
function newGen()
{
	//making shapes
	for(var i = 0; i < mapX; i++)
	{
		heightmap[i] = [];
		tiles[i] = [];
		for(var j = 0; j < mapY; j++)
		{
			heightmap[i][j] = 0;
			tiles[i][j] = 0;
		}
	}

	var max = 0;
	var balls = ballsmin + Math.floor(Math.random() * ballsmin);
	
	for(var i = 0; i < balls; i++)
	{
		var ballx = Math.floor(Math.random()*(mapX-30)+15);
		var bally = Math.floor(Math.random()*(mapY-30)+15);
		var ballr = Math.floor(Math.random()*(10)+5);

		for(var x = -ballr; x <= ballr; x++)
		{
			for(var y = -ballr; y <= ballr; y++)
			{
				var h = ballr*ballr - x*x - y*y;
				
				if(h > 0)
				{
					var cx = ballx+x;
					var cy = bally+y;

					if(cx > 0 && cx <= mapX && cy > 0 && cy <= mapY)
					{
						
						var hh = heightmap[cx][cy] + h;
						heightmap[cx][cy] = hh;
						if(hh > max)
						{
							max = hh;
						}
					}
				}
			}
		}
	}

	//defining last bits:
	townid = 0;
	spawncount = 0;
	var scale = 100/max;
	for(x = 0; x < mapX; x++)
	{
		for(y = 0; y < mapY; y++)
		{
			hh = Math.floor(heightmap[x][y] * scale);
			heightmap[x][y] = hh;

			if(hh >= 70){ //snow
				tiles[x][y] = 12;
			}else if(hh >= 50){ //mountains
				if(tileSort(50, 0))
				{
					if(tileSort(50, 0))
					{
						tiles[x][y] = 10;
					}else{
						tiles[x][y] = 11;
					}
				}else{
					tiles[x][y] = 9;
				}
			}else if(hh >= 40){ //hills
				if(tileSort(50, 0))
				{
					tiles[x][y] = 8;
				}else{
					tiles[x][y] = 7;
				}
				addSpawnLoc(x, y);
			}else if(hh >= 6){ //normal ground
								
				if(tileSort(98, 0)) //towns
				{
					if(tileSort(90, 0)) //another check
					{
						//looks if theres a town nearby, else place plain land
						var tdist = Math.floor(Math.random()*(towndistance))+towndistance;
						if(tileOutRange(x, y, 13, tdist))
						{
							var townname = "";

							for(var i = 0; i < townnames.length; i++)
							{
								townname += String(townnames[i][Math.floor(Math.random()*townnames[i].length)]);
							}
							tiles[x][y] = 13;
							town[townid] = [];
							town[townid][0] = townname;
							town[townid][1] = x;
							town[townid][2] = y;
							town[townid][3] = minimalwoodstock;
							town[townid][4] = minimalstonestock;
							console.log(town[townid][1]+","+""+town[townid][2]+" - (tid: "+townid+") name: "+ town[townid][0]);
							townid++;

						}else{
							
							if(tileSort(50, 0)) //differnt plains
							{
								tiles[x][y] = 3;
							}else{
								tiles[x][y] = 4;
							}
							addSpawnLoc(x, y);
						}

					}else{ //just plain
						if(tileSort(60, 0)) //watchtower or plains
						{
							tiles[x][y] = 14;
						}else{
							
							if(tileSort(50, 0)) //differnt plains
							{
								tiles[x][y] = 3;
							}else{
								tiles[x][y] = 4;
							}
							addSpawnLoc(x, y);
						}
					}
				}else{ //plains or trees
					if(tileSort(40, 50))
					{
						if(tileSort(50, 0)) //differnt trees
						{
							tiles[x][y] = 5;
						}else{
							tiles[x][y] = 6;
						}
					}else{
						
						if(tileSort(50, 0)) //differnt plains
						{
							tiles[x][y] = 3;
						}else{
							tiles[x][y] = 4;
						}
						addSpawnLoc(x, y);
					}
				}
			}else if(hh >= 1){
				if(tileSort(8, 0)) //cactus or sandplains
				{
					tiles[x][y] = 2;
				}else{
					tiles[x][y] = 1;
				}
			}else{
				tiles[x][y] = 0;
			}
		}
	}

	console.log("-------------- total "+(townid-1)+" towns ----------");
}

function addSpawnLoc(x, y)
{
	spawnlocs[spawncount] = [];
	spawnlocs[spawncount][0] = x;
	spawnlocs[spawncount][1] = y;
	return spawncount++;
}

function tileSort(range, extraoff)
{
	if(Math.floor(Math.random()*(100)-extraoff) > range)
	{
		return true
	}else{
		return false
	}
}

//----- game settings
function setup(notsetup)
{
	//document.getElementById('board').innerHTML = newGen();
	//var bwidth = ((border/100)*90);
	//document.getElementById('board').style.width = bwidth+'px';
	
	/*var cookie = readCookie('vangamemapsave')
	if(cookie)
	{

	}else{*/
		newGen();
	//}
	
	//sets the camera somewhat in the middle of the map
	var randspawn = Math.floor(Math.random()*spawncount);

	playerX = spawnlocs[randspawn][0];
	playerY = spawnlocs[randspawn][1];

	camX = spawnlocs[randspawn][0]-8;
	camY = spawnlocs[randspawn][1]-8;

	if(spawnlocs[randspawn][0] > (tilesMax-windowX))
	{
		camX = camX-tileSize;
	}
	if(spawnlocs[randspawn][1] > (tilesMax-windowY))
	{
		camY = camY-tileSize;
	}
	//console.log(camX+"-"+camY +"||"+ windowX +"-"+ windowY);

	//npcController(0);
	npcController(1);
	canvasSetup();

	//for running code that isnt supposed to run again
	if(runonce == false)
	{
		//player flicker
		setInterval(function() { TileSwitcher(0); }, 500);

		//npc flicker
		setInterval(function() { TileSwitcher(1); }, 500);
	
		//always on the end
		runonce = true;
	}
}

//----- canvas loading
function canvasSetup()
{
    var canvasx = 0, canvasy = 0;
    var t = realTime.getHours();
    
    document.getElementById('time').innerHTML = t + "h realtime / ingame";

    context.clearRect(0, 0, canvas.width, canvas.height); 

    canvas.style.backgroundColor = tilecolors[0];
    for(var x = camX; x < camX+windowX; x++)
	{
		for(var y = camY; y < camY+windowY; y++)
		{
			context.beginPath();
			context.rect(canvasx, canvasy, tileSize, tileSize);
			if(tiles[x][y] >= 0)
			{
				if(t > 8 && t < 21)
				{
					context.fillStyle = tilecolors[tiles[x][y]];
				}else{
					context.fillStyle = "#252520";
				}	
				//context.fillStyle = tilecolors[tiles[x][y]];
			}
			context.fill();
			
			//throw border away when done testing?
			context.lineWidth = 0;
			context.strokeStyle = 'grey';
			context.stroke();

			if(tileSize > minimalimgdraw)
			{
				var img = new Image();
				if(x == playerX && y == playerY)
				{
					if(tiles[playerX][playerY] > 0)
					{
						img.src = tileimgurl[0];
					}
				}else{
					if(tiles[x][y] > 0)
					{
			    		img.src = tileimgurl[tiles[x][y]];	 
					}
				}
				//+2 for image centering
				context.drawImage(img, canvasx+2, canvasy+2, tileSize-4, tileSize-4);
			}
			canvasy = canvasy+tileSize;	
		}
		canvasx = canvasx+tileSize;
		canvasy = 0;
	}
	return true;
}

function tileOutRange(x, y, tiletype, distance)
{
	for(x2 = x+distance; x2 > (x-distance); x2--)
	{
		for(y2 = y+distance; y2 > (y-distance); y2--)
		{
			if(x2 > distance && y2 > distance && x2 < mapX-distance && y2 < mapY-distance)
			{
				if(tiles[x2][y2] == tiletype)
				{
					return false;
				}
			}
		}	
	}
	return true;
}

//----- button movement
function playerMovement(dir)
{
	if(dir == 'left')
	{
		if(tiles[playerX-1][playerY] != 0)
		{
			playerX = playerX - 1;
		}
	}
	if(dir == 'right')
	{
		if(tiles[playerX+1][playerY] != 0)
		{
			playerX = playerX + 1;
		}
	}
	if(dir == 'up')
	{

		if(tiles[playerX][playerY-1] != 0)
		{
			playerY = playerY - 1;
		}

	}
	if(dir == 'down')
	{
		if(tiles[playerX][playerY+1] != 0)
		{
			playerY = playerY + 1;
		}
	}
	npcController(2);
	canvasSetup();
	return true;
}

//----- key movement
function mapMovement(dir)
{
	if(dir == 'left')
	{
		if(camX > 0)
		{
			camX = camX - 1;
		}
	}
	if(dir == 'right')
	{
		if(camX < mapX-tileSize)
		{
			camX = camX + 1;
		}
	}
	if(dir == 'up')
	{
		if(camY > 0)
		{
			camY = camY - 1;
		}

	}
	if(dir == 'down')
	{
		if(camY < mapY-tileSize)
		{
			camY = camY + 1;
		}
	}
	canvasSetup();
	return true;
}

function togglePlayerMapCtrls()
{
	if(movetoggle)
	{
		movetoggle = false;
	}else{
		movetoggle = true;
	}
}

document.onkeyup = function(e) {
    switch (e.keyCode) {
        case 73: 
            mapZoom('in'); // zoom in
            break;
        case 79: 
            mapZoom('out'); // zoom out
            break;
        case 67: 
            togglePlayerMapCtrls(); // change moving with player or map
            break;
        case 37:
	        if(movetoggle)
	        {
	            mapMovement('left');  
	        }else{
	        	playerMovement('left');
	        }
        	break;
        case 38:
	        if(movetoggle)
	        {
	            mapMovement('up');  
	        }else{
	        	playerMovement('up');
	        }
            break;
        case 39:
	        if(movetoggle)
	        {
	            mapMovement('right');  
	        }else{
	        	playerMovement('right');
	        }
            break;
        case 40:
	       	if(movetoggle)
	        {
	            mapMovement('down');  
	        }else{
	        	playerMovement('down');
	        }
            break;
    }
};

//---- save/load the map (cookies)
function saveMap()
{
	var save = '';
	
	for(var x = 0; x < mapX; x++)
	{
		for(var y = 0; y < mapY; y++)
		{	
			save += tiles[x][y];
		}
		save += ",";
	}
	return save;
}

//----- click events
canvas.addEventListener('click', function(event) {
	var ex = event.pageX - canvas.offsetLeft,
        ey = event.pageY - canvas.offsetTop,
        elements = [],
        cx = 0,
        cy = 0;

    	cx = Math.floor(ex / tileSize);
    	cy = Math.floor(ey / tileSize);

		cx = cx+camX;
		cy = cy+camY;
		
		clickedTileInfo(cx, cy);
		
}, false);

function mapZoom(zoom)
{
	if(zoom == 'in' && zoomlevel > 0)
	{
		zoomlevel--;
		tileSize += zoompx;
		windowX = Math.floor(window.innerWidth / tileSize)+1,
   		windowY = Math.floor(window.innerHeight / tileSize);
		
		return canvasSetup();
	}
	else if(zoom == 'out' && zoomlevel < maxzoomout)
	{
		zoomlevel++;
		tileSize -= zoompx;
		windowX = Math.floor(window.innerWidth / tileSize)+1,
   		windowY = Math.floor(window.innerHeight / tileSize);
		
		return canvasSetup();
	}
}

function clickedTileInfo(x, y)
{
	var string = "";
	for(var i = 0; i < npc.length; i++)
	{
		if(x == npc[i][1] && y == npc[i][2])
		{
			string = "<p>clicked on "+npc[i][6]+" ("+x+"-"+y+"-"+tiles[x][y]+")</p>";
			return document.getElementById('clickinfo').innerHTML = string;
			break;
		}
	}
	if(x == playerX && y == playerY)
	{
		string = "<p>clicked on player ("+x+"-"+y+"-"+tiles[x][y]+")</p>";	
	}else{
		if(tiles[x][y] < 13)
		{
			string = "<p>clicked on "+generictilename[tiles[x][y]]+" ("+x+"-"+y+"-"+tiles[x][y]+")</p>";	
		}else if(tiles[x][y] == 13){
			for(var i = 0; i < town.length; i++)
			{
				if(town[i][1] == x && town[i][2] == y)
				{
					string = "<p>clicked on '"+town[i][0]+"' ("+x+"-"+y+"-"+tiles[x][y]+" townid "+i+" | woodstock = "+town[i][3]+", stonestock = "+town[i][4]+")</p>";		
					return document.getElementById('clickinfo').innerHTML = string;
					break;
				}
			}	
		}else{
			string = "<p>clicked on "+x+"-"+y+"-"+tiles[x][y]+"</p>";	
		}
		
	}
	return document.getElementById('clickinfo').innerHTML = string;
}

function closeWindow()
{
	/*var cookie = readCookie('vangamemapsave')
	if(cookie)
	{
		console.log("hallo daar " +cookie);
		eraseCookie('vangamemapsave');
	} else {
		var map = saveMap();
		createCookie('vangamemapsave', map, 1);
	}*/
	document.getElementById('setup').innerHTML = "";
	document.getElementById('setup').style.display = "none";
	return true;
}

//update a single tile
function TileSwitcher(type)
{
	//player flicker
	if(type == 0) //npc flicker
	{
		//throw border away when done testing?
		/*context.lineWidth = 0;
		context.strokeStyle = 'grey';
		context.stroke();*/		

		if(tileswitcher[type]){
			tileswitcher[type] = false;
		}else{
			tileswitcher[type] = true;
		}

		var ux = (playerX-camX)*tileSize;
		var uy = (playerY-camY)*tileSize;
		//context.clearRect(ux, uy, 32, 32);
		
		var img = new Image();
		
		context.beginPath();
		context.rect(ux, uy, tileSize, tileSize);
		context.fillStyle = tilecolors[tiles[playerX][playerY]];
		context.fill();

		if(tileSize > minimalimgdraw)
		{	
			if(tileswitcher[type])
			{	
				img.src = tileimgurl[tiles[playerX][playerY]];
			}else{
				img.src = tileimgurl[0];
			}
			context.drawImage(img, ux+2, uy+2, tileSize-4, tileSize-4);
		}else{ //make only player position visible by maximum outzooming
			img.src = tileimgurl[0];
			context.drawImage(img, ux-4, uy-4, tileSize+8, tileSize+8);
		}
	}else
	//----------------------------------
	if(type == 1) //npc flicker
	{

		if(tileswitcher[type]){
			tileswitcher[type] = false;
		}else{
			tileswitcher[type] = true;
		}
		if(tileSize > minimalimgdraw)
		{
			for(var i = 0; i < npc.length; i++)
			{	
				var npcX = npc[i][1];
				var npcY = npc[i][2];

				ux = (npcX-camX)*tileSize;
				uy = (npcY-camY)*tileSize;

				var img = new Image();
				
				context.beginPath();
				context.rect(ux, uy, tileSize, tileSize);
				context.fillStyle = tilecolors[tiles[npcX][npcY]];
				context.fill();

					
				if(tileswitcher[type])
				{	
					img.src = tileimgurl[tiles[npcX][npcY]];
				}else{
					img.src = tileimgurl[npc[i][3]];
				}
				context.drawImage(img, ux+2, uy+2, tileSize-4, tileSize-4);
				
			}
		}
	}
}

//controlling npcs (CLEANUP)
function npcController(type)
{
	if(type == 0) //test npc
	{
		//resets npc array
		npc = [];

		//creates npc
		npcCreate(0, 0, (playerX+2), (playerY+2), 26, 2, false, 'test npc (bandit)');
	}
	if(type == 1) //spawning npcs if minimal is met
	{
		var npccount = 0; townid = 0; npc = [];
		for(var i = npccount; i < town.length; i++)
		{
			npcCreate(i, 1, town[townid][1], town[townid][2], 26, 2, false, 'npc town worker (npc id '+i+" | townid "+townid+") from town '"+town[townid][0]);

			//townid to npc and otherwise
			npc[i][9] = townid;
			town[townid][5] = i;
			
			//end
			townid++;
		}
	}
	if(type == 2) //movement of npc
	{
		var range = 5;
		for(var i = 0; i < npc.length; i++)
		{
			var checkwhere = [];
			checkwhere[0] = [(npc[i][1]+1), npc[i][2]];
			checkwhere[1] = [(npc[i][1]-1), npc[i][2]];
			checkwhere[2] = [npc[i][1], (npc[i][2]+1)];
			checkwhere[3] = [npc[i][1], (npc[i][2]-1)];
			checkwhere[4] = [(npc[i][1]+1), (npc[i][2]+1)];
			checkwhere[5] = [(npc[i][1]-1), (npc[i][2]+1)];
			checkwhere[6] = [(npc[i][1]+1), (npc[i][2]-1)];
			checkwhere[7] = [(npc[i][1]-1), (npc[i][2]-1)];
			
			//regular bandit
			if(npc[i][0] == 0)
			{
				if(npc[i][5])
				{

				}else{
					//detected player?
					var choosed = 0;
					var stop = false;
					do {
						choosed = Math.floor(Math.random() * checkwhere.length);
						if(isNotWater(checkwhere[choosed][0],checkwhere[choosed][1]))
						{
							npc[i][1] = checkwhere[choosed][0];
							npc[i][2] = checkwhere[choosed][1];
							stop = true;
						}
					}
					while(stop != true);
				}
			}

			//villager
			if(npc[i][0] == 1)
			{
				if(npc[i][7] == 0)
				{
					//woodcutter job
					npc[i][7] = 1;
				}
				
				if(npc[i][7] == 1)
				{
					var startradx = town[npc[i][9]][1]-range,
						startrady = town[npc[i][9]][2]-range,
						endradx = town[npc[i][9]][1]+range,
						endrady = town[npc[i][9]][2]+range,
						choicecount = 0;

					if(npc[i][8] == 0)
					{ 
						//target tile pos
						npc[i][10] = [];
						npc[i][11] = [];

						//raduis around the town center
						for(var j = startradx; j <= endradx; j++)
						{
							for(var k = startrady; k <= endrady; k++)
							{
								//check for trees
								if(tiles[j][k] == 5 || tiles[j][k] == 6)
								{
									npc[i][10][choicecount] = j;
									npc[i][11][choicecount] = k;
									choicecount++;
								}

							}
						}

						if(choicecount > 3)
						{
							npc[i][8] = 1;
							npc[i][12] = Math.floor(Math.random()*choicecount);
							npc[i][13] = false;
						}else{
							npc[i][8] = 2;
							//input "plant trees" here
						}
					}else if(npc[i][8] == 1){
						
						//pathfinding (basic)
						if(moveTownNPCAtoB(i)) //only true if TARGET is reached
						{	
							if(npc[i][13]) //is back at start?
							{
								npc[i][8] = 0;

								//add wood to town stock
								town[npc[i][9]][3] = town[npc[i][9]][3] + Math.floor((Math.random()*2)+1);
							}else{
								
								if(Math.floor(Math.random()*(100)) > 50) //making trees into lil D.I.R.T.Y plain
								{
									tiles[npc[i][10][npc[i][12]]][npc[i][11][npc[i][12]]] = 3;
								}else{
									tiles[npc[i][10][npc[i][12]]][npc[i][11][npc[i][12]]] = 4;
								}

								//return to town
								npc[i][13] = true;
								npc[i][10][npc[i][12]] = town[npc[i][9]][1];
								npc[i][11][npc[i][12]] = town[npc[i][9]][2];


							}
							
						}
					
					
					}

				}
			
			}

		
		}
	}
}

function npcCreate(npcid, type, x, y, imgid, health, detect, name)
{
	npc[npcid] = [];
	//id of npc
	npc[npcid][0] = type;

	//npc pos x
	npc[npcid][1] = x;
	
	//npc pos y
	npc[npcid][2] = y;
	
	//npc img
	npc[npcid][3] = imgid;

	//health of npc (2 health)
	npc[npcid][4] = health;

	//detected player?
	npc[npcid][5] = detect;
	
	//name of npc
	npc[npcid][6] = name;

	if(type == 1)
	{
		//job/task
		npc[npcid][7] = 0;

		//current status job/task
		npc[npcid][8] = 0;
	}
}

function moveTownNPCAtoB(npcid)
{
	if(npc[npcid][1] != npc[npcid][10][npc[npcid][12]] || npc[npcid][2] != npc[npcid][11][npc[npcid][12]])
	{	
		//x
		if(npc[npcid][1] < npc[npcid][10][npc[npcid][12]]){
			npc[npcid][1] = npc[npcid][1]+1;
		}
		if(npc[npcid][1] > npc[npcid][10][npc[npcid][12]]){
			npc[npcid][1] = npc[npcid][1]-1;	
		}
		
		//y
		if(npc[npcid][2] < npc[npcid][11][npc[npcid][12]]){
			npc[npcid][2] = npc[npcid][2]+1;
		}
		if(npc[npcid][2] > npc[npcid][11][npc[npcid][12]]){
			npc[npcid][2] = npc[npcid][2]-1;
		}
		
		if(npc[npcid][1] == npc[npcid][10][npc[npcid][12]] && npc[npcid][2] == npc[npcid][11][npc[npcid][12]]){
			return true;
		}
		return false;

	}else if(npc[npcid][1] == npc[npcid][10][npc[npcid][12]] && npc[npcid][2] == npc[npcid][11][npc[npcid][12]]){
		return true;
	}
}

function isNotWater(x, y){
	return (tiles[x][y] > 0);
}

// EPIC CVB-MADE TOWN GEN STUFF YOU WILL LOVE

function isRoad(x,y){
	return (tiles[x][y] > 14 && tiles[x][y] < 26);
}

function updateRoad(x,y){
	if (isRoad(x,y)){
		var adjacentRoads = [];
		adjacentRoads[0]=isRoad(x-1,y);
		adjacentRoads[1]=isRoad(x,y-1);
		adjacentRoads[2]=isRoad(x+1,y);
		adjacentRoads[3]=isRoad(x,y+1);
		
		
		
	}
}

//--- cookies --- by http://www.quirksmode.org/js/cookies.html

function createCookie(name,value,days) {
	if (days) {
		var date = new Date();
		date.setTime(date.getTime()+(days*24*60*60*1000));
		var expires = "; expires="+date.toGMTString();
	}
	else var expires = "";
	document.cookie = name+"="+value+expires+"; path=/";
}

function readCookie(name) {
	var nameEQ = name + "=";
	var ca = document.cookie.split(';');
	for(var i=0;i < ca.length;i++) {
		var c = ca[i];
		while (c.charAt(0)==' ') c = c.substring(1,c.length);
		if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
	}
	return null;
}

function eraseCookie(name) {
	createCookie(name,"",-1);
}

//---- NOT USED --------------------------------------------------------------------------------
//show map in divs (not used)

//normal view
/*var dv = ''; 
for(var x = 0; x < mapX; x++)
{
	dv += "<div class='tt-row'>"; j = false;

	for(var y = 0; y < mapY; y++)
	{
		if(j)
		{	
			dv += "<div onclick='highlight("+i+")' id='tile-"+i+"' value='"+i+"' x='"+x+"' y='"+y+"' type='"+tiles[x][y]+"' class='tt tt"+tiles[x][y]+" even'><div class='left'></div><div class='middle'></div><div class='right'></div></div>";//"+x+"-"+y+"
			j=false;
		}else{
			dv += "<div onclick='highlight("+i+")' id='tile-"+i+"' value='"+i+"' x='"+x+"' y='"+y+"' type='"+tiles[x][y]+"' class='tt tt"+tiles[x][y]+"'><div class='left'></div><div class='middle'></div><div class='right'></div></div>"; //"+x+"-"+y+"
			j=true;
		}
		i++;
	}
	dv += "</div>";
}
return dv;*/

/* debug information
document.getElementById('content').innerHTML += "<p>";
var count = 0;
for(x = 0; x < mapX; x++) //cursor test
{
	for(y = 0; y < mapY; y++)
	{
		if(tiles[x][y] > 0 && tiles[x][y] != 12)
		{
			count++;
			}
	}
}
document.getElementById('content').innerHTML += count;
document.getElementById('content').innerHTML += " avaible spawn locations, spawned at "+playerX+"-"+playerY+".</p>";
*/