var map, activeMarker, crosshairPoly=false;
    var geocoder;
	
		var iconBlue=new GIcon(); 
    	//iconBlue.image='http://labs.google.com/ridefinder/images/mm_20_blue.png';
		iconBlue.image='../images/mm_20_blue.gif';
    	iconBlue.shadow='../images/mm_20_shadow.png';
    	iconBlue.iconSize=new GSize(12, 20);
    	iconBlue.shadowSize=new GSize(22, 20);
    	iconBlue.iconAnchor=new GPoint(6, 20);
    	iconBlue.infoWindowAnchor=new GPoint(5, 1);

		var iconRed=new GIcon(); 
    	iconRed.image='../images/mm_20_red.gif';
		iconRed.shadow='../images/mm_20_shadow.png';
		iconRed.iconSize=new GSize(12, 20);
		iconRed.shadowSize=new GSize(22, 20);
		iconRed.iconAnchor=new GPoint(6, 20);
		iconRed.infoWindowAnchor=new GPoint(5, 1);
	
		var iconYellow=new GIcon(); 
		iconYellow.image='../images/mm_20_yellow.gif';
		iconYellow.shadow='../images/mm_20_shadow.png';
		iconYellow.iconSize=new GSize(12, 20);
		iconYellow.shadowSize=new GSize(22, 20);
		iconYellow.iconAnchor=new GPoint(6, 20);
		iconYellow.infoWindowAnchor=new GPoint(5, 1);
	
		var customIcons = [];
		customIcons["SH"]=iconBlue;
		customIcons["SF"]=iconRed;
		customIcons["SB"]=iconYellow;
	
		customIcons["FH"]=iconBlue;
    	customIcons["FF"]=iconRed;
		customIcons["FB"]=iconYellow;
	
		customIcons["JH"]=iconBlue;
		customIcons["JF"]=iconRed;
		customIcons["JB"]=iconYellow;
	
		customIcons["OH"]=iconBlue;
		customIcons["OF"]=iconRed;
		customIcons["OB"]=iconYellow;

	
	function load() {
      if (GBrowserIsCompatible()) {
        geocoder = new GClientGeocoder();
        map = new GMap2(document.getElementById('map'));
		map.addMapType(G_SATELLITE_3D_MAP);
		map.addControl(new GLargeMapControl());
        map.addControl(new GMapTypeControl());
		//map.enableGoogleBar();
        map.setCenter(new GLatLng(56.26392, 9.501785), 7);
      }
    }

   function searchLocations() {
     var adresse = document.getElementById('adresseInput').value;
	 geocoder.setBaseCountryCode("dk") 
     geocoder.getLatLng(adresse, function(latlng) {
       if (!latlng) {
         alert(adresse + ' not found');
       } else {
         searchLocationsNear(latlng);
       }
     });
   }

   function searchLocationsNear(center) {
     map.clearOverlays();	//	moved this so it doesnt clear the crosshair polys 
     var radius = document.getElementById('radiusSelect').value;
     var searchUrl = 'map_data_xml.php?lat=' + center.lat() + '&lng=' + center.lng() + '&radius=' + radius; //alert(searchUrl)
     GDownloadUrl(searchUrl, function(data) {
       var xml = GXml.parse(data);
       var markers = xml.documentElement.getElementsByTagName('marker');

       var sidebar = document.getElementById('sidebar');
       sidebar.innerHTML = '';
       if (markers.length == 0) {
         sidebar.innerHTML = 'No results found.';
        map.setCenter(new GLatLng(56.26392, 9.501785), 7);
		 
         return;
       }

       var bounds = new GLatLngBounds();
       for (var i = 0; i < markers.length; i++) {
         var name = markers[i].getAttribute('name');
		 var branchname = markers[i].getAttribute('branchname');
		 var branch_id = markers[i].getAttribute('branch_id');
		 var email = markers[i].getAttribute('email');
		 var hjemmeside = markers[i].getAttribute('hjemmeside');
         var adresse = markers[i].getAttribute('adresse');
		 var postnummer = markers[i].getAttribute('postnummer');
		 var city = markers[i].getAttribute('city');
		 var tlf = markers[i].getAttribute('tlf');
		 var telefax = markers[i].getAttribute('telefax');
		 var category = markers[i].getAttribute('category');
         var distance = parseFloat(markers[i].getAttribute('distance'));
         var point = new GLatLng(parseFloat(markers[i].getAttribute('lat')),
                                 parseFloat(markers[i].getAttribute('lng')));
         
         var marker = createMarker(point, name, branch_id, branchname, email, hjemmeside, adresse, postnummer, tlf, telefax, city, category);
         map.addOverlay(marker);
         var sidebarEntry = createSidebarEntry(marker, name, branch_id, branchname, adresse, postnummer, tlf, telefax, city, distance, category);
         sidebar.appendChild(sidebarEntry);
         bounds.extend(point);
       }
       map.setCenter(bounds.getCenter(), map.getBoundsZoomLevel(bounds));
	   map.savePosition();
     });
	 drawCrosshair(center, radius);
   }

    function createMarker(point, name, branch_id, branchname, email, hjemmeside, adresse, postnummer, tlf, telefax, city, category) {
	  var marker = new GMarker(point, customIcons[category]);
	  //GLog.write(category);
	  

var html='<div class="infowindow"><b>Branch id: </b> '+branch_id+'&nbsp; &#8212; &nbsp; <b>Bibliotekstype: </b>' + category + '<br /><b>Biblioteksnavn:</b> '+name+'<br /><b>Biblioteksafdeling:</b> '+branchname+'<br /><b>Adresse: </b>'+adresse+', '+postnummer+' '+city+'<br /><b>Tlf.nr.: </b>' + tlf + ' &nbsp; &#8212; &nbsp; <b>Telefax: </b>' + telefax + '<br /><b>E-mail: </b><a href=\"mailto:' + email + '\">' + email + '</a><br /><b>Hjemmeside: </b><a href="'+hjemmeside+'">'+hjemmeside+'</a>	<br /><img src="../images/icon_dgs.gif" width="20" height="19">&nbsp;<a href="http://www.degulesider.dk/vbw/kort/rute-resultat.do?&to.b=' + city + '&to.z=' + postnummer + '&to.g=' + adresse + '&partnerid=kortlink' + '">I bil - Til fods - P&aring; cykel - Ruteplan</a>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<img src="../images/icon_rejseplan.gif" width="17" height="17">&nbsp;<a href="http://www.rejseplanen.dk/bin/query.exe/mn?ZADR=1&Z=' + adresse + ', ' + postnummer + '">Rejseplanen</a><br />S&oslash;g i n&aelig;rheden: f.eks. pizza, caf&eacute;, tog osv.<form action="http://maps.google.dk/maps" method="get"" target="_blank">'+ '<input type="text" SIZE=35 MAXLENGTH=80 name="q" id="q" value="" />'+ '<INPUT value="S&Oslash;G" TYPE="SUBMIT">'+ '<input type="hidden" name="near" value="' + name+ ' @' + point.lat() + ',' + point.lng() + '"/>';

		html+='<br /><a href="javascript:zoomIn()"><img src="../images/transparent.gif" width="140" height="1"><img src="../images/zoomin.gif" alt="Zoom In" title="Zoom In" height="24" width="26"></a><a href="javascript:zoomOut()"><img src="../images/resetzoom.gif" alt="Reset Zoom" title="Reset Zoom" height="24" width="26"></a><a href="javascript:map.closeInfoWindow()"><img src="../images/close.gif" alt="Close" title="Close" height="24" width="21"></a>';
	   html+='</div>';

	  
	  

      GEvent.addListener(marker, 'click', function() {
        marker.openInfoWindowHtml(html);
		//	store marker whose infowindow is open as activeMarker (new global)
		activeMarker=marker;
      });
      return marker;
    }

    function createSidebarEntry(marker, name, branch_id, branchname, adresse, postnummer, tlf, telefax, city, distance, category) {
      var div = document.createElement('div');

var html = '<img src="'+customIcons[category].image+'" width="9" height="15"> <b>'+branch_id+' - '+name+' </b>('+distance.toFixed(1)+') km<br/><b>'+branchname+'</b><br/> '+adresse+', '+postnummer+' '+city+'<hr />';

      //Original code
	  div.innerHTML = html;
      div.style.cursor = 'pointer';
      div.style.marginBottom = '5px'; 
      GEvent.addDomListener(div, 'click', function() {
        GEvent.trigger(marker, 'click');
      });
      GEvent.addDomListener(div, 'mouseover', function() {
        div.style.backgroundColor = '#eee';
      });
      GEvent.addDomListener(div, 'mouseout', function() {
        div.style.backgroundColor = '#fff';
      });
      return div;
    }

	function zoomIn(){
	map.closeInfoWindow();
	map.setCenter(activeMarker.getLatLng(), 17, G_HYBRID_MAP);
	GEvent.trigger(activeMarker, "click");
}

function zoomOut(){
	map.closeInfoWindow();
	map.setCenter(activeMarker.getLatLng(), 10, G_NORMAL_MAP);
	GEvent.trigger(activeMarker, "click");
}
function drawCrosshair(center, radius){
	// Esa 2006 http://esa.ilmari.googlepages.com/circle.htm
	//calculating km/degree
	var latConv=center.distanceFrom(new GLatLng(center.lat()+0.1, center.lng()))/100;
	var lngConv=center.distanceFrom(new GLatLng(center.lat(), center.lng()+0.1))/100;

	//	nodes must be a divisor of 360 else cross lines won't be correct
	//var nodes=72, liColor='black', liWidth=1; liOpac=0.7, crossSize=0.2;
	var nodes=72, liColor='red', liWidth=2; liOpac=0.7, crossSize=0.2;
	liWidth=liWidth||2;

	if(crosshairPoly===false){
		crosshairPoly={};
	} else {
		map.removeOverlay(crosshairPoly.vertical);
		map.removeOverlay(crosshairPoly.horizontal);
		map.removeOverlay(crosshairPoly.circle);
	}
	
	var circlePoints=[], verticalPoints=[], horizontalPoints=[], step=parseInt(360/nodes)||10, point;
	for(var i=0; i<=360; i+=step){
		point=new GLatLng(center.lat()+(radius/latConv * Math.cos(i * Math.PI/180)), center.lng()+(radius/lngConv * Math.sin(i * Math.PI/180)))
		circlePoints.push(point);
		if(i===90 || i===270){
			horizontalPoints.push(point);
		} else if(i===0 || i===180){
			verticalPoints.push(point);
		}
	}
	circlePoints.push(circlePoints[0]);
	crosshairPoly.circle=new GPolyline(circlePoints, liColor, liWidth, liOpac);
	crosshairPoly.vertical=new GPolyline(verticalPoints, liColor, liWidth, liOpac);
	crosshairPoly.horizontal=new GPolyline(horizontalPoints, liColor, liWidth, liOpac);
	map.addOverlay(crosshairPoly.vertical);
	map.addOverlay(crosshairPoly.horizontal);
	map.addOverlay(crosshairPoly.circle);
}
