//author: Krzysztof Kołakowski
//version: 1.0.1
//* fixed checking url for gpx file from xml answer
//* changed displaying map for mode "route" 

var MyMap;
var Dir = "/libs/map";
var mapList ;
var mapDiv;
var mapX=0;
var mapY=0;
var listX = 0;
var listY = 0;
var bgImageLink = "";
var styleLink = "http://"+window.location.hostname+Dir+'/style.css';
var host = "http://"+window.location.hostname;
var defaultLocation = new GLatLng(53.742696,20.511213); // olsztyn :)
var DisplayWaypoints = 1; //displaying waypoints from gpx file
var ImageList = Array();

function LoadGPXFileIntoGoogleMap(map, filename, colour, dispWaypoints ) {
	// Remove any existing overlays from the map.
	map.clearOverlays();

	var request = GXmlHttp.create();
	var xmlobject;

	request.open("GET", host+"/"+filename, true);
	request.onreadystatechange = function() {
		if (request.readyState == 4) {
			if(request.status == 200)
			{
				//alert(request.responseText);
      				//dump(request.responseText);
				if(!request.overrideMimeType)
				{// changing the txt format of response to xml object
					xmlobject=new ActiveXObject("Microsoft.XMLDOM");
					xmlobject.async="false";
					xmlobject.loadXML(request.responseText); 
				}
				else
					xmlobject = request.responseXML;
     				parser = new GPXParser(xmlobject, map);
				parser.SetTrackColour(colour); // Set the track line colour
				parser.SetTrackWidth(5); // Set the track line width
				parser.SetMinTrackPointDelta(0.001); // Set the minimum distance
				// between track points
				parser.CenterAndZoom(xmlobject, G_PHYSICAL_MAP); // Center and Zoom the map over all the points.
				parser.AddTrackpointsToMap(); // Add the trackpoints

				if(dispWaypoints == 1) // display Waypoints?
					parser.AddWaypointsToMap(); // Add the waypoints		
			}
			else
      				alert("Błąd podczas ładowania pliku GPX");
		}
	};
	if(request.overrideMimeType)
		request.overrideMimeType('text/xml');
	request.send(null);
}
 
function map_start(ID) {
	var url;
	var xmlobject;
	MyMap = new GMap2(mapDiv,{ size: new GSize(mapX,mapY) });
	MyMap.removeMapType(G_HYBRID_MAP);
	MyMap.removeMapType(G_SATELLITE_MAP);
	MyMap.addMapType(G_PHYSICAL_MAP);
	MyMap.addControl(new ImageButtonMapControl());
	MyMap.addControl(new ImageButtonZoomControl());
	var Request = GXmlHttp.create();
	var route;
	mapDiv.style.display="none";
	Request.onreadystatechange = function() {
		if (Request.readyState == 4) {
			//url = Request.responseText;
			xmlobject = Request.responseXML;
					
			//alert(url);
			if (!xmlobject)
			{
				//alert("NIe ma pliku gpx");
				MyMap.setCenter(defaultLocation,7,G_PHYSICAL_MAP);
				return;
			}
			route = xmlobject.getElementsByTagName("route");
			url = route[0].getAttribute('GpsFilePath');
			if (url == "")
				return;
			mapDiv.style.display="block";
			DisplayWaypoints =  route[0].getAttribute('waypoint_display'); //displaying waypoints from gpx file
			var colour = route[0].getAttribute("route_color"); // colour of route on map
			LoadGPXFileIntoGoogleMap(MyMap, url, colour, DisplayWaypoints);
		}
	}
	Request.open("GET", host+Dir+"/map_feed.php?id="+ ID +"&action=gpx", true);
	Request.send(null);
}

function map_list(type, district, recom)
{	
	var xmlobject;
	var Request = GXmlHttp.create();
	
	Request.onreadystatechange = function() {
		if (Request.readyState == 4) {
			xmlobject = Request.responseXML;
			
			if (!xmlobject)
			{
				mapDiv.style.display="none";
//				alert("Pusty plik xml.");
				return;
			}
			//alert(xmlobject);
			var routesTable = xmlobject.getElementsByTagName('route');

			var table = document.createElement("table");
			var tbody = document.createElement("tbody");
			var tr = document.createElement("tr");
			var td = document.createElement("td");
			var trt, tdt;
			mapList.appendChild(table);
			table.appendChild(tbody);
			var i;
			if(routesTable.length> 0)// if routeTable is not empty start the map
			{
				MyMap = new GMap2(mapDiv,{ size: new GSize(mapX,mapY) });
				MyMap.removeMapType(G_HYBRID_MAP);
				MyMap.removeMapType(G_SATELLITE_MAP);
				MyMap.addMapType(G_PHYSICAL_MAP);
				MyMap.addControl(new ImageButtonZoomControl());
				MyMap.addControl(new ImageButtonMapControl());
				MyMap.setCenter(defaultLocation,7,G_PHYSICAL_MAP);
				mapList.style.display = "block";
			}
			else return ;
			for(i=0 ; i<routesTable.length ; i++)
			{
				var id = routesTable[i].getAttribute('route_id');
				var route_name = routesTable[i].getAttribute('route_name');
				if(route_name != "")
				{
					tbody.appendChild(trt = tr.cloneNode(false));
					trt.appendChild(tdt = td.cloneNode(false));
					tdt.innerHTML = "»";
					trt.appendChild(tdt = td.cloneNode(false));
					tdt.innerHTML = "<a class='trclink' href='javascript:void(0);' onclick='map_start("+id+",null)'>"+ route_name+"</a>";
				}
			}
		}
	}
	if(type != "")
		Request.open("GET", host+Dir+"/map_feed.php?route_type="+ type +"&action=routes", true);
	else if(district != "")
		Request.open("GET", host+Dir+"/map_feed.php?d="+ district +"&action=routes", true);
	else if(recom == "1")
		Request.open("GET", host+Dir+"/map_feed.php?recomended=1&action=routes", true);
	else 
		return;
	Request.send(null);
}

function SetStyleSheet(link)
{
	if(document.createStyleSheet) 
		document.createStyleSheet(link);
	else
	{
		var styles = "@import url('"+link+"');";
		var newSS=document.createElement('link');
		newSS.rel='stylesheet';
		newSS.href='data:text/css,'+escape(styles);
		document.getElementsByTagName("head")[0].appendChild(newSS);
	}
}

function load()
{
	mapDiv = document.getElementById("map");
	if(!mapDiv) return;
	SetStyleSheet(styleLink);
	if(mod == "route")
	{
		mapX = 540;
		mapY = 300;
		mapDiv.style.display = "none";
		map_start(id);
	}
	else if(mod == "routes")
	{
		mapX = 450;
		mapY = 300;
		listX = 200;
		listY = 300;
		mapList = document.getElementById('map_list');
		mapList.style.fontSize = "8pt";
		mapList.style.overflow = "auto";//overflow: auto;
		mapList.style.height  = listY;
		mapList.style.width  = listX;
		mapList.style.display = "none";
		map_list(route_type, dist_id, recomended);
	}
}

function ImageButtonZoomControl(){}

ImageButtonZoomControl.prototype = new GControl();
ImageButtonZoomControl.prototype.initialize = function(map)
{
	var container = document.createElement('div');
	var ZoomInDiv = document.createElement('div');
	this.SetButtonStyle_(ZoomInDiv);
	container.appendChild(ZoomInDiv);
	var img = document.createElement("img");
	loadImage("plus");
	img.src = ImagePath+"plus.png";
	img.alt = "Powiększ";
	ZoomInDiv.appendChild(img);
	GEvent.addDomListener(ZoomInDiv, "mousedown", function() {this.getElementsByTagName('img')[0].src =ImagePath+"plus_pressed.png"; });
	GEvent.addDomListener(ZoomInDiv, "mouseup", function() {this.getElementsByTagName('img')[0].src =ImagePath+"plus.png"; });
	GEvent.addDomListener(ZoomInDiv, "click", function() {map.zoomIn(); });
	var ZoomOutDiv = document.createElement("div");
  	this.SetButtonStyle_(ZoomOutDiv);
  	container.appendChild(ZoomOutDiv);
	img = document.createElement("img");
	loadImage("minus");
	img.src = ImagePath+"minus.png";
	img.alt = "Pomniejsz";
  	ZoomOutDiv.appendChild(img);
	GEvent.addDomListener(ZoomOutDiv, "mousedown", function() {this.getElementsByTagName('img')[0].src =ImagePath+"minus_pressed.png"; });
	GEvent.addDomListener(ZoomOutDiv, "mouseup", function() {this.getElementsByTagName('img')[0].src =ImagePath+"minus.png"; });
  	GEvent.addDomListener(ZoomOutDiv, "click", function() { map.zoomOut(); });
	map.getContainer().appendChild(container);
	return container;
}

ImageButtonZoomControl.prototype.SetButtonStyle_ = function(button) {
  button.style.cursor = "pointer";
}

ImageButtonZoomControl.prototype.getDefaultPosition = function() {
  return new GControlPosition(G_ANCHOR_TOP_LEFT, new GSize(10, 10));
}

function ImageButtonMapControl(){}

ImageButtonMapControl.prototype = new GControl();
ImageButtonMapControl.prototype.initialize = function(map)
{
	var container = document.createElement('div');
	var table = document.createElement('table');
	var tbody = document.createElement('tbody');
	table.appendChild(tbody);
	var tr = document.createElement('tr');
	tbody.appendChild(tr);
	var td = document.createElement('td');
	tr.appendChild(td);
	container.appendChild(table);
	var MapDiv = document.createElement('div');
	this.SetButtonStyle_(MapDiv);
	td.appendChild(MapDiv);
	var img = document.createElement("img");
	loadImage("mapa");
	img.src = ImagePath+"mapa.png";
	img.alt = "Mapa";
	MapDiv.appendChild(img);
	GEvent.addDomListener(MapDiv, "mousedown", function() {this.getElementsByTagName('img')[0].src =ImagePath+"mapa_pressed.png"; });
	GEvent.addDomListener(MapDiv, "mouseup", function() {this.getElementsByTagName('img')[0].src =ImagePath+"mapa.png"; });
	GEvent.addDomListener(MapDiv, "click", function() {map.setMapType(G_NORMAL_MAP);});
	var TerainDiv = document.createElement("div");
  	this.SetButtonStyle_(TerainDiv);
	td = document.createElement('td');
	tr.appendChild(td);
  	td.appendChild(TerainDiv);
	img = document.createElement("img");
	loadImage("Teren");
	img.src = ImagePath+"teren.png";
	img.alt = "Teren";
  	TerainDiv.appendChild(img);
	GEvent.addDomListener(TerainDiv, "mousedown", function() {this.getElementsByTagName('img')[0].src =ImagePath+"teren_pressed.png"; });
	GEvent.addDomListener(TerainDiv, "mouseup", function() {this.getElementsByTagName('img')[0].src =ImagePath+"teren.png"; });
  	GEvent.addDomListener(TerainDiv, "click", function() { map.setMapType(G_PHYSICAL_MAP); });
	map.getContainer().appendChild(container);
	return container;
}

ImageButtonMapControl.prototype.SetButtonStyle_ = function(button) {
  button.style.cursor = "pointer";
}

ImageButtonMapControl.prototype.getDefaultPosition = function() {
  return new GControlPosition(G_ANCHOR_TOP_RIGHT, new GSize(7, 7));
}

function loadImage(iname)
{
	var i = ImageList.length;
	ImageList[i] = (new Image()).src = ImagePath+iname +".png";	
	ImageList[i+1] = (new Image()).src = ImagePath+iname+"_pressed.png";
}

if (window.addEventListener){
	window.addEventListener("load", load, false);
	window.addEventListener("unload", GUnload, false);
}
else if (window.attachEvent){
	window.attachEvent("onload", load);
	window.attachEvent("onunload", GUnload);
}
else{
	window["onload"] =  load;
	window["onunload"] = GUnload;
}

