var tooltip    = document.createElement("div");
var maintitle  = "sFOCUS Swiss Cricket Grounds";
var legends    = [];
var locations  = [];
var iGMarkers  = [];
var notes      = [];
var directions = [];
var lines      = [];
var gerror     = 0;
var xmlDoc;
var map;
var gDir;

function setupMaps()
{
  setLayout();
  getFile();
}

function getFile()
{
  if (GBrowserIsCompatible()) 
  {
    var request = GXmlHttp.create();
    request.open("GET", "scripts/sf_map_data.xml", true);
    request.onreadystatechange = function()
	  {
      if (request.readyState == 4) 
		  {
			  xmlDoc = GXml.parse(request.responseText); 
				
				
				initMap();   
		  }		
	  }
		request.send(null);
	}  
}

function initMap()
{
  var center = getCenter();
	map = new GMap2(document.getElementById("map"));
	map.setCenter(center, 7);
	map.disableDragging();
	createMarkerArray();
	for(var i=0;i<iGMarkers.length;i++)
	{
	  map.addOverlay(iGMarkers[i].m);
	}
	document.getElementById("map").appendChild(tooltip);
  hideTooltip();
	document.getElementById("nav").innerHTML = createLegendHTML();
	document.title = maintitle;
	lines = xmlDoc.documentElement.getElementsByTagName("line");
		document.getElementById("overview").innerHTML="";
}

function loadMap(indexno) 
{
	
	loliteLink('a','legend',indexno);
	var iGM = createMarker(indexno,locations[indexno],0);
	iGM.dir    = createDirections(indexno,locations[indexno]);
	map = new GMap2(document.getElementById("map"));
	map.setCenter(new GLatLng(iGM.lat,iGM.lng),15);
	
	map.addControl(new GLargeMapControl());
	map.addControl(new GMapTypeControl());
 
	map.hideControls();
  GEvent.addListener(map, "mouseover", function(){map.showControls();});
  GEvent.addListener(map, "mouseout", function(){map.hideControls();});
	document.title = maintitle + "; "+legends[indexno];
	
	
	
	var infoContent = createInfo(iGM)+iGM.dir;
	map.addOverlay(iGM.m);
	iGM.m.openInfoWindowTabsHtml([new GInfoWindowTab("info",infoContent),new GInfoWindowTab("transport",iGM.note)]);
	document.getElementById("overview").innerHTML='<a href="javascript:onclick=initMap()">Return to Overview Map</a>';
}

function getCenter()
{
   var temp   = [];
   temp       = xmlDoc.documentElement.getElementsByTagName("centre");
	 var lat    = parseFloat(temp[0].getAttribute("lat"));
 	 var lon    = parseFloat(temp[0].getAttribute("lon"));
	 var center = new GLatLng(lat,lon);
	 return center;
}

function createMarkerArray()
{
  var temp;
	
	legendHTML="";
	locations = xmlDoc.documentElement.getElementsByTagName("location");
  for(var i=0;i<locations.length;i++)
	{
	  iGMarkers[i] = createMarker(i,locations[i],1);
		iGMarkers[i].m.tooltip = createLegend(i,locations[i]);
	}
}

function createLegend(indexno,location)
{
  var legend;
	var rvalue;
	
  if(location.getAttribute("ground") != "")
	  legend= location.getAttribute("city") + ", " + location.getAttribute("ground");
  else
	  legend = location.getAttribute("city");
	legends[indexno] = legend;
	rvalue = '<div class="tooltip">'+legend+'</div>';
	return rvalue;
}

function createLegendHTML()
{
  var legendHTML = "";
	for(var i=0;i<legends.length;i++)
	{
    legendHTML  += '<a class= "legend" href="javascript:onclick = loadMap('+i+')" onmouseover="showtip('+i+')" onmouseout="hidetip()">' +legends[i]+ '</a><br>';
	}
	return legendHTML;
}

function createMarker(indexno,location,nIcon)
{
  var legend;
  var mIcon  = createIcon(nIcon);
	var iGM    = new iGMarker(indexno);
	var lat    = parseFloat(location.getAttribute("lat"));
	var lon    = parseFloat(location.getAttribute("lon"));
	var note   = location.getAttribute("notes");
  iGM.m      = new GMarker(new GLatLng(lat,lon), {icon:mIcon});
	iGM.note   = createTransport(location);
	iGM.lat = lat;
	iGM.lng = lon;
	GEvent.addListener(iGM.m, "click", function() {
    loadMap(iGM.indexno);});		
	GEvent.addListener(iGM.m,"mouseover", function() {
		hiliteLink('a','legend',iGM.indexno);});       
  GEvent.addListener(iGM.m,"mouseout", function() {
		loliteLink('a','legend',iGM.indexno);});
	return iGM;
}

function hiliteLink(tagname,classname,indexno)
{
  var elem = getElementByClassName(tagname,classname,indexno);
	elem.style.color = '#ff0000';
	elem.style.fontSize = '9pt';
	elem.style.textDecoration = 'none';
}

function loliteLink(tagname,classname,indexno)
{
  var elem = getElementByClassName(tagname,classname,indexno);
	elem.style.color = '#c68c06';
	elem.style.fontSize = '8pt';
	elem.style.textDecoration = 'underline';
}

function showTooltip(m)
{
  tooltip.innerHTML = m.tooltip;
	var point=map.getCurrentMapType().getProjection().fromLatLngToPixel(map.getBounds().getSouthWest(),map.getZoom());
	var offset=map.getCurrentMapType().getProjection().fromLatLngToPixel(m.getPoint(),map.getZoom());
	var anchor=m.getIcon().iconAnchor;
	var width=m.getIcon().iconSize.width;
	var pos = new GControlPosition(G_ANCHOR_BOTTOM_LEFT, new GSize(offset.x - point.x - anchor.x + width,- offset.y + point.y +anchor.y)); 
	pos.apply(tooltip);
	tooltip.style.visibility="visible";
}

function hideTooltip()
{
  tooltip.style.visibility="hidden";
}

function showtip(indexno)
{
  var temp = iGMarkers[indexno];
  showTooltip(temp.m);
}

function hidetip() 
{
	tooltip.style.visibility="hidden";
}

function createIcon(nIcon)
{
  var mIcon = new GIcon();

  switch(nIcon)
	{
	  case 0:
		  mIcon.image = "images/stump1.png";
		  mIcon.iconSize = new GSize(30,47);
	    mIcon.iconAnchor = new GPoint(15,47);
		  mIcon.infoWindowAnchor = new GPoint(15,1);
		break;
	  case 1:
		  mIcon.image = "images/stump2.png";
		  mIcon.iconSize = new GSize(16,27);
	    mIcon.iconAnchor = new GPoint(8,27);
		  mIcon.infoWindowAnchor = new GPoint(8,1);
		break;
		default:
		break;
  }	
	return mIcon;
}

function createDirections(indexno,location)
{
  var directions;
	var label  = location.getAttribute("ground");
	var lat    = parseFloat(location.getAttribute("lat"));
	var lon    = parseFloat(location.getAttribute("lon"));
directions = 
	  '<form class="trans" action="javascript:getDirections()">' 
	  +' <b>Directions to here from</b>: <input type="text" SIZE=20 MAXLENGTH=20 name="fromAddr" id="fromAddr" value="" /><br>'
	  +'<INPUT name="ginput" id ="ginput" value="Get Directions" TYPE="SUBMIT">'
	  +'<input type="hidden" id="thisAddr" value="'+label+"@"+ lat+ ',' + lon+'"/></form>';
  return directions;
}

function createTransport(location)
{
  var code = parseFloat(location.getAttribute("code"));
  var transport='<p class="trans">From <b>';
	transport+=location.getAttribute("start");
	transport+='</b> ';
	transport+=createSBB(code);
	transport+='<br>';
	transport+=location.getAttribute("notes");
	transport+='<div id="dist"></div>';
	transport+='</p>';	
	return transport
}

function createSBB(code)
{
  var sbb = '<a class="blue" href="http://fahrplan.sbb.ch/bin/bhftafel.exe/dn?input=';
	sbb     += code;
  sbb     += '&boardType=dep&time=now&selectDate=today&start=yes"  target="_blank">(SBB-CFF-FFS)</a>';
	return sbb;
}

function getDirections() 
{
  gDir=new GDirections(map, document.getElementById("nav"));
	GEvent.addListener(gDir, "error", gdirError);
  var fromAddr = document.getElementById("fromAddr").value;
  var thisAddr = document.getElementById("thisAddr").value;	
  gDir.load("from: "+fromAddr+" to: "+thisAddr);
	
  if(!gerror)
	{
	  
    var inputState = document.getElementById("ginput");
	  if(inputState.value == "Get Directions")
	  {
	    document.getElementById("nav").innerHTML = "";
	    inputState.value = "Clear directions";	
	  }
	  else
	  {
	    gDir.clear();
	    inputState.value = "Get Directions";
		  document.getElementById("nav").innerHTML = createLegendHTML();
			document.getElementById("fromAddr").value = "";
	  }
	}
	else
	{
	  var text = "Error: Check that the coordinates are correct\n[eg. 47.5123N,7.7890E or 47 51.23N, 7 7.789E]\nNote: Some Swiss place names are not recognized";
		alert(text);
		//inputState.value == "Get Directions";
		
	  gerror = 0;
	}
}

function onFoot(lineno)
{
  var pts = [];
 
	var colour = lines[lineno].getAttribute("colour");
  var width  = parseFloat(lines[lineno].getAttribute("width"));
	var points = lines[lineno].getElementsByTagName("point");
  for (var i=0;i<points.length;i++)
	{
    pts[i] = new GLatLng(parseFloat(points[i].getAttribute("lat")),
                         parseFloat(points[i].getAttribute("lng")));
  }
	var line = new GPolyline(pts,colour,width);
	map.addOverlay(line);
	var d = document.getElementById("dist");
	d.innerHTML = "Follow ";
	switch(colour)
	{
	  case "#FF0000":
		  d.innerHTML += '<img src="images/redline.png" height="3" width="20"> (approx.';
		break;
		case "#0054A6":
		  d.innerHTML += '<img src="images/blueline.png" height="3" width="20"> (approx.';
		break;
		case "#006E3A":
		  d.innerHTML += '<img src="images/greenline.png" height="3" width="20"> (approx.';
		break;
	}
	var dist = Math.round(line.getLength());
	d.innerHTML += dist+'m).';

}

function gdirError()
{
	gerror = 1;
}

function createInfo(iGM)
{
  var info;
	
	info = '<p class="smp"><b>'+legends[iGM.indexno]+'</b>: ('+iGM.lat+'N,'+iGM.lng+'E)</p>';
	return info;
}

function mapKey() 
{
  var key ="ABQIAAAAH-UKi_zhkpJuRJZyYTzFNxQl1XGHEElVPhPiU2R4iOqvR1uD4xSkmK7lA5nmVSf9fg7hoz4Bv8oLCQ";
	return key;
}

function iGMarker(i)
{
  var m;
	var lat;
	var lng;
	var note;
	var dir;
	this.indexno = i;
}

function getElementByClassName(tagname,classname,indexno)
{
  var lc = [];
	var j  = 0;
	var d = document.getElementsByTagName(tagname);
  for(var i=0;i<d.length;i++)
	{
	
	  if(d[i].className == classname)
		{
	    lc[j] = d[i];
			j++;
		}
	}
  return lc[indexno];
}

function getElementsByClassName(tagname,classname)
{
  var lc = [];
	var j  = 0;
	var d = document.getElementsByTagName(tagname);
  for(var i=0;i<d.length;i++)
	{
	  if(d[i].className == classname)
		{
	    lc[j] = d[i];
			j++;
		}
	}
  return lc;
}

/**
function dirTo(indexno) 
{
  iGM[i].m.openInfoWindowHtml(iGM[i].dir);
}

function dirFrom(indexno) 
{
  iGM[i].m.openInfoWindowHtml(iGM[i].dir);
}
**/

/** from sf_jscript.js **/

function setLayout()
{
  var text;
 
  text="";
  text+= '<map name="sf_header_Map">';
  text+= '<area shape="rect" alt="" coords="330,203,408,218" href="sf_news.html">';
  text+= '<area shape="rect" alt="" coords="249,203,326,218" href="sf_reports.html">';
  text+= '<area shape="rect" alt="" coords="167,203,245,218" href="sf_maps.html">';
  text+= '<area shape="rect" alt="" coords="86,203,163,218" href="sf_links.html">';
  text+= '<area shape="rect" alt="" coords="4,203,82,218" href="sf_join.html">';
  text+= '<area shape="rect" alt="" coords="310,183,408,198" href="users/Booker/sf_bookings.html">';
  text+= '<area shape="rect" alt="" coords="208,183,306,198" href="sf_services.html">';
  text+= '<area shape="rect" alt="" coords="106,183,204,198" href="sf_contact.html">';
  text+= '<area shape="rect" alt="" coords="4,183,101,199" href="index.html">';
  text+= '</map>';
	document.getElementById('mapvalues').innerHTML = text;
	text= '<img src="images/sf_header.png" width="410" height="221" border="0" alt="" usemap="#sf_header_Map">';
	document.getElementById('header').innerHTML = text;
	text= '<hr width="100%">';
	document.getElementById('topline').innerHTML = text;
	text+='<img src="images/sf_footer.png" width="275" height="17" border="0" alt="">';
	document.getElementById('bottomline').innerHTML = text;
}


