
var G_GEO_SUCCESS             = 200;
var G_GEO_BAD_REQUEST         = 400;
var G_GEO_SERVER_ERROR        = 500;
var G_GEO_MISSING_QUERY       = 601;
var G_GEO_MISSING_ADDRESS     = 601;
var G_GEO_UNKNOWN_ADDRESS     = 602;
var G_GEO_UNAVAILABLE_ADDRESS = 603;
var G_GEO_UNKNOWN_DIRECTIONS  = 604;
var G_GEO_BAD_KEY             = 610;
var G_GEO_TOO_MANY_QUERIES    = 620;

var map;
var directionsPanel;
var directions;
var selLang = "German";
var usedProtocol = "http";

var tsc = {
	English:	"T&Uuml;V S&Uuml;D Service-Centre",
	German:		"T&Uuml;V S&Uuml;D Service-Center"
};

var thsc = {
	English:	"T&Uuml;V HANSE Service-Centre",
	German:		"T&Uuml;V HANSE Service-Center"
};


var routeError = {
	English:	"Route could not be calculated. Please change your input!",
	German:		"Route kann nicht berechnet werden. Bitte &auml;ndern Sie ihre Eingaben!"
};

var reasons=[];   
reasons[G_GEO_SUCCESS]            = "";
reasons[G_GEO_MISSING_ADDRESS]    = "Missing Address: The address was either missing or had no value.";     
reasons[G_GEO_UNKNOWN_ADDRESS]    = "Unknown Address:  No corresponding geographic location could be found for the specified address."; 
reasons[G_GEO_UNAVAILABLE_ADDRESS]= "Unavailable Address:  The geocode for the given address cannot be returned due to legal or contractual reasons.";
reasons[G_GEO_BAD_KEY]            = "Bad Key: The API key is either invalid or does not match the domain for which it was given";
reasons[G_GEO_TOO_MANY_QUERIES]   = "Too Many Queries: The daily geocoding quota for this site has been exceeded.";                                   
reasons[G_GEO_SERVER_ERROR]       = "Server error: The geocoding request could not be successfully processed.";

/* http://code.google.com/apis/maps/ */
function loadMap(wobjectId,lat,lon,zoomLevel,iconDir,usedProtocol) {
	/*alert(wobjectId+","+lat+","+lon+","+zoomLevel+", "+iconDir+", "+usedProtocol);*/
	if (usedProtocol=="" || !usedProtocol) {
		usedProtocol = "http";
	}
	var baseIconPath = usedProtocol+"://www.tuev-sued.de/extras/styles/tuev_internet/images/gicon/";
	var iconPath = baseIconPath+iconDir;
	/*alert(iconPath);*/
	if (document.getElementById("map_"+wobjectId) == null) {
		return false;
	}
	if (GBrowserIsCompatible()) {
		var map = new GMap2(document.getElementById("map_"+wobjectId));
		map.setCenter(new GLatLng(lat,lon),parseInt(zoomLevel));
		gMapType = map.getMapTypes();
		map.setMapType(gMapType[0]);  // [0] map [1] satellite [2] hybrid
		map.enableScrollWheelZoom();
		map.addControl(new GLargeMapControl());
		map.addControl(new GMapTypeControl());
		/*map.addControl(new GOverviewMapControl());*/
		
		var icon = new GIcon();
		icon.image = iconPath+"/large.png";
		icon.shadow = iconPath+"/large_shadow.png";
		icon.iconSize = new GSize(86, 73);
		icon.shadowSize = new GSize(86, 73);
		icon.iconAnchor = new GPoint(29, 73);
		marker = new GMarker(map.getCenter(),{icon:icon});
		map.addOverlay(marker);
		
		/* set icons for different zoom level*/
		var zl = GEvent.addListener(map, "zoomend", function() {
			map.clearOverlays();
			if (map.getZoom() > 13) {
				var icon = new GIcon();
				icon.image = iconPath+"/large.png";
				icon.shadow = iconPath+"/large_shadow.png";
				icon.iconSize = new GSize(86, 73);
				icon.shadowSize = new GSize(86, 73);
				icon.iconAnchor = new GPoint(29, 73);
				icon.transparent = baseIconPath+"/large_transparent.png";
			} else if (map.getZoom() <= 13 && map.getZoom() > 10) {
				var icon = new GIcon();
				icon.image = iconPath+"/medium.png";
				icon.shadow = iconPath+"/medium_shadow.png";
				icon.iconSize = new GSize(65, 55);
				icon.shadowSize = new GSize(65, 55);
				icon.iconAnchor = new GPoint(22, 55);
				icon.transparent = baseIconPath+"/medium_transparent.png";
			} else if (map.getZoom() <= 10 && map.getZoom() > 8) {
				var icon = new GIcon();
				icon.image = iconPath+"/small.png";
				icon.shadow = iconPath+"/small_shadow.png";
				icon.iconSize = new GSize(43, 37);
				icon.shadowSize = new GSize(43, 37);
				icon.iconAnchor = new GPoint(15, 37);
				icon.transparent = baseIconPath+"/small_transparent.png";
			} else {
				var icon = new GIcon();
				icon.image = iconPath+"/mini.png";
				icon.shadow = iconPath+"/mini_shadow.png";
				icon.iconSize = new GSize(32, 28);
				icon.shadowSize = new GSize(32, 28);
				icon.iconAnchor = new GPoint(11, 28);
				icon.transparent = baseIconPath+"/mini_transparent.png";
			}
			marker = new GMarker(new GLatLng(lat,lon),{icon:icon});
			map.addOverlay(marker);
		});
		
		
	} else {
		/*alert("Dieser Browser ist leider nicht mit Google Maps kompatibel.");*/
	}
}

function loadBoxMap(wobjectId,lat,lon,zoomLevel,iconDir,usedProtocol) {
	/*alert(wobjectId+","+lat+","+lon+","+zoomLevel+", "+iconDir);*/
	zoomLevel = 15;
	if (usedProtocol=="" || !usedProtocol) {
		usedProtocol = "http";
	}
	var iconPath = usedProtocol+"://www.tuev-sued.de/extras/styles/tuev_internet/images/gicon/"+iconDir;
	/*alert(iconPath);*/
	if (document.getElementById("map_"+wobjectId) == null) {
		return false;
	}
	if (GBrowserIsCompatible()) {
		var map = new GMap2(document.getElementById("map_"+wobjectId),{draggableCursor: 'hand', draggingCursor: 'hand'});
		map.setCenter(new GLatLng(lat,lon),parseInt(zoomLevel));
		gMapType = map.getMapTypes();
		map.setMapType(gMapType[0]);  // [0] map [1] satellite [2] hybrid
		
		var icon = new GIcon();
		icon.image = iconPath+"/mini.png";
		icon.shadow = iconPath+"/mini_shadow.png";
		icon.iconSize = new GSize(32, 28);
		icon.shadowSize = new GSize(32, 28);
		icon.iconAnchor = new GPoint(11, 28);
		icon.infoWindowAnchor = new GPoint(11, 1);
		marker = new GMarker(map.getCenter(),{icon:icon});
		map.addOverlay(marker);
		
		var zl = GEvent.addListener(map, "click", function() {
			redirectWobject(wobjectId);
		});
		
	} else {
		/*alert("Dieser Browser ist leider nicht mit Google Maps kompatibel.");*/
	}
}

function initializeMap (lat,lon,zoom,languageId,givenProtocol) {
		selLang = languageId;
		usedProtocol = givenProtocol;
		/*alert("initializeMap: "+lat+" / "+lon);*/
		if (GBrowserIsCompatible()) {
			document.getElementById('wopsMap').style.visibility = "visible";
			document.getElementById('wopsMap').style.display = "block";
			map = new GMap2(document.getElementById("wopsMap"));
			map.setCenter(new GLatLng(lat,lon),parseInt(zoom));
			
			gMapType = map.getMapTypes();
			map.setMapType(gMapType[0]); /* [0] map [1] satellite [2] hybrid */
			
			map.addControl(new GLargeMapControl());
			map.addControl(new GMapTypeControl());
			map.addControl(new GOverviewMapControl());
			
			/* create map with octagons */
			reDrawMap(map);
			
			/* set different events for places*/
			var ml = GEvent.addListener(map, "moveend", function() {
				reDrawMap(map);
			});
			var zl = GEvent.addListener(map, "zoomend", function() {
				reDrawMap(map);
			});
			var zl = GEvent.addListener(map, "click", function() {
				map.enableScrollWheelZoom();
			});
			var zl = GEvent.addListener(map, "singlerightclick", function() {
				map.disableScrollWheelZoom();
			});
			
		} else {
			/*alert("Dieser Browser ist leider nicht mit Google Maps kompatibel.");*/
		}
		
	}
	
	function addPlace (map,placeData,icon) {
		/*alert("add place for "+placeData["town"]);*/
		var marker = new GMarker(new GLatLng(placeData["lat"],placeData["lon"]),{icon:icon});
		var mout = GEvent.addListener(marker, "mouseout", function() {
			/*marker.closeInfoWindow();*/
		});
		var cl = GEvent.addListener(marker, "click", function() {
			loadSelectedPlace(placeData["wobjectId"]);
			/*setSelectedPlace(placeData["wobjectId"]);*/
		});
		var mover = GEvent.addListener(marker, "mouseover", function() {
			var html = ""; /*check if location is a tuev hanse location, if yes use alternative title for tooltip (woplacesearch)*/
			if(placeData["iconDir"] == "tuevhanse")
			{
				html = "<div style='border:0px solid #0F69AE;'><span style='color:#FFFFFF;background-color:#0F69AE;padding:1px;'>&nbsp;"+thsc[selLang]+" in "+placeData["town"]+"&nbsp;</span><span style='width:12px; border:6px solid white;'></span><br/>"+placeData["street"]+"<br/>"+placeData["postcode"]+" "+placeData["town"]+"<br/>"+placeData["phone"]+"</div>";
			}
			else
			{
				html = "<div style='border:0px solid #0F69AE;'><span style='color:#FFFFFF;background-color:#0F69AE;padding:1px;'>&nbsp;"+tsc[selLang]+" in "+placeData["town"]+"&nbsp;</span><span style='width:12px; border:6px solid white;'></span><br/>"+placeData["street"]+"<br/>"+placeData["postcode"]+" "+placeData["town"]+"<br/>"+placeData["phone"]+"</div>";
			}
			marker.openInfoWindowHtml(html,noCloseOnClick=false); 
		});
		map.addOverlay(marker);
		return true;
	}
	
	function reDrawMap (map) {
		map.clearOverlays();
		var zoomLevel = map.getZoom();
		/*alert(zoomLevel);*/
		
		if (usedProtocol=="" || !usedProtocol) {
			usedProtocol = "http";
		}
		
		if (zoomLevel <= 4) {
			/*map.setCenter(map.getCenter(),4);*/
		}
		if (zoomLevel <= 7) {
			return false;
		}
		var bounds = map.getBounds();
		var southWest = bounds.getSouthWest();
		var northEast = bounds.getNorthEast();
		for (i=0;i<placeLayer.length;i++) {
			if ((placeLayer[i]["lon"] < southWest.lng() || placeLayer[i]["lon"] > northEast.lng()) || (placeLayer[i]["lat"] < southWest.lat() || placeLayer[i]["lat"] > northEast.lat())) {
				/* draw place only inside map*/
				/*alert("dont draw "+placeLayer[i]["postcode"]);*/
			} else {
				/*alert("draw "+placeLayer[i]["postcode"]);*/
				var baseIconPath = usedProtocol+"://www.tuev-sued.de/extras/styles/tuev_internet/images/gicon/";
				var iconPath = baseIconPath+placeLayer[i]["iconDir"];
				var icon = new GIcon();
				if (zoomLevel > 13) {
					icon.image = iconPath+"/large.png";
					icon.shadow = iconPath+"/large_shadow.png";
					icon.iconSize = new GSize(86, 73);
					icon.shadowSize = new GSize(86, 73);
					icon.iconAnchor = new GPoint(29, 73);
					icon.infoWindowAnchor = new GPoint(29,0);
					icon.transparent = baseIconPath+"/large_transparent.png";
				} else if (zoomLevel <= 13 && map.getZoom() > 10) {
					icon.image = iconPath+"/medium.png";
					icon.shadow = iconPath+"/medium_shadow.png";
					icon.iconSize = new GSize(65, 55);
					icon.shadowSize = new GSize(65, 55);
					icon.iconAnchor = new GPoint(22, 55);
					icon.infoWindowAnchor = new GPoint(21,0);
					icon.transparent = baseIconPath+"/medium_transparent.png";
				} else if (zoomLevel <= 10 && map.getZoom() > 8) {
					icon.image = iconPath+"/small.png";
					icon.shadow = iconPath+"/small_shadow.png";
					icon.iconSize = new GSize(43, 37);
					icon.shadowSize = new GSize(43, 37);
					icon.iconAnchor = new GPoint(15, 37);
					icon.infoWindowAnchor = new GPoint(15,0);
					icon.transparent = baseIconPath+"/small_transparent.png";
				} else {
					icon.image = iconPath+"/mini.png";
					icon.shadow = iconPath+"/mini_shadow.png";
					icon.iconSize = new GSize(32, 28);
					icon.shadowSize = new GSize(32, 28);
					icon.iconAnchor = new GPoint(11, 28);
					icon.infoWindowAnchor = new GPoint(11,0);
					icon.transparent = baseIconPath+"/mini_transparent.png";
				}
				addPlace(map,placeLayer[i],icon);
			}
		}
	}
	
	function loadSelectedPlace (wobjectId) {
		window.location.href = String(window.location).replace(/\?.*$/, "") + "?mode=mapclick&wobjectId="+wobjectId;
	}
	
	function redirectWobject (wobjectId) {
		window.location.href = String(window.location).replace(/\?.*$/, "") + "?op=redirectWobject&wobjectId="+wobjectId;
	}
	
	function setSelectedPlace (wobjectId) {
		var url = 'modulename=WOPlace&function=getCompanyAttributes&languageId=<tmpl_var session.page.languageId>&wobjectId='+ wobjectId;
		/*alert(url);*/
		var myAjax = new Ajax.Request(sAjaxGateway, {
				method: 'get', 
				parameters: url, 
				onComplete: showSelectedPlace
			}
			);
		return false;
	}
	
	function showSelectedPlace(originalResponse){
		var response = originalResponse.responseText;
		var placeData = eval(response);
		var place = placeData[0];
		document.getElementById('wopsAddress').innerHTML = place["htmlContent"];
		initializeMap(place["lat"],place["lon"],13,selLang);
		return true;
	}
	
	function googleRouting () {
		/*String(window.location).replace(/\#$/,"");
		window.location = String(window.location).replace(/\#.*$/, "") + "#routing";*/
		var from = document.getElementById('src').value;
		var to = document.getElementById('dest').value;
		openLocationRoute('googleRoutingLayer');
		document.getElementById('wopsRouting').innerHTML = ""; /* Route wird berechnet... */
		showLoadingBar();
		directionsPanel = document.getElementById("wopsRouting");
		directions = new GDirections(map, directionsPanel);
		directions.clear();
		var dl = GEvent.addListener(directions, "load", function() {
			hideLoadingBar();
			try {map.clearOverlays();}catch(ex){}
			GEvent.clearListeners(map);
			document.getElementById('wopsRoutingLinkDiv').style.visibility = "visible";
			document.getElementById('wopsRoutingLinkDiv').style.display = "block";
			document.getElementById('wopsRoutingLink').href = usedProtocol+"://maps.google.de/maps?f=d&saddr="+from+"&daddr="+to+"&hl=de&geocode=&mra=ls&sll=48.817603,11.866264&sspn=0.063524,0.181961&ie=UTF8&spn=0.031757,0.090981&z=14&pw=2";
		});
		var el = GEvent.addListener(directions,"error", function() {
			hideLoadingBar();
			document.getElementById('wopsRouting').innerHTML = "<b>"+routeError[selLang]+"</b><br/><br/>";
		});
		var geocoder = new GClientGeocoder();
		geocoder.getLatLng(from+", Deutschland",loadDirection);
		/*alert("from:"+from+" to:"+to);
		directions.load("from:"+from+" to:"+to);*/
	}
	
	var loadDirection = function(latLng){
		var waypoints = new Array();
		waypoints[0] = latLng;
		waypoints[1] = new GLatLng(document.getElementById('destLat').value,document.getElementById('destLon').value);
		/*alert(latLng.lat()+"/"+latLng.lng());
		alert(waypoints[1].lat()+"/"+waypoints[1].lng());*/
		directions.loadFromWaypoints(waypoints);
	}
	
	function checkEnter(e){
		var characterCode;
		if(e && e.which) { 
			e = e;
			characterCode = e.which;
		} else {
			e = event;
			characterCode = e.keyCode;
		}
		
		if (characterCode == 13) { 
			googleRouting();
			return false;
		} else {
			return true;
		}
	}
	
	function showLoadingBar () {
		var sInnerHTML = '<br/><br/><img src="/extras/styles/jobexchange/images/loading_tuev.gif" style="vertical-align: middle;"></br><br/><br/><br/>';
		document.getElementById('loadingRoute').innerHTML = sInnerHTML;
		document.getElementById('loadingRoute').style.display = "block";
		document.getElementById('loadingRoute').style.visibility = "visible";
	}
	
	function hideLoadingBar () {
		document.getElementById('loadingRoute').innerHTML = "";
		document.getElementById('loadingRoute').style.visibility = "hidden";
		document.getElementById('loadingRoute').style.display = "none";
	}
	
