
//Global --------------------- Sidebar  ----

var sidebar_html = "";
var gmarkers = [];
var pois = [];
var htmls = [];
var a_Pois =[];
var breadPoi=false;	
var i = 0;
var map;
var actualMarker =-1 ;
var degreesPerRadian = 180.0 / Math.PI;
var radiansPerDegree = Math.PI / 180.0;
var select_html = '<select onChange="handleSelected(this)">' +
                  '<option selected> - Select a location - </option>';


function selectPoi(PoiName){
	  if (PoiName.value !=" - Poi auswaehlen - "){
     readPoi("/content/map/poi/" + PoiName.value +".gpx",PoiName.value);
     debug('select Poi ' + document.getElementById("selPoi").value);
   }
}

   // Read the data from url
   // -------------------------------------------------------------------------------------------------
function readPoi(url,PoiName) {
	//alert(url);
	debug('readPoi '); 
	breadPoi=true;
    var request = GXmlHttp.create();
    request.open("GET", url, true);
    request.onreadystatechange = function() {
    if (request.readyState == 4) {
    	document.getElementById("status").innerHTML = PoiName + " Start Parsing";
        var xmlDoc = request.responseXML;
        var wpt = xmlDoc.documentElement.getElementsByTagName("wpt");
        var iconName = url.slice(url.lastIndexOf("/")+1,url.lastIndexOf("."));
        // hide the info window, otherwise it still stays open where the removed marker used to be
        //  map.getInfoWindow().hide();
        pois = [];
        // reset the sidebar
        // document.getElementById("sidebar").innerHTML="";  
        document.getElementById("status").innerHTML = PoiName + " Start Parsing "+wpt.length+" Elements.";
        var cnt =0;
      
        for (i=0; i<gmarkers.length; i++) {
          map.removeOverlay(gmarkers[i]);
        }
        while (a_Pois.length >0 ) {
          a_Pois.pop();
        }             
     
        for (var i = 0; i < wpt.length; i++) {
          document.getElementById("status").innerHTML = PoiName + " Start Parsing "+wpt.length+" Elements. "+proz+"%";
          
  	      var lng = parseFloat(wpt[i].getAttribute("lat"));
   	      var lat = parseFloat(wpt[i].getAttribute("lon"));
    	  var names = wpt[i].getElementsByTagName("name");
    	  var name = names.length ? names[0].childNodes[0].data : "";
          var point = new GLatLng(lng,lat);
          //names.split(" ").length
          var temp = name.replace(/ /,"");
    	    //alert(temp.length);
          if(!temp.length)	name = iconName+"#"+i;
          var proz =wpt.length/(i+1)*100;
          var bounds = map.getBounds();
      	  //							  .getNorthEast();
	      //var SW_Coord = map.getBounds().getSouthWest();
          if (bounds.contains(point)){
          	a_Pois[cnt]= new Object()
            a_Pois[cnt]["point"] = point;
            a_Pois[cnt]["name"] = name;
            a_Pois[cnt]["iconName"] = iconName;
          	//map.addOverlay(createMarker(point, info, mlabel));
          	cnt++;
          	//marker = createMarker(point, name,name,iconName);
          	//map.addOverlay(createMarker(point, name,name,iconName));
          }   
          document.getElementById("status").innerHTML = PoiName + " Parsed "+wpt.length+" Elements.<br> "+cnt+" Elements on Map.";
    	}
    	var cnt2=0;
    	var anz = Math.round(a_Pois.length/20);
    	debug(anz);
    	for (var i = 0; i < a_Pois.length; i++) {
          if (a_Pois.length > 20) { 
    	    if (i % anz == 0){
    	  	  map.addOverlay(createMarker(a_Pois[i]["point"], a_Pois[i]["name"],a_Pois[i]["name"],a_Pois[i]["iconName"]));
    	  	  cnt2++;
    	    }
    	  } else {
    	  	map.addOverlay(createMarker(a_Pois[i]["point"], a_Pois[i]["name"],a_Pois[i]["name"],a_Pois[i]["iconName"]));
    	    cnt2++;
    	  }
    	}
        document.getElementById("status").innerHTML = PoiName + " Parsed "+wpt.length+" Elements.<br> "+cnt+" Elements on Map.<br> "+cnt2+" Elements Shown.";
        // put the assembled sidebar_html contents into the sidebar div
        select_html += '</select>';
        //  if (wpt.length < 50){
        //  	document.getElementById("sidebar").innerHTML = sidebar_html;
        //  } else {
            //document.getElementById("sidebar").innerHTML = select_html;
        //  }
        //actualMarker =-1 ;
      } else {
        document.getElementById("status").innerHTML = PoiName + ' Request send <img src="/system/images/indicator.gif" alt="Working..." />';
      }	
    }
    request.send(null);
}


// This function picks up the click and opens the corresponding info window
function myclick(i) {
   gmarkers[i].openInfoWindowHtml(htmls[i]);
   actualMarker = i;
}
// This function is invoked when the mouse goes over an entry in the sidebar
function mymouseover(i) {
  if (actualMarker ==-1) return;
  document.getElementById("entfernung").innerHTML = calcDistance(actualMarker,i);
}
// This function is invoked when the mouse leaves an entry in the sidebar
function mymouseout(i) {
  if (actualMarker ==-1) return;
  document.getElementById("entfernung").innerHTML ="";
}

function handleSelected(opt) {
   var i = opt.selectedIndex - 1; 
   if (i > -1) {
     GEvent.trigger(gmarkers[i],"click");
   }
   else {
     map.closeInfoWindow();
   }
}
    
function new_loc(){
 map.setCenter(new GLatLng(document.Suchform.Lat.value, document.Suchform.Long.value), 13,G_HYBRID_MAP);
}



function changeMapType(maptype) {
	var x= map.getMapTypes();
  	switch(maptype) {
    	case 'sat':
            //Gets the available map types and then sets the map type
    		//map.setMapType(x[1]);
    		map.setMapType(G_SATELLITE_MAP);
    		mapctrl= "<A href=javascript:changeMapType('map');>Kartenansicht</a><br><A href=javascript:changeMapType('hyb');>Karte/Sat</a><br><A href=javascript:changeMapType('phy');>Gelände</a>";
       	    break;
   		case 'map':
            //Gets the availabe map types and then sets the map type
    	    //	map.setMapType(x[0]);
    		map.setMapType(G_NORMAL_MAP);
    		mapctrl= "<A href=javascript:changeMapType('sat');>Satellitenansicht</a><br><A href=javascript:changeMapType('hyb');>Karte/Sat</a><br><A href=javascript:changeMapType('phy');>Gelände</a>";
    	    break;
    	case 'hyb':
            //Gets the availabe map types and then sets the map type
    		//map.setMapType(x[2]);
    		map.setMapType(G_HYBRID_MAP);
    		mapctrl= "<A href=javascript:changeMapType('sat');>Satellitenansicht</a><br><A href=javascript:changeMapType('map');>Kartenansicht</a><br><A href=javascript:changeMapType('phy');>Gelände</a>";
    	    break;
    	case 'phy':
            //Gets the availabe map types and then sets the map type
    		//map.setMapType(x[3]);
    		map.setMapType(G_PHYSICAL_MAP);
    		mapctrl= "<A href=javascript:changeMapType('sat');>Satellitenansicht</a><br><A href=javascript:changeMapType('map');>Kartenansicht</a><br><A href=javascript:changeMapType('hyb');>Karte/Sat</a>";
    	    break;
 		 
 	}
 	zoom = '<A href=javascript:map.zoomIn();>Vergrößern</a><br><a href=javascript:map.zoomOut();>Verkleinern</a><hr>';
 	document.getElementById('changemap').innerHTML=zoom + mapctrl;
}

    	
    	
if (GBrowserIsCompatible()) {

    // -------------------------------------------------------------------------------------------------
    // Create the Map
    
    map = new GMap2(document.getElementById("map"));
    map.addControl(new GSmallMapControl());
    map.addControl(new GScaleControl());
    // Event listener Move
    GEvent.addListener(map, "moveend", function() {
			var center = map.getCenter();
			var zoom =   map.getZoom();
			if(breadPoi){
			   selectPoi(document.getElementById('selPoi'));
		  }
			debug( center.toString()+" Zoom "+zoom.toString());
			});
    
    map.setCenter(new GLatLng(document.Suchform.Lat.value, document.Suchform.Long.value), 13,G_HYBRID_MAP);
		//map.setCenter(new GLatLng('.$StartCoord.'), '.$ZoomLevel.', '.$Map_Type.');

    // ====== set up marker mouseover tooltip div ======
    var tooltip = document.createElement("div");                        
    map.getPane(G_MAP_FLOAT_PANE).appendChild(tooltip);
    tooltip.style.visibility="hidden";
   
    // Create a base icon for all of our markers that specifies the
    // shadow, icon dimensions, etc.
    // -------------------------------------------------------------------------------------------------
    var baseIcon = new GIcon();
    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);
    baseIcon.infoShadowAnchor = new GPoint(18, 25);             
   
     
    // Helper Func to Create Marker
    // Creates a marker at the given point with the given number label
    // -------------------------------------------------------------------------------------------------
    function createMarker(point, InfoText, MName, iconName) {
    	var icon = new GIcon(baseIcon);
    	var mtype = '';
    	if (iconName==undefined){
        icon.image = "http://www.google.com/mapfiles/marker.png";
      } else {
        icon.image = "http://www.vogtherzog.de/system/icon/poi/"+iconName+".png";
        icon.iconSize = new GSize(22, 22);
       mtype = iconName;
      }
      //alert('Marker');
      var marker = new GMarker(point,icon);
      marker.type = mtype;
      GEvent.addListener(marker, "click", function() {
        marker.openInfoWindowHtml(InfoText);
        actualMarker = i;
      });
      
      if (MName == undefined){
        htmls[i] = InfoText; 
        MName = InfoText;
      } else {
      	if (MName==InfoText){
      		htmls[i]=MName;
      	} else {	 
        	htmls[i] = MName + "<br>" + InfoText;
        }
      } 
      marker.tooltip = '<div class="VHInput">'+MName+'</div>'; 
      gmarkers[i] = marker;
      gmarkers[i].label = MName;
      // add a line to the sidebar html
      //sidebar_html += '<a href="javascript:myclick(' + i + ')" onmouseover="mymouseover('+i+')" onmouseout="mymouseout('+i+')">' + MName + '</a><br>';
      select_html  += '<option> ' + MName + '</option>';
      i++;
      
      
      // alert('Marker2');
      //  ======  The new marker "mouseover" and "mouseout" listeners  ======
      GEvent.addListener(marker,"mouseover", function() {
       showTooltip(marker);
      });        
      //alert('Marker3');
      GEvent.addListener(marker,"mouseout", function() {
	       tooltip.style.visibility="hidden"
      }); 
      //alert('Marker4');
      return marker;
    } // end Create Marker

    

    // Returns the bearing in degrees between two points.
    // North = 0, East = 90, South = 180, West = 270.
    // -------------------------------------------------------------------------------------------------
    function bearing( from, to ) {
      // See T. Vincenty, Survey Review, 23, No 176, p 88-93,1975.
      // Convert to radians.
      var lat1 = from.latRadians();
      var lon1 = from.lngRadians();
      var lat2 = to.latRadians();
      var lon2 = to.lngRadians();
    
      // Compute the angle.
      var angle = - Math.atan2( Math.sin( lon1 - lon2 ) * Math.cos( lat2 ), Math.cos( lat1 ) * Math.sin( lat2 ) - Math.sin( lat1 ) * Math.cos( lat2 ) * Math.cos( lon1 - lon2 ) );
      if ( angle < 0.0 )
           angle  += Math.PI * 2.0;
    
      // And convert result to degrees.
      angle = angle * degreesPerRadian;
      angle = angle.toFixed(1);
    
      return angle;
    }
    
     // -------------------------------------------------------------------------------------------------
    function calcDistance(p1,p2){
      var html = "Distanz:<hr> Von "+gmarkers[p1].label;
      if (p2==undefined) return html;          
      if (p1==p2) return html;
      
      var d=gmarkers[p1].getPoint().distanceFrom(gmarkers[p2].getPoint())/1000;
      html += " bis "+gmarkers[p2].label;
      html += "<br> "+ d.toFixed(5) +" km ";
      html += "  Richtung: "+bearing(gmarkers[p1].getPoint(),gmarkers[p2].getPoint())+" Grad<br>";
      return html;  
    }
     
     // ====== This function displays the tooltip ======
     // it can be called from an icon mousover or a sidebar mouseover
     // -------------------------------------------------------------------------------------------------
    function showTooltip(marker) {
    	tooltip.innerHTML = marker.tooltip;
        var point=map.getCurrentMapType().getProjection().fromLatLngToPixel(map.fromDivPixelToLatLng(new GPoint(0,0),true),map.getZoom());
        var offset=map.getCurrentMapType().getProjection().fromLatLngToPixel(marker.getPoint(),map.getZoom());
        var anchor=marker.getIcon().iconAnchor;
        var width=marker.getIcon().iconSize.width+5;
        var height=tooltip.clientHeight+5;
        var pos = new GControlPosition(G_ANCHOR_TOP_LEFT, new GSize(offset.x - point.x - anchor.x + width, offset.y - point.y -anchor.y -height)); 
        pos.apply(tooltip);
        tooltip.style.visibility="visible";
    }
    
     
       
     // Read the data from url
     // -------------------------------------------------------------------------------------------------
    function readPersonalDate(url) { 
      var request = GXmlHttp.create();
      request.open("GET", url, true);
      request.onreadystatechange = function() {
        if (request.readyState == 4) {
          var xmlDoc = request.responseXML;
          // obtain the array of markers and loop through it
          var markers = xmlDoc.documentElement.getElementsByTagName("marker");
          
          // hide the info window, otherwise it still stays open where the removed marker used to be
          map.getInfoWindow().hide();
          
          for (i=0; i<gmarkers.length; i++) {
            map.removeOverlay(gmarkers[i]);
          }
          // empty the array
          gmarkers = [];
       
          // reset the sidebar
          sidebar_html="";            
          
          for (var j = 0; j < markers.length; j++) {
            // obtain the attribues of each marker
            var point = new GLatLng(parseFloat(markers[j].getAttribute("lat")),
                                    parseFloat(markers[j].getAttribute("lng")));
            var info  = markers[j].getAttribute("infotext"); 
            var mlabel  = markers[j].getAttribute("markername");                         
          
           	map.addOverlay(createMarker(point, info, mlabel));
                     
                       
           //map.addOverlay(new GMarker(point));
           
          }
          // put the assembled sidebar_html contents into the sidebar div
          //document.getElementById("sidebar").innerHTML = sidebar_html;
          actualMarker =-1 ;
        }
      }
      request.send(null);
    } 



    
      
    // Load the Data
    // -------------------------------------------------------------------------------------------------
	   //readPersonalDate("'.$Datafile.'");
	   //readPoi("/content/map/poi/Skoda.gpx");
	   //readPoi("'.$datafile2.'");
	   
}


    	       



    //]]>

