/* JS for GoogleMaps */
// arrays to hold copies of the markers and html used by the side_bar
		// because the function closure trick doesnt work there
		var gmarkers = [];
		var htmls = [];
		var htmls2 = [];
		var h1s = [];
		var h2s = [];
		var i = 0;
		// arrays to hold variants of the info window html with get direction forms open
		var to_htmls = [];
		var from_htmls = [];		
		
function init() {
      if (GBrowserIsCompatible()) {      		
		// create map
        var map = new GMap2(document.getElementById("map_canvas"));
		// set map type
		map.setMapType(G_HYBRID_MAP);
		
		// set initial center: (long,lat),zoom
        map.setCenter(new GLatLng(49.24128903347686,6.9448935985565186), 10);		
				
		// SETUP MAP CONTROLS		
        map.addControl(new GLargeMapControl());
        var mapControl = new GHierarchicalMapTypeControl();        
        // Set up map type menu relationships
        mapControl.clearRelationships();
        mapControl.addRelationship(G_SATELLITE_MAP, G_HYBRID_MAP, "Labels", false);    
        // Add control after you've specified the relationships
		map.addMapType(G_PHYSICAL_MAP);
        map.addControl(mapControl);		

		/*
		// START Click-Event Listener
        GEvent.addListener(map,"click", function(overlay,latlng) {
		   // ignore if we click on the info window
          if (overlay) return;                      
          var tileCoordinate = new GPoint();
          var tilePoint = new GPoint();
          var currentProjection = G_NORMAL_MAP.getProjection();
          tilePoint = currentProjection.fromLatLngToPixel(latlng, map.getZoom());
          tileCoordinate.x = Math.floor(tilePoint.x / 256);
          tileCoordinate.y = Math.floor(tilePoint.y / 256);
          var myHtml = "Latitude: " + latlng.lat() + "<br/>Longitude: " + latlng.lng() + 
            "<br/>The Tile Coordinate is:<br/> x: " + tileCoordinate.x + 
            "<br/> y: " + tileCoordinate.y + "<br/> at zoom level " + map.getZoom();	
          map.openInfoWindow(latlng, myHtml);
        }); 
		// END Click-Event Listener					
	*/
		  
	  
		// Creates a marker whose info window displays the letter corresponding to the given index.
		function createLetterMarker(point, index, info) {
			// Create a lettered icon for this point using our icon class			
			var letter = String.fromCharCode("A".charCodeAt(0) + index);
			var letteredIcon = new GIcon(baseIcon);
			letteredIcon.image = "http://www.google.com/mapfiles/marker" + letter + ".png";
			// Set up our GMarkerOptions object
			markerOptions = { icon:letteredIcon };
			var marker = new GMarker(point, markerOptions);			
			GEvent.addListener(marker, "click", function() {marker.openInfoWindowHtml(info); });		
			return marker;
		}
		
		// Creates a marker whose info window displays the letter corresponding to the given index.
		function createMarker(point, info,html) {			
			var marker = new GMarker(point);
			GEvent.addListener(marker, "click", function() {marker.openInfoWindowHtml(info); });		
			return marker;
		}
		
	// A function to create a tabbed marker and set up the event window
      function createTabbedMarker(point,info1,info2,h1,h2) {
        var marker = new GMarker(point);
        GEvent.addListener(marker, "click", function() {
          marker.openInfoWindowTabsHtml([new GInfoWindowTab(h1,info1), new GInfoWindowTab(h2,info2)]);
        });
        return marker;
      }	  
		
		// A function to create the marker and set up the event window
      function createMarkerWithRoute(point,name,html,html2,h1,h2) {
        var marker = new GMarker(point);

        // The info window version with the "to here" form open
        to_htmls[i] = html + name+"<br>Richtung: <b>Hierher</b> - <a href='#' onclick='fromhere("+i+")'>Von hier</a>" +
           '<br>Start Adresse:<form action="http://maps.google.com/maps" method="get" target="_blank">' +
           '<input type="text" SIZE=40 MAXLENGTH=40 name="saddr" id="saddr" value="" /><br>' +
           '<INPUT value="Route berechnen" TYPE="SUBMIT">' +
           '<input type="hidden" name="daddr" value="' + point.lat() + ',' + point.lng() + 
                  //"(" + name + ")" + 
           '"/>';
        // The info window version with the "to here" form open
        from_htmls[i] = html + name+"<br>Richtung: <a href='#' onclick='tohere("+i+")'>Hierher</a> - <b>Von hier</b>" +
           '<br>Ziel Adresse:<form action="http://maps.google.com/maps" method="get"" target="_blank">' +
           '<input type="text" SIZE=40 MAXLENGTH=40 name="daddr" id="daddr" value="" /><br>' +
           '<INPUT value="Route berechnen" TYPE="SUBMIT">' +
           '<input type="hidden" name="saddr" value="' + point.lat() + ',' + point.lng() +
                 // "(" + name + ")" + 
           '"/>';
        // The inactive version of the direction info
        html = html + name+"<br>Route berechnen: <a href='#' onclick='tohere("+i+")'>Hierher</a> - <a href='#' onclick='fromhere("+i+")'>Von hier</a>";

        //GEvent.addListener(marker, "click", function() { marker.openInfoWindowHtml(html);});
		GEvent.addListener(marker, "click", function() { marker.openInfoWindowTabsHtml([new GInfoWindowTab(h1,html), new GInfoWindowTab(h2,html2)]); });
		
        // save the info we need to use later for the side_bar
        gmarkers[i] = marker;
        htmls[i] = html;
		htmls2[i] = html2;
		h1s[i] = h1;
		h2s[i] = h2;
        // add a line to the side_bar html
        //side_bar_html += '<a href="javascript:myclick(' + i + ')">' + name + '</a><br>';
        i++;
        return marker;
      }	  	 
	  
	  
	    // ==================================================
      // A function to create a tabbed marker and set up the event window
      // This version accepts a variable number of tabs, passed in the arrays htmls[] and labels[]
      function createVariableTabbedMarker(point,htmls,labels) {
        var marker = new GMarker(point);
        GEvent.addListener(marker, "click", function() {
          // adjust the width so that the info window is large enough for this many tabs
          if (htmls.length > 2) {
            htmls[0] = '<div style="width:'+htmls.length*88+'px">' + htmls[0] + '</div>';
          }
          var tabs = [];
          for (var i=0; i<htmls.length; i++) {
            tabs.push(new GInfoWindowTab(labels[i],htmls[i]));
          }
          marker.openInfoWindowTabsHtml(tabs);
        });
        return marker;
      }
      // ==================================================

				
		// Create a base icon for all of our markers that specifies the
		// shadow, icon dimensions, etc.
		var baseIcon = new GIcon(G_DEFAULT_ICON);
		baseIcon.shadow = "http://www.google.com/mapfiles/shadow50.png";
		baseIcon.iconSize = new GSize(20, 34);
		baseIcon.shadowSize = new GSize(37, 34);
		baseIcon.iconAnchor = new GPoint(9, 34);
		baseIcon.infoWindowAnchor = new GPoint(9, 2);			
		
		// Read the data from example.xml
      var request = GXmlHttp.create();
      //request.open("GET", "../../gmLocServlet/locations", true);
      request.open("GET","http://sln-web.sb.dfki.de:8005/gmLocServlet/locations",true);
	  
      request.onreadystatechange = function() {
        if (request.readyState == 4) {
          var xmlDoc = GXml.parse(request.responseText);
          // obtain the array of markers and loop through it
          var markers = xmlDoc.documentElement.getElementsByTagName("marker");
          
          for (var i = 0; i < markers.length; i++) {
            // obtain the attribues of each marker
            var lat = parseFloat(markers[i].getAttribute("lat"));
            var lng = parseFloat(markers[i].getAttribute("lng"));
            var point = new GLatLng(lat,lng);
			// tab 1 data
			var label = markers[i].getAttribute("label");			
			var tab = markers[i].getAttribute("tab");
            var html = markers[i].getAttribute("html");            
			// tab 2 data
			//var html2 = markers[i].getAttribute("html2");            
			//var tab2 = markers[i].getAttribute("tab2");
			
			var tabHtml = []; 
			var tabLabel = []; 
			var t=1;
			for(t=1;t<=8;t++){
				if(markers[i].getAttribute("html"+t)==null) break;
				tabHtml[t-1] = markers[i].getAttribute("html"+t);
				tabLabel[t-1] = markers[i].getAttribute("tab"+t);
			}			
			
			html += '<br>Start Adresse:<form action="http://maps.google.com/maps" method="get" target="_blank">' +
           '<input type="text" SIZE=40 MAXLENGTH=40 name="saddr" id="saddr" value="" /><br>' +
           '<INPUT value="Route berechnen" TYPE="SUBMIT">' +
           '<input type="hidden" name="daddr" value="' + point.lat() + ',' + point.lng() + 
                  //"(" + name + ")" + 
           '"/>';		   
		   tabHtml[t-1] = html; tabLabel[t-1] = tab;
			
			
            // create the marker
            //var marker = createMarker(point,label,html);
			//var marker = createMarkerWithRoute(point,label,html,html2,tab1,tab2);
			var marker = createVariableTabbedMarker(point,tabHtml,tabLabel);
			
            map.addOverlay(marker);			
          }         
        }
      }
      request.send(null);
	  	  		
      }
	  else{
	  // browser not gMaps compatible..
	  }
    }
	
	 // functions that open the directions forms
      function tohere(i) {
        //gmarkers[i].openInfoWindowHtml(to_htmls[i]);
		gmarkers[i].openInfoWindowTabsHtml([new GInfoWindowTab(h1s[i],to_htmls[i]), new GInfoWindowTab(h2s[i],htmls2[i])]);
      }
      function fromhere(i) {
        //gmarkers[i].openInfoWindowHtml(from_htmls[i]);
		gmarkers[i].openInfoWindowTabsHtml([new GInfoWindowTab(h1s[i],from_htmls[i]), new GInfoWindowTab(h2s[i],htmls2[i])]);
      }
	
	// open link in external window
function openExtern(target) {
	//console.log("opening extern link: '"+target+"'");
	win = window.open(target, "_blank");
	win.focus();
}

	

