jQuery(document).ready(function() {
	var map = null;
	var bounds = null;
	var geoapp = {
		init : function() {
			map = new GMap2(document.getElementById("map_canvas"));
			var startLat=48;
		    var startLng=7;
		    var startpoint = new GLatLng(startLat,startLng);
		    map.setCenter(startpoint, 4);   
			//map.addControl(new GSmallMapControl());
		    //map.addControl(new GMapTypeControl());
			map.addMapType(G_PHYSICAL_MAP);
	        map.setMapType(G_PHYSICAL_MAP);
	        map.removeMapType(G_HYBRID_MAP);
	        if (typeof console != 'undefined')
			console.log('init done');
		},

		handlePosition : function(a) {
			bounds = new GLatLngBounds();
			// $j('#locateButton').siblings('img').hide();
			var zoomLevel = 14;
			if (a.coords.accuracy > 500)
				zoomLevel = 10;
			var point = new GLatLng(a.coords.latitude,
					a.coords.longitude);
			if (typeof console != 'undefined')
			console.log('point:');
			if (typeof console != 'undefined')
			console.log(point);
			map.setCenter(point, zoomLevel);
			
			var Icon = new GIcon(G_DEFAULT_ICON);
			var marker = new GMarker(point, Icon);
			map.addOverlay(marker);
			// map.addOverlay(overlay);
			if (typeof yourvar != 'undefined')
			console.log('done with accuracy: ' + a.coords.accuracy);
			
			var city=geoapp.getCityName(a.coords.latitude, a.coords.longitude);
			var clubxml=geoapp.getClubXML(city);
		},

		handleError : function(error) {
			if(error.PERMISSION_DENIED){
				//alert("PERMISSION_DENIED!");
			} else if(error.POSITION_UNAVAILABLE){
				//alert("POSITION_UNAVAILABLE!");
			} else if(error.TIMEOUT){
			    //alert("TIMEOUT!");
			}
			geoapp.ipFallBack();
			if (typeof console != 'undefined')
			console.log("error output:");
			if (typeof console != 'undefined')
			console.log(error);
			jQuery('#locateButton').siblings('img').hide();
			jQuery('#geodemo-error').show();
		},

		locateMeOnMap : function(geoapi) {
			jQuery('#geodemo-error').hide();
			jQuery('#geo-demo').show();
			jQuery('#geo-busy2').show();
			map.checkResize();
			if (geoapi) {
			navigator.geolocation.getCurrentPosition(this.handlePosition,
					this.handleError,
					{timeout:60000});
			}
			else {
				geoapp.ipFallBack();
			}
		},
		ipFallBack: function() {
			jQuery.getJSON('/api/geoapi.php', function(data) {
				var geoloc={coords:{latitude:data.latitude,longitude:data.longitude,accuracy:1000}};
				geoapp.handlePosition(geoloc);
			});
		},
		getCityName: function (latitude, longitude) {
			jQuery.ajax({
				url: "/api/getCity.php",
				type: "POST",
				data:{'latitude':latitude, 'longitude':longitude},
				success: function(response){
					if (response.length>0)
						geoapp.getClubXML(response);
					else {
						alert('Es ist bei der Bestimmung ihres Ortes ein Fehler aufgetreten.');
						jQuery('#geo-busy2').hide();
					}
				}
			});
		},
		getClubXML: function (location) {
			if (typeof location != 'undefined') {
				//alert(location);
				jQuery.ajax({
					url: '/golfmap.php',
					type: "GET",
					data:{'plz':location, 'distance':25, 'county':3, 'radio':'city', 'city':location},
					dataType: 'html',
					success: geoapp.loadClubXML
				});
			}
		},
		loadClubXML : function(response) {
			//console.log(response)
			if (response.length>0) {
				jQuery.ajax({
					url: '/'+response,
					type: "GET",
					success: function(xml){
						//console.log(xml);
						jQuery(xml).find("marker").each(function()
						{
							//console.log(this);
							var point = new GLatLng(
								jQuery(this).attr('lat'),
								jQuery(this).attr('lng')
							);
							
							
							var domain = 'http://' + window.location.hostname + '/';
							var imageIcon=domain+"images/googlemap/icon13.png";
					        var imageIcon_hover=domain+"images/googlemap/icon5.png";
					        var Icon = new GIcon(G_DEFAULT_ICON);
					        Icon.image = imageIcon;
					        var marker = new GMarker(point, {'icon': Icon,'title':jQuery(this).find('name').text()});
					        var link = jQuery(this).find('url').text();
				            GEvent.addListener(marker, "click", function() {
				                window.location.href = link;
				            });
				            // Switch icon on marker mouseover and mouseout
				            GEvent.addListener(marker, "mouseover", function() {
				                marker.setImage(imageIcon_hover);
				            });
				            GEvent.addListener(marker, "mouseout", function() {
				                marker.setImage(imageIcon);
				            });
							map.addOverlay(marker);
							bounds.extend(point);
						});
						map.setCenter(bounds.getCenter());
						map.setZoom(map.getBoundsZoomLevel(bounds));
						jQuery('#geo-busy2').hide();
						//alert('all done');
					}
				});
			}
			else {
				alert('Es ist bei der Bestimmung ihres Ortes ein Fehler aufgetreten.');
				jQuery('#geo-busy2').hide();
			}
		}
	}
	
	geoapp.init();
	//geoapp.foo();
	jQuery('#locateButton').click(function(event) {
		event.preventDefault();
		if (navigator.geolocation)
			geoapp.locateMeOnMap(true);
		else {
			geoapp.locateMeOnMap(false);
		}
	});
});
