/**
 * Astarond Javascript file
 **/
 
astarond = new Object();
// ID of map background element in DOM
astarond.backgroundImageID = 'astarond_background';
// ID of map overlay element in DOM
astarond.mapImageID = 'astarond_map';
// ID of walkarea element in DOM
astarond.walkareaImageID = 'astarond_walkarea';
// ID of mapinfo element in DOM
astarond.mapinfoID = 'astarond_mapinfo';
astarond.tempimagefolder = "http://test.rocards.org/tempimages";

// variable for warp
astarond.warp = true;
astarond.hooks = new Object();
astarond.registerIndex = 0;
	
astarond.testscript = function()
{
	x_fetchScript(4, roplayer.receiveScript);
}

astarond.init = function()
{
	this.backgroundImage = document.getElementById(this.backgroundImageID);
	this.mapImage = document.getElementById(this.mapImageID);
	this.walkareaImage = document.getElementById(this.walkareaImageID);
	this.mapinfoArea = document.getElementById(this.mapinfoID);
		
	if (window.addEventListener)
		this.mapinfoArea.addEventListener('DOMMouseScroll', astarond.mousewheel, false);
	this.mapinfoArea.onmousewheel = astarond.mousewheel;
	
	this.reset();
	
	this.exclude = new Object({363:true,364:true,365:true,366:true,367:true,368:true,369:true,370:true,375:true,371:true,372:true,373:true,374:true,376:true,377:true,378:true,379:true,501:true,500:true,499:true,498:true,497:true,496:true,495:true,494:true,491:true,490:true,448:true});
	
	// add onClick events to map divs
	for (var i in mapinfo)
	{
		var div = document.getElementById('ID' +i);
		if (div != undefined)
		{
			div.onclick = function()
			{
				astarond.openMap(this.id.substr(2));
			}
		}
	}
}

astarond.reset = function()
{
	clearMarks(this.mapImages);
	clearMarks();
	clearMarks(this.flags);
	
	this.mode = 0;
	this.mapID = null;
	this.mapname = null;
	this.request = new Array();
	this.mapdata = new Object();
	this.mapImages = new Array();
	this.registers = new Array();
	this.flags = new Array();	
	this.hooks['onMapLoad'] = new Array();
	this.hooks['onRouteReceive'] = new Array();	

	this.registers[0] = new Array(-1, document.createElement('div'), new Array(), new Array(), false);
	this.registers[1] = new Array(-1, document.createElement('div'), new Array(), new Array(), false);
	this.registers[2] = new Array(-1, document.createElement('div'), null, null, false);
	
	var vars = new Array('s_map', 's_map_id', 's_x', 's_y', 'd_map', 'd_map_id', 'd_x', 'd_y');
	
	for (var val in vars)
	{
		document.getElementsByName(vars[val])[0].value = "";
	}
}

astarond.mousewheel = function(event)
{
	if (astarond.registerIndex != 2)
		return;
		
    var delta = 0;
    
    if (!event)
		event = window.event;
            
    if (event.wheelDelta)
		delta = event.wheelDelta / 120;
  	else if (event.detail)
		delta = -event.detail / 3;

    if (delta)
		astarond.moveMapinfoArea(delta);
 
	event.returnValue = false;
}

astarond.moveMapinfoArea = function(offset, relative)
{
	if (relative == null)
		relative = true;
		
	var top = parseInt(this.mapinfoArea.style.top);
	
	if (relative)
		top += offset * 10;
	else
		top = offset;
	
	if (top > 0)
		top = 0;
	if (top < this.maxScrollHeight && this.maxScrollHeight < 0)
	{
		top = this.maxScrollHeight;
	}
			
	var scrollBarPosition = (this.maxScrollHeight != null && this.maxScrollHeight != 0) ? (top / this.maxScrollHeight) : 0;
	
	var slider = document.getElementById('slider');
	
	slider.style.top = (308 * scrollBarPosition) + "px";
	this.mapinfoArea.style.top = top + "px";
}

astarond.redrawRegisters = function()
{
	this.registerChange(this.registerIndex);
}

astarond.registerChange = function(registerID)
{
	if (registerID != this.registerIndex)
	{
		document.getElementById("registerlabel_" +this.registerIndex).className = "register_inactive";
		document.getElementById("registerlabel_" +registerID).className = "register_active";	
		
	//	this.mapinfoArea.style.top = "0px";	
	//	this.moveMapinfoArea(0, false);
	
	}
	
	if (!this.registers[registerID][4])
	{
		Worldmap.hideElement('sliderbox');
	}
	else
	{
		Worldmap.showElement('sliderbox');
	}
	
	this.moveMapinfoArea(0, false);
	
	this.registerIndex = registerID;
	astarond.mapinfoArea.innerHTML = "";
	
	var newDiv = this.registers[this.registerIndex][1].cloneNode(true);
	newDiv.style.width = '100%';
	
	astarond.mapinfoArea.appendChild(newDiv);
}

astarond.addHook = function(hookType, hookFunc, thisObj)
{
	this.hooks[hookType].push(new Array(hookFunc, thisObj));	
}

astarond.applyHooks = function(hookType)
{
	for (i in astarond.hooks[hookType])
	{
		astarond.hooks[hookType][i][0](astarond.hooks[hookType][i][1]);
	}
	
	astarond.hooks[hookType] = new Array();
}

astarond.markMap = function(x, y)
{
	x_markMap(astarond.mapID, x, y, this.receiveMark);
}

astarond.receiveMark = function(ret)
{
	astarond.mapImage.src = "scripts/astarond/" +ret;
}

astarond.submitSearch = function()
{		
	var s_map_id = document.getElementsByName('s_map_id')[0].value;

	if (s_map_id == "")
		return;

	var request = new Object();

	var vars = new Array('s_x', 's_y', 'd_map_id', 'd_x', 'd_y');
	
	for (var val in vars)
	{
		var current_var = document.getElementsByName(vars[val])[0].value;
		if (current_var == "" || current_var < 0)
			return;
			
		request[vars[val]] = document.getElementsByName(vars[val])[0].value;
	}
	
	this.setLoadingState(true);
	x_calcMapRoute(s_map_id, request['s_x'], request['s_y'], request['d_map_id'], request['d_x'], request['d_y'], this.warp, this.worldrouteReceived);
	astarond.modeChange(0);
}

astarond.changedSrcMapName = function(obj)
{
	var mapID = this.getMapIDByName(obj.value);
	
	if (mapID != null)
	{
		document.getElementsByName('s_map_id')[0].value = mapID;
		clearMarks(this.flags);
		markMap(mapID, mark_start, this.flags);
		this.modeChange(1);
	}
	else
	{
		alert("Map name not found: " +obj.value);
	}
}

astarond.changedDestMapName = function(obj)
{
	var mapID = this.getMapIDByName(obj.value);
	
	if (mapID != null)
	{
		document.getElementsByName('d_map_id')[0].value = mapID;
		markMap(mapID, mark_dest, this.flags);
		this.modeChange(0);
	}
	else
	{
		alert("Map name not found: " +obj.value);
	}
	
}

astarond.getMapIDByName = function(mapname)
{
	for (var m in mapinfo)
		if (mapinfo[m][0] == mapname)
			return m;
			
	return null;
}

astarond.worldrouteReceived = function(ret)
{
	clearMarks();
		
	astarond.setLoadingState(false);
	
	astarond.modeChange(0);
	ret = ret.split("::");

	if (ret[0] == 'oerr')
	{
		alert ("Error: " +ret[1]);
		return;
	}
	ret = ret[1].split('&');
	
	astarond.mapdata = new Object();
	
	var routeinfo = astarond.registers[2][1];
	routeinfo.innerHTML = "";
	
	var retdesc;

	astarond.routesteps = 0;
	astarond.registers[2][4] = false;
	
	for (var i in ret)
	{
		var retData = ret[i].split(';');
		
		if (astarond.mapdata[retData[0]] == undefined)
			astarond.mapdata[retData[0]] = new Array();
			
		astarond.mapdata[retData[0]].push(retData[1]);
		
		if (retData[0] == astarond.mapID)
			astarond.processMapImages(retData[0]);
		
		retdesc = retData[1].split('_');
		retdesc = mapinfo[retData[0]][0];
		
		var div = document.createElement('div');
		div.className = "routelink";
			
		var a = document.createElement('a');
		a.innerHTML = "&nbsp;" +((++astarond.routesteps < 10 ? " " : "") +astarond.routesteps) +"&nbsp;&rArr;" +retdesc;
		a.href = 'javascript:astarond.openMap(' +retData[0]+ ');';
		
		div.appendChild(a);
		routeinfo.appendChild(div);
		
		var smalldiv = document.getElementById('ID' +retData[0]);
		
		if (smalldiv == undefined)
			continue;
			
		var thumb = document.createElement('img');
		thumb.src = astarond.tempimagefolder +"/" +retData[1].replace(/\.png/, "_t.png");
		
		thumb.style.width = smalldiv.style.width;
		thumb.style.height = smalldiv.style.height;
		addMark(smalldiv, thumb);
	}
	
	astarond.maxScrollHeight = -(astarond.routesteps + 1) * 18 + 432;
	
	if (astarond.maxScrollHeight < 0)
	{
		astarond.registers[2][4] = true;
	}
		
	astarond.registerChange(2);
	
	astarond.applyHooks('onRouteReceive');
}

astarond.receiveMapInfo = function(ret)
{
	
	var retinfo = ret.split("---");
	
	ret = retinfo[0].split("?");

	var mapinfoArea = astarond.registers[0][1];
	mapinfoArea.innerHTML = "";
	
	var areamaps = document.getElementById('astarond_areamap');
	
	while (areamaps.hasChildNodes())
			areamaps.removeChild(areamaps.firstChild);
	
	var addedMaps = new Object();
	
	var i = 0;

	for (var p in ret)
	{
		var portalinfo = ret[p].split('&');

		if (portalinfo[5] == 0)
			astarond.addAreaMap(portalinfo[1], portalinfo[2], portalinfo[0], i, portalinfo[5] == 0 ? 'Portal to ' : 'Warp to ');
	
		if (addedMaps[portalinfo[0]] != undefined && addedMaps[portalinfo[0]] == portalinfo[5])
			continue;
			
		addedMaps[portalinfo[0]] = portalinfo[5];
			
		var targetMapName = mapinfo[portalinfo[0]][0];
		
		var div = document.createElement('div');
		div.className = "routelink";
		
		var a = document.createElement('a');
		a.href = 'javascript:astarond.openMap(' +portalinfo[0]+ ');';
		a.innerHTML = "&nbsp;&rArr;" +targetMapName;
		
		
		if (portalinfo[5] > 0)
		{
			if (portalinfo[5] >= 1000)
				a.innerHTML += " (" +portalinfo[5] / 1000 + "k)";
			else
				a.innerHTML += " (" +portalinfo[5]+ ")";
		}
				
		var checkimg = document.createElement('img');
		checkimg.id = "portalcheckbox_" +i;
		checkimg.className = 'checkbox_off';
		checkimg.align = 'right';
		checkimg.alt = 'Show Portal';
		checkimg.src = 'http://images.rocards.de/blank.gif';
		
		var aimg = document.createElement('a');
		aimg.appendChild(checkimg);
				
		aimg.href = 'javascript:checkbox(document.getElementById("portalcheckbox_' +i+ '"), "checkbox_on", "checkbox_off"); astarond.showPortal(' +astarond.mapID+ ', ' +portalinfo[0]+ ', ' +i+ ');';
		
		var span = document.createElement('span');
		span.appendChild(aimg);
				
		div.appendChild(a);
		div.appendChild(span);
				
		mapinfoArea.appendChild(div);
		
		i++;
	}

	var mapinfoArea = astarond.registers[1][1];
	mapinfoArea.innerHTML = "";
	
	ret = retinfo[1].split("?");
	
	i = 0;
	for (var p in ret)
	{
		var npcinfo = ret[p].split('&');
		
		if(npcinfo[1] == undefined)
			continue;
			
		var div = document.createElement('div');
		div.className = "routelink";
				
		var a = document.createElement('a');
		a.id = "npc_" +i;
		a.href = 'javascript:astarond.showNPC(' +npcinfo[0]+ ');';
		
		if (npcinfo[1].length > 15)
			npcinfo[1] = npcinfo[1].substr(0, 15) + "...";
		a.innerHTML = "&nbsp;" +npcinfo[1];		
		
		div.appendChild(a);
		mapinfoArea.appendChild(div);
		
		i++;
	}
	
	astarond.registers[0][0] = astarond.mapID;
	astarond.registers[1][0] = astarond.mapID;
	astarond.redrawRegisters();
		
	astarond.applyHooks('onMapLoad');
}

astarond.addAreaMap = function(c_x, c_y, targetMapID, areaID, areaDesc)
{
	var area = document.createElement('area');
	area.shape = 'circle';
	
	var coords = coordsToPixel(c_x, c_y, this.width, this.height);
	area.coords = coords[0]+ "," +coords[1]+ ",10";
	area.href = 'javascript:astarond.openMap(' +targetMapID+ ')';
	area.alt = areaDesc +mapinfo[targetMapID][0];
	area.title = areaDesc +mapinfo[targetMapID][0];
	area.id = areaID;
	area.style.cursor = 'crosshair';
	
	var areamap = document.getElementById('astarond_areamap');
	areamap.appendChild(area);
}

astarond.setLoadingState = function(state)
{
	if (state)
	{
		addMark(this.mapImage.parentNode, loading_image);
		Worldmap.showElement('loading-overlay');
		this.loading = true;
	}
	else
	{
		Worldmap.hideElement('loading-overlay');
		this.loading = false;
	}
}

// NPC Handling =========================
astarond.showNPC = function(npcID)
{
	clearMarks(this.registers[1][2]);
	var newNode = this.mapImage.cloneNode(false);
	
	var found = false;
	for (var i in this.registers[1][3])
	{
		if (this.registers[1][3][i] == npcID)
		{
			this.registers[1][3].splice(i, 1);
			found = true;
		}
	}
	
	if (!found)
		this.registers[1][3].push(npcID);

	if (this.registers[1][3].length == 0)
		return;
		
	newNode.src = "scripts/RCDraw/RCDrawRequest.php?mode=npc&npc[]=" +this.registers[1][3].join("&npc[]=");
	
	addMark(this.mapImage.parentNode, newNode, this.registers[1][2]);	
}

astarond.showPortal = function(fromMap, toMap, checkboxIndex)
{
	clearMarks(this.registers[0][2]);
	var newNode = this.mapImage.cloneNode(false);
	
	var cBox = document.getElementById("portalcheckbox_" +checkboxIndex);
	
	this.registers[0][1].innerHTML = astarond.mapinfoArea.innerHTML;
	
	if (cBox == null || cBox.className == 'checkbox_on')
	{
		this.registers[0][3].push(toMap);
	}
	else
	{
		for (var i in this.registers[0][3])
		{
			if (this.registers[0][3][i] == toMap)
			{
				this.registers[0][3].splice(i, 1);
				break;
			}
		}
	}
		
	if (this.registers[0][3].length == 0)
		return;
		
	newNode.src = "scripts/RCDraw/RCDrawRequest.php?mode=portal&map=" +fromMap+ "&destmap[]=" +this.registers[0][3].join("&destmap[]=");
	addMark(this.mapImage.parentNode, newNode, this.registers[0][2]);	
}


// NPC

// MODES =========================
astarond.modeChange = function(modeID)
{
	this.mode = parseInt(modeID);
	
	if (this.mode == 2)
	{
		return;
	}
	else if (this.mode == 0)
	{
		document.getElementById('mode_dest').className = 'mode_inactive';
		document.getElementById('mode_start').className = 'mode_active';
	}
	else if (this.mode == 1)
	{
		document.getElementById('mode_start').className = 'mode_inactive';
		document.getElementById('mode_dest').className = 'mode_active';
	}	
}

// MODES =========================

astarond.openMap = function(mapID)
{
	this.opening = true;
	
	if (this.loading)
		Worldmap.hideElement('loading-overlay');
		
	if (this.exclude[mapID] != null)
		return;
		
	Worldmap.hideElement('routeMapSelect');
	Worldmap.hideElement('markMapSelect');
	Worldmap.hideElement('markMonsterSelect');
		
	mapname = mapinfo[mapID][0];
	this.mapID = mapID;
	
	this.width = mapinfo[mapID][2];
	this.height = mapinfo[mapID][3];	
	
	this.processMapImages(mapID);
	
	this.changeMap(mapname);
	opendiv('worldmap_overlay');	

	x_getMapInfoById(mapID, this.receiveMapInfo);

	if (mapID != 332)
		document.getElementById("mapinfo_label").innerHTML = "&nbsp;" +mapinfo[mapID][0];
	else
		document.getElementById("mapinfo_label").innerHTML = "&nbsp;raaa_temple";
	
	clearMarks(this.registers[0][2]);
	clearMarks(this.registers[1][2]);
	this.registers[0][3] = new Array();
	this.registers[1][3] = new Array();
	
	
	if (this.mode == 2)
	{
		return;
	}
	else if (this.mode == 0)
	{
		this.modeChange(0);
	}
	else if (this.mode == 1)
	{
		this.modeChange(1);
	}			
	
	setTimeout("astarond.doneOpening()", 10);
}

astarond.doneOpening = function()
{
	this.opening = false;
}

astarond.closeMap = function()
{
	if (this.loading)
		Worldmap.showElement('loading-overlay');
		
	closediv('worldmap_overlay');
	
	Worldmap.showElement('routeMapSelect');
	Worldmap.showElement('markMapSelect');
	Worldmap.showElement('markMonsterSelect');
}

astarond.processMapImages = function(mapID)
{
	clearMarks(this.mapImages);	
	if (this.mapdata[mapID] == undefined)
	{
		this.mapdata[mapID] = new Array();
		this.mapImage.src = 'http://images.rocards.de/blank.gif';
	}
	else if (this.mapdata[mapID] != undefined)
	{	
		for (i in this.mapdata[mapID])
		{
			var newNode = this.mapImage.cloneNode(false);
			newNode.src = this.tempimagefolder +"/"+ this.mapdata[mapID][i];
			
			addMark(this.mapImage.parentNode, newNode, this.mapImages);
		}
	}	
}

astarond.changeMap = function(mapname)
{
	this.mapname = mapname;
	this.backgroundImage.src = 'http://images.rocards.de/maps/' +mapname+ (mapname == 'tha_scene01' ? '.png' : '.gif');
	//this.walkareaImage.src = 'images/gatmaps/' +mapname+ '.png';	
}

astarond.mapClicked = function(test)
{
	if (astarond.opening)
		return;
		
	if (navigator.appName.indexOf("Explorer") != -1)
	{
		var coords = pixelToCoords(window.event.x, window.event.y, this.width, this.height);
		this.setMapCoords(coords[0], coords[1]);
	}
	else
	{
		setTimeout("processMapClick();", 1);
	}
}

astarond.mapClickedData = function(x, y)
{
	var coords = pixelToCoords(x, y, this.width, this.height);
	this.setMapCoords(coords[0], coords[1]);
}

astarond.setMapCoords = function(x, y)
{	
	if (x < 0 || y < 0 || x > this.width || y > this.height)
		return;
			
	var new_mode;
	
	if (this.mode == 2)
	{
		// no idea
		return;
	}
	else if (this.mode == 0)
	{
		// src map handling
		clearMarks(this.flags);
		markMap(this.mapID, mark_start, this.flags);
		new_mode = 1;
		document.getElementsByName('s_x')[0].value = x;
		document.getElementsByName('s_y')[0].value = y;
		document.getElementsByName('s_map')[0].value = this.mapname;
		document.getElementsByName('s_map_id')[0].value = this.mapID;
	}
	else if (this.mode == 1)
	{
		// dest map handling
		markMap(this.mapID, mark_dest, this.flags);
		new_mode = 0;
		document.getElementsByName('d_x')[0].value = x;
		document.getElementsByName('d_y')[0].value = y;
		document.getElementsByName('d_map')[0].value = this.mapname;
		document.getElementsByName('d_map_id')[0].value = this.mapID;
		astarond.submitSearch();
	}
	else
	{
		return;
	}
	
	this.modeChange(new_mode);
}

// Hilfsfunktionen

processMapClick = function()
{	
	var loc = location.toString().split("?");
	loc = loc[loc.length - 1];
	
	if (loc == null)
	{
		alert(window.event);
		return;
	}
	
	loc = loc.split(",");

	if (loc.length < 2)
	{
		alert("no data");
	}
	
	astarond.mapClickedData(loc[0], loc[1]);
}

function opendiv(div)
{
	document.getElementById(div).style.display = 'block';
}

function closediv(div)
{
	document.getElementById(div).style.display = 'none';
}

function pixelToCoords(x, y, width, height)
{
	maxwh = Math.max(width, height);

	x = Math.floor(((x * maxwh / 256) + width - maxwh) / 2);
	y = Math.floor(height - ((y * maxwh / 256) + height - maxwh) / 2);

	return new Array(x, y);
}

function coordsToPixel(x, y, width, height)
{
	maxwh = Math.max(width, height);
	
	x = Math.floor(((2 * x - width + maxwh) * 256) / maxwh);
	y = Math.floor(((2 * y - height - maxwh) * 256) / -maxwh);
	
	return new Array(x, y);
}