// Jumpplanner supporting JavaScript
// Copyright 2007 - 2008, Elissen - elissen@eve-icsc.com

var waypoints = new Array();
var waypointsID = new Array();
var starting = "";
var startingID = 0;
var calibration = 0;
var fuel = 0;
var freighter = 0;
var ship = "Revelation";
var stations = "all";
var maxdist = 5;

var mapZoom = 1.0;
var mapHorizontal = 0;
var mapVertical = 0;

var maxwaypoints = 10;
var waypointcount = 0;
var highsec = false;
var wp0allowhighsec = false;

var highsecShips = new Array("Panther", "Redeemer", "Sin", "Widow", "Anshar", "Ark", "Nomad", "Rhea");


function shipTypeSelected() {
	ship = document.jumpplanner.ship.options[document.jumpplanner.ship.selectedIndex].value;
	highsec = highsecShips.indexOf(ship) > -1;
}

function showAdditionalEdit() {
	if (waypointcount >= maxwaypoints)
		return alert(maxwaypoints + " waypoints is the max");
	var element = document.getElementById("waypointsID");
	var br = document.createElement('br');

	// sigh, IE does not properly propragate names though the system so
	// if you do it the right way, document.getElementsByName will not find it.
	if (navigator.userAgent.indexOf('MSIE') > 1) {
		var ip = document.createElement('<input type="text" name="waypoints' + waypointcount + '" size="50" />');
	} else {
		var ip = document.createElement('input');
		ip.setAttribute('name', 'waypoints' + waypointcount);
		ip.setAttribute('size', 50);
	}
	element.parentNode.insertBefore(br, element);
	element.parentNode.insertBefore(ip, element);
	MakeAutocompleteSystem("waypoints" + waypointcount);
	waypointcount++;
}

function showAddWaypoint(loc, id) {
	var txt = document.createTextNode('Add waypoint:');
	var form = document.createElement('form');
	form.setAttribute('action', 'javascript:void(0);');
	
	// sigh, IE does not properly propragate names though the system so
	// if you do it the right way, document.getElementsByName will not find
	// it.
	if (navigator.userAgent.indexOf('MSIE') > 1) {
		var ip = document.createElement('<input type="text" name="waypoints' + id + '" size="50" />');
	} else {
		var ip = document.createElement('input');
		ip.setAttribute('type', 'text');
		ip.setAttribute('name', 'waypoints' + id);
		ip.setAttribute('size', 50);
	}
	form.appendChild(ip);

	var btn = document.createElement('input');
	btn.setAttribute('type', 'button');
	btn.setAttribute('value', 'add');
	btn.onclick = function() {
		addWaypoint(id, ip.value);
		window.location.href = buildURL();
	}
	form.appendChild(btn);

	var br = document.createElement('br');
	
	form.onsubmit = function() {
		addWaypoint(id, ip.value);
		window.location.href = buildURL();
	}
	
	var d = document.getElementById(loc);
	d.appendChild(txt);
	d.appendChild(form);
	d.appendChild(br);

	MakeAutocompleteSystem('waypoints' + id);
	ip.focus();
}

function hideSpan(name) {
	document.getElementById(name).style.display = 'none';
}

function buildURL() {
	var url = "/jumptools/jumpplanner.php?jdc=" + calibration + "&jfc=" + fuel +
		"&jf=" + freighter + "&fromsystem=" + starting + "&ship=" + ship + 
		"&stations=" + stations;
	for (i = 0; i < waypoints.length; i++)
		url += "&waypoints" + i + "=" + waypoints[i];
	return url;
}

function updateMap() {
	var url = "/jumptools/jumpplannermap.php?md=" + maxdist + "&amp;from=" +
		startingID + "&amp;stations=" + stations + "&amp;zoom=" + mapZoom + "&amp;horizontal=" + mapHorizontal +
		"&amp;vertical=" + mapVertical;
	for (i = 0; i < waypointsID.length; i++)
		url += "&amp;waypoints%5B%5D=" + waypointsID[i];
	document.getElementById("mapdiv").innerHTML = '<img src="' + url + '" alt="map" />';
	return false;
}

function mapZoomIn() {
	mapZoom = mapZoom / 1.5;
	updateMap();
}

function mapZoomOut() {
	mapZoom = mapZoom * 1.5;
	updateMap();
}

function mapRight() {
	mapHorizontal = mapHorizontal + 1;
	updateMap();
}

function mapLeft() {
	mapHorizontal = mapHorizontal - 1;
	updateMap();
}

function mapUp() {
	mapVertical = mapVertical - 1;
	updateMap();
}

function mapDown() {
	mapVertical = mapVertical + 1;
	updateMap();
}

function removeWaypoint(index) {
	if (waypoints.length < 2) {
		alert("You can not remove your last waypoint");
		return;
	}
	if (index == -1) {
		starting = waypoints[0];
		waypoints.shift();
		window.location.href = buildURL();
		return;
	}
	if (index < 0) {
		alert("index can not be a negative value");
		return;
	}
	if (index > waypoints.length - 1) {
		alert ("Index is greater then amount of items in the array");
		return;
	}
	waypoints.splice(index, 1);
	window.location.href = buildURL();
	return;
}

function addWaypoint(index, item) {
	if (index == -1) {
		waypoints.unshift(starting);
		starting = item;
		return;
	}
	if (index < 0) {
		alert("index can not be a negative value");
		return;
	}
	if (index > waypoints.length - 1) {
		alert ("Index is greater then amount of items in the array");
		return;
	}
	waypoints.splice(index, 0, item);
	return;
}

function MakeAutocompleteSystem(name) {
	new CAPXOUS.AutoComplete(name, function() {
		var p = 'false';
		if (highsec) {
			if (this.text.name == 'fromsystem') {
				p = 'true';
			}
			if (wp0allowhighsec == true && this.text.name == "waypoints-1") {
				p = 'true';
			}
		}
		return 'dynamic/system.php?allowHighSec=' + p + '&name=' + this.text.value;
	}, { });
}

function appendBR(el) {
	var b = document.createElement('br');
	el.appendChild(b);
}

function createNamedDiv(name) {
	if (navigator.userAgent.indexOf('MSIE') > 1) {
		return document.createElement('<div name="' + name + '">');
	} else {
		var d = document.createElement('div');
		d.setAttribute('name', name);
		return d;
	}
}

function appendText(el, txt) {
	var t = document.createTextNode(txt);
	el.appendChild(t);
	return t;
}

function removeChildren(el) {
	while (el.childNodes.length > 0)
		el.removeChild(el.firstChild);
}

function addTextCell(row, txt) {
	var cell = document.createElement('td');
	appendText(cell, txt);
	row.appendChild(cell);
	return cell;
}

function addAlternativesHeader(tbl) {
	var row = document.createElement('tr');
	addTextCell(row, '');
	var cell = addTextCell(row, 'Distance');
	cell.style.fontWeight = 'bold';
	cell = addTextCell(row, 'System');
	cell.style.fontWeight = 'bold';
	cell = addTextCell(row, 'Region');
	cell.style.fontWeight = 'bold';
	cell = addTextCell(row, 'Security status');
	cell.style.fontWeight = 'bold';
	cell = addTextCell(row, 'Has station');
	cell.style.fontWeight = 'bold';
	cell = addTextCell(row, 'Sovereignty');
	cell.style.fontWeight = 'bold';
	tbl.appendChild(row);
}

function addAlternativeRow(xmlnode, row) {
	// extra jump?
	if (xmlnode.getAttribute('inrange') == 0) {
		var cell = document.createElement('td');
		var img = document.createElement('img');
		img.src = 'images/exclmark.jpg';
		img.title = "Warning: selecting this system will add extra jumps to your route";
		cell.appendChild(img);
		row.appendChild(cell);
	} else {
		addTextCell(row, '');
	}
	// distance...
	var cell = addTextCell(row, xmlnode.getAttribute('distance') + ' ly');
	// for proper sorting
	cell.setAttribute('sorttable_customkey', xmlnode.getAttribute('distance'));
	var cell = document.createElement('td');
	var lnk = document.createElement('a');
	appendText(lnk, xmlnode.getAttribute('name'));
	cell.appendChild(lnk);
	row.appendChild(cell);
	addTextCell(row, xmlnode.getAttribute('region'));
	addTextCell(row, xmlnode.getAttribute('security'));
	addTextCell(row, xmlnode.getAttribute('stations'));
	addTextCell(row, xmlnode.getAttribute('sov'));
	return lnk;
}

function closeAlternatives(id) {
	var d = document.getElementById('alt' + id);
	removeChildren(d);
	d.parentNode.removeChild(d);
	var d = document.getElementById('after' + id);
	d.style.display = '';
}

function findAlternatives(s1, s2, place, isWaypoint, waypointIndex, currentSystem) {

	if (window.XMLHttpRequest) { // Mozilla, Safari,...
		http_request = new XMLHttpRequest();
		if (http_request.overrideMimeType) {
			http_request.overrideMimeType('text/xml');
		}
	} else if (window.ActiveXObject) { // IE
		try {
			http_request = new ActiveXObject("Msxml2.XMLHTTP");
		} catch (e) {
			try {
				http_request = new ActiveXObject("Microsoft.XMLHTTP");
			} catch (e) {}
		}
	}
	
	if (!http_request) {
		alert('Sorry, but something ugly happened while making a XMLHttpRequest object');
		return false;
	} else {
		// set a place hold...
		var aft = document.getElementById('after' + place);
		aft.style.display = 'none';
		var d = document.createElement('div');
		d.setAttribute('id', 'alt' + place);
		
		d.style.color = 'yellow';
		d.style.marginLeft = '2em';
		appendBR(d);
		appendText(d, 'Please wait while the alternatives are being loaded...');
		appendBR(d);
		appendBR(d);

		aft.parentNode.insertBefore(d, aft.nextSibling);

		// now fetch the info
		http_request.onreadystatechange = function () {
			if (http_request.readyState == 4) {
				if (http_request.status == 200) {
					var systems = http_request.responseXML.getElementsByTagName('system');
					var d = document.getElementById('alt' + place);
					var tbl1 = document.createElement('table');
					var tbl = document.createElement('TBODY');
					tbl1.appendChild(tbl);
					addAlternativesHeader(tbl);
					// clone provided by prototype
					var savewaypoints = waypoints.clone();
					if (!isWaypoint)
						waypoints.splice(waypointIndex, 0, 'x');
					for (var i = 0; i < systems.length; i++) {
						if (systems[i].getAttribute('id') != currentSystem) {
							var row = document.createElement('tr');
							var lnk = addAlternativeRow(systems[i], row);
							waypoints[waypointIndex] = systems[i].getAttribute('name');
							lnk.href = buildURL();
							tbl.appendChild(row);
						}
					}
					waypoints = savewaypoints;
					removeChildren(d);
					d.style.color = 'white';
					tbl.style.fontSize = 'small';
					appendBR(d);
					var img = document.createElement('img');
					img.src = '/jumptools/dynamic/alternatives.php?mode=map&s1=' + s1 + '&s2=' + s2 +
						'&maxdist=' + maxdist + '&stations=' + stations;
					img.alt = 'Alternatives';
					img.height = 415;
					img.width = 400;
					d.appendChild(img);
					d.appendChild(tbl1);
					sorttable.makeSortable(tbl1);
					appendBR(d);
					var lnk = document.createElement('a');
					lnk.href = '#';
					lnk.onclick = function() {
						closeAlternatives(place);
						return false;
					}
					var img = document.createElement('img');
					img.src = '/images/v2/button-close.jpg';
					img.title = 'Cancel';
					lnk.appendChild(img);
					d.appendChild(lnk);
					appendBR(d);
					appendBR(d);
					appendText(d, "");
				} else {
					var d = document.getElementById('alt' + place);
					removeChildren(d);
					appendBR(d);
					appendText(d, 'Error fetching alternatives');
					appendBR(d);
					appendBR(d);
				}
			}
		}
		http_request.open("GET", '/jumptools/dynamic/alternatives.php?s1=' + s1 + '&s2=' + s2 +
			'&maxdist=' + maxdist + '&stations=' + stations, true);
		http_request.send("");
	}

}
