GM_Styles();
function GM_Styles() {
	// Set up some styles
	document.writeln('		<style type="text/css">');
	document.writeln('			.gv_tooltip { background-color:#ffffff; filter:alpha(opacity=100); -moz-opacity:1.0; border:1px solid #666666; padding:2px; text-align:left; font:10px Verdana,sans-serif; color:black; white-space:nowrap; }');
	document.writeln('			.gv_tooltip img.gv_marker_thumbnail { display:block; padding-top:3px; }');
	document.writeln('			.gv_tooltip img.gv_marker_photo { display:none; }');
	document.writeln('		</style>');
}

function updateShopList(cntr) {
	var newLat = cntr.lat();
	var newLng = cntr.lng();
	
	var url = "/tl_files/googleMaps/getShopData.php?lat="+newLat+"&lng="+newLng;

	/**
	 * The simple way for an Ajax request, use onRequest/onComplete/onFailure
	 * to do add your own Ajax depended code.
	 */
	new Request({
		url: url,
		method: 'get',
		onSuccess: function(txt){
			$('shopList').set('html', txt);
		}
	}).send();
}

function calculateDistance() {
	distanceDirectionsInstance = new GDirections();
	var arrLocation = new Array();
	for(i=0;i<ajaxShopList.length;i++){
		arrLocation[0] = startAddress;
		arrLocation[1] = ajaxShopList[i][3];
		distanceDirectionsInstance.load(arrLocation);
	}
}

function getDistanceNow(){
	alert(distanceDirectionsInstance.getDistance().html)
}

function showRouteToShop(i){
	$('searchresult').innerHTML = '';
	$('furtherInformation').style.display = 'block';
	addy = shopAddresses[i];
	direct.clear();
	
	var arrLocation = new Array();
	arrLocation[0] = startAddress;
	arrLocation[1] = addy;

	//Load the map and directions from the specified waypoints
	direct.loadFromWaypoints(arrLocation);
	$('shopInformation').innerHTML = shopInfos[i];
	eval('marker'+i).closeInfoWindow();
}

function fitMap(i) {
	var myPoints = new Array();
	myPoints[0] = new GLatLng(homePoint[1], homePoint[0]);
	myPoints[1] = new GLatLng(shopLat[i], shopLng[i]); 
	
	var bounds = new GLatLngBounds();
	for (var i=0; i< myPoints.length; i++) {
		bounds.extend(myPoints[i]);
	}
	map.setZoom(map.getBoundsZoomLevel(bounds));
	map.setCenter(bounds.getCenter());
}

function removeRouteMarker(){
	for(i=0; i < direct.getNumRoutes()+1;i++){
		var directionMarker = direct.getMarker(i);
    	map.removeOverlay(directionMarker);
	}
}

function getSingleDistance() {
    addy = arr[i]['addy'];
	direct.load("from: " + startAddress + " to: " + addy, {"locale": document.getElementById('countryQuery').getValue()});
	document.getElementById('distanz'+i).innerHTML = direct.getDistance().html;
}

function GM_Initialize_Marker_Tooltip(map) {
	var mtt = document.createElement('div');
	mtt.id = 'gm_marker_tooltip';
	mtt.style.visibility = 'hidden';
	map.getPane(G_MAP_FLOAT_PANE).appendChild(mtt);
	return (mtt);
}

function GM_Create_Marker_Tooltip(map,marker) {
	// copied almost verbatim from http://www.econym.demon.co.uk/googlemaps/tooltips4.htm
	if (!marker || !marker.tooltip) { return false; }
	document.getElementById('gm_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;
	var height=document.getElementById('gm_marker_tooltip').clientHeight;
	offset.x += -1; offset.y += 4; // a little adjustment
	height = 18; // makes all tooltips hover near the icon, even if they're tall and have thumbnails or whatnot (they expand downward instead of upward)
	var pos = new GControlPosition(G_ANCHOR_TOP_LEFT, new GSize(offset.x -point.x -anchor.x +width, offset.y -point.y -anchor.y -height*0.75)); 
	pos.apply(document.getElementById('gm_marker_tooltip'));
	document.getElementById('gm_marker_tooltip').style.visibility = 'visible';
}

function GM_Hide_Marker_Tooltip() {
	document.getElementById('gm_marker_tooltip').style.visibility = 'hidden';
}

function createMarker(map, longitude, latitude, infoWindowContent, name, index) {
	eval('point' + index + '= new GPoint(longitude,latitude);');
	eval('icon' + index + '= new GIcon(arcoIcon);');
	eval('icon' + index + '.iconSize = new GSize(17, 28);');
	eval('marker' + index + '= new GMarker(point' + index + ',icon' + index + ')');
	eval('var thisMarker = marker' + index +';');
	
	GEvent.addListener(
			thisMarker, 'click', function() {
			thisMarker.openInfoWindowHtml(infoWindowContent);
		}
	);
	
	if (!document.getElementById('gm_marker_tooltip')) { gm_marker_tooltip = GM_Initialize_Marker_Tooltip(map); } // initialize it if it hasn't been done yet
	var tooltip_html = name;
	thisMarker.tooltip = '<div class=\"gv_tooltip\">' + tooltip_html + '</div>';
	
	GEvent.addListener(thisMarker,'mouseover', 
		function() { 
			GM_Create_Marker_Tooltip(map,thisMarker);
			if(document.getElementById('shopListItem'+index)){
				document.getElementById('shopListItem'+index).style.backgroundColor = '#cbcbb8';
			}
		}
	);
	
	GEvent.addListener(thisMarker,'mouseout', 
		function() { 
			GM_Hide_Marker_Tooltip();
			if(document.getElementById('shopListItem'+index)){
				document.getElementById('shopListItem'+index).style.backgroundColor = '#f3f3e9';
			}
		}
	);
	
	map.addOverlay(thisMarker);
}

function changeIcon(markerId, lat, lng){

	map.removeOverlay(eval('marker' + markerId));

	eval('point' + markerId) = new GPoint( lng, lat);
    eval('shopIcon' + markerId) = new GIcon(arcoIcon);
	
	eval('marker' + markerId) = new GMarker( eval('point' + markerId), eval('shopIcon' + markerId) );
  	GEvent.addListener(eval('marker' + markerId), 'click',
  		function(){ 
    		eval('marker' + markerId).openInfoWindowHtml(
    			"This is a test..."
    		);
  		}
  	);
  	
  	map.addOverlay(eval('marker' + markerId));
}


function handleErrors(){
   if (map.getStatus().code == G_GEO_UNKNOWN_ADDRESS)
     alert("No corresponding geographic location could be found for one of the specified addresses. This may be due to the fact that the address is relatively new, or it may be incorrect.\nError code: " + map.getStatus().code);
   else if (map.getStatus().code == G_GEO_SERVER_ERROR)
     alert("A geocoding or directions request could not be successfully processed, yet the exact reason for the failure is not known.\n Error code: " + map.getStatus().code);
   
   else if (map.getStatus().code == G_GEO_MISSING_QUERY)
     alert("The HTTP q parameter was either missing or had no value. For geocoder requests, this means that an empty address was specified as input. For directions requests, this means that no query was specified in the input.\n Error code: " + map.getStatus().code);
     
   else if (map.getStatus().code == G_GEO_BAD_KEY)
     alert("The given key is either invalid or does not match the domain for which it was given. \n Error code: " + map.getStatus().code);

   else if (map.getStatus().code == G_GEO_BAD_REQUEST)
     alert("A directions request could not be successfully parsed.\n Error code: " + map.getStatus().code);
    
   else alert("An unknown error occurred.");
   
}

function startSearch(address) {
	if( ! geoTranslater) return;
	if( address == '') return;
	if( address == 'Straße 123, 45678 Ort') return;
	geoTranslater.getLocations(
		address,
		function(point) {
			var ret = '';
			var numresults = 0;
			if( point.Placemark) {
				for( i = 0; i < point.Placemark.length; i++) {	// Mögliche Varianten als Auswahlergebnis auflisten
					if( point.Placemark[i]) {
						ret += '<a href="javascript:startSearch(\''+point.Placemark[i].address+'\');">'+point.Placemark[i].address+'</a /><br />';
						numresults++;
					}
				}
			}
			// Multiple possible matches: Show chooser list
			if( numresults > 1) {
				map.setCenter(new google.maps.LatLng(51, 9), 5);	// Germany
				document.getElementById('map').style.width = '600px';
				document.getElementById('searchresult').innerHTML = '<b>Meinten Sie</p>:<br />'+ret+'<div style=\'margin-bottom:25px;\'></div>';
				//document.getElementById('usedsearchaddress').innerHTML = 'Diese Angabe hat mehrere Varianten';
				
			// One result: start dealer search
			} else if( numresults > 0) {
				var place = point.Placemark[0];
				startAddress = place.address;
				document.getElementById('adressQuery').value = startAddress;
				homePoint[1] = place.Point.coordinates[1];
				homePoint[0] = place.Point.coordinates[0];
				var point2 = new GLatLng(place.Point.coordinates[1], place.Point.coordinates[0]);
				map.setCenter(point2, 9);
				
				var userIcon = new GIcon(arcoIcon);
				userIcon.image = "/tl_files/googleMaps/arko_google_user.png";
				
				marker = new GMarker( point2, userIcon );
				map.addOverlay(marker);
				document.getElementById('searchresult').innerHTML = '';
				updateShopList(map.getCenter());
				document.getElementById('map').style.width = '870px';
			
			// Address not found: display error
			} else {
				map.setCenter(new google.maps.LatLng(51, 9), 5);	// Germany
				document.getElementById('searchresult').innerHTML = '<p>Die angegebene Adresse <em>"'+address+'"</em> wurde nicht gefunden!<br />Bitte korrigieren Sie Ihre Adresseingabe.</p>';
				alert('Die angegebene Adresse\n\n"'+address+'"\n\nwurde nicht gefunden!\n\nBitte korrigieren Sie Ihre Adresseingabe.');
			}
	        
	       /* if (!point) {
	            alert(document.getElementById('adressQuery').getValue() + " not found");
	        } else {
	            map.setCenter(point, 9);
	            
				var userIcon = new GIcon(arcoIcon);
				userIcon.image = "/tl_files/googleMaps/arko_google_user.png";
				
				marker = new GMarker( point, userIcon );
				map.addOverlay(marker);
				
				updateShopList(map.getCenter());
			}/**/
		}
	);
}

function isset(varname)  {
  if(typeof( window[ varname ] ) != "undefined") return true;
  else return false;
}
