WebAppDir = '/SADB';
CMSWebAppDir = '';
YellowPageEntryURL = '/branchenbuch/hamburg/eintrag/___SADB_ID___/';
POI_PATH = '';
MARKER_PATH = '' + '/images/icons';

var reloadAdsPreventHack = false;

PolyLine = new Class({
	initialize: function (map, points, fixed, optimize, color) {
	
		var isNew = (!points || (points.length == 0));
		if (null == points) points = [];
		this.fixed = false;
		this.map = map;
		this.isEdit = false;
		this.startLine(points,color?color:'red');
		GEvent.trigger(this.line,"lineupdated");
		if (optimize) this.setOptimizedView();
		this.fixed = !(fixed==false);
		if (!isNew || this.fixed) this.stopEdit()
		else this.line.enableDrawing();
		if (!this.fixed) {
			GEvent.addListener(this.map, "singlerightclick", this.removeLast.bind(this));
		}
	},
	setOptimizedView: function(result) {
		var len = this.line.getVertexCount() || 0;
		var minX = 0;
		var maxX = 0;
		var minY = 0;
		var maxY = 0;

		// get required view size
		for (var i=0; i < len; i++) {
		 	var point = this.line.getVertex(i);
		 	if (i==0) {
				minX = point.lng();
				maxX = point.lng();
				minY = point.lat();
				maxY = point.lat();
		 	} else {
				if (point.lng() < minX) minX = point.lng();
				if (point.lng() > maxX) maxX = point.lng();
				if (point.lat() < minY) minY = point.lat();
				if (point.lat() > maxY) maxY = point.lat();
		 	}
		}
		try {
			min = new GLatLng(minY,minX);
			max =  new GLatLng(maxY,maxX);
			var bounds = new GLatLngBounds(min,max);
			this.map.setCenter(bounds.getCenter(),this.map.getBoundsZoomLevel(bounds));
		} catch (e) {
		}
	},
	zoomIn: function () {
		this.map.zoomIn(this.map.getCenter(), false,false);
	},
	zoomOut: function () {
		this.map.zoomOut(this.map.getCenter(), false);
	},
	wheelZoom: function (a) {
		if (a.cancelable) a.preventDefault();
        if (a.detail || -a.wheelDelta) {
			var latlng = new GLatLng(this.mouselat,this.mouselng);
			if ((a.detail || -a.wheelDelta) < 0)
				this.map.zoomIn(latlng, false,false);
			else if ((a.detail || -a.wheelDelta) > 0)
				this.map.zoomOut(latlng, false);
        }
        return false;
	},
	transformCoords: function(x,y) {
		new Ajax(
			WebAppDir + '/LDAPProcessor?cmd=de.redero.ldap.sadb.cmd.SADBAjaxGeoTransformCommand' + 
			'&x=' + x + 
			'&y=' + y
			,
			{	
				method: 'get',
				requestHeaders: {Accept: 'application/json'},
				async: false,
				onSuccess: this.setValues
			}
		).request();
	},
	setValues: function(transport) {
		coords = Json.evaluate('(' + transport.responseText + ')');
		if ($('wgs84')) {
			$('wgs84').innerHTML += coords.wgs84_x + ',' + coords.wgs84_y + ';\n';
			$('gk3').innerHTML += coords.gk3_x + ',' + coords.gk3_y + '\n';
			$('gk4').innerHTML += coords.gk4_x + ',' + coords.gk4_y + '\n';
		}
	},
	newLine: function(pnts) {
        if (this.fixed) return;
		if (!pnts) pnts = [];
		if ($('wgs84')) {
			$('wgs84').innerHTML = '';
			$('gk3').innerHTML = '';
			$('gk4').innerHTML = '';
			$('length').innerHTML = '';
		}
		this.map.clearOverlays();
		this.startLine(pnts,'red');
        this.line.enableDrawing();
	},
	removeLast: function() {
        if (this.fixed) return;
		if (this.line && this.isEdit) {
			var len = this.line.getVertexCount() || 0;
			var pnts = [];
			for (i=0; i < len-1; i++) {
			 	pnts.push(this.line.getVertex(i));
			}
			this.newLine(pnts);
			GEvent.trigger(this.line,"lineupdated");
		}					
	},
	startDrawing: function(color) {
          if (this.fixed) return;
		  this.map.addOverlay(this.line);
		  this.line.enableEditing({onEvent: "mouseover"});
		  this.line.disableEditing({onEvent: "mouseout"});
		  this.isEdit=true;
		  GEvent.addListener(this.line, "lineupdated", 
			(function() {
				if ($('wgs84')) {
			    	$('wgs84').innerHTML = '';
			 		$('gk3').innerHTML = '';
			 		$('gk4').innerHTML = '';
				    $('length').innerHTML = (Math.round(this.line.getLength() / 100) / 10) + "&nbsp;km";
			 		var len = this.line.getVertexCount()||0;
			 		for(var i=0; i<len; i++){
			 			var point = this.line.getVertex(i);
			 			this.transformCoords(point.lng().toFixed(6), point.lat().toFixed(6));
			 		}
				}
			  }).bind(this)
		  );
		  GEvent.addListener(this.line, "endline",
		  	(function() {
		    	GEvent.addListener(this.line, "click", function(latlng, index) {
			      if ((typeof index == "number") && (this.line)) {
			    	  this.line.deleteVertex(index);
			      }
		    	});
		    	this.isEdit=false;
		 	}).bind(this)
		 );
	},
    startLine: function(pnts, color) {
        if (this.fixed) return;
        if (this.line) {
              this.line.disableEditing();
              this.line.hide();
        }
        var opacity=0.5;
        var thickness=4;
        if (color=='transparent') {
              opacity=0;
        }
        this.line = new GPolyline(pnts, color, thickness, opacity);
        this.startDrawing(color);
	}, 
	editLine: function() {
          if (this.fixed) return;
		  if (this.line) {
		  	this.line.enableEditing();
		  	this.line.enableDrawing();
		  	this.isEdit=true;
		  }
	},
	stopEdit: function() {
		  if (this.line) {
		  	this.line.disableEditing();
		  	this.line.disableEditing({onEvent: "mouseover"});
		  	this.isEdit=false;
		  }
	}
});

EmbeddedLocalSearch = new Class ({
	initialize: function(mapControler) {
		this.mapControler = mapControler;
		this.optimizeView=true;
		this.result = null;
		this.routeID = null;
		this.maxLayerDistance = -1;
		this.listeners = new Array();
		this.cAddressText = null;
	},
	registerEvents: function() {
		this.listeners.push(GEvent.addListener(this.mapControler.map,'moveend', function() {
			try {simulatePI();} catch (e) {}
			try {if (reloadAdsPreventHack) simulateAI();} catch (e) {}
		}));
		
		this.listeners.push(GEvent.addListener(this.mapControler.map,'maptypechanged', function() {
			try {simulatePI();} catch (e) {}
			try {if (reloadAdsPreventHack) simulateAI();} catch (e) {}
		}));
		
		this.listeners.push(GEvent.addListener(this.mapControler.app,'poilist_change', function() {
			try {simulatePI();} catch (e) {}
			try {if (reloadAdsPreventHack) simulateAI();} catch (e) {}
		}));
		
		this.listeners.push(GEvent.addListener(this.mapControler.app,'useraction', function() {
			try {simulatePI();} catch (e) {}
			if (!window.ie7 && !window.ie6) {
				try {if (reloadAdsPreventHack) simulateAI();} catch (e) {}
			}
		}));
	},
	deregisterEvents: function() {
		for(i=this.listeners.length-1;i >= 0; i--) {
			GEvent.removeListener(this.listeners[i]);
			this.listeners.pop(i);
		}
	},
	search: function(address,addressText,optimizeView) {
		this.cAddressText = addressText;
		this.optimizeView=(optimizeView || (optimizeView==null));
		requestURL = WebAppDir + '/proxy.jsp?call=1&allowdistrict=false' +
			'&streetaddress=' + encodeURIComponent(address).replace(/\+/g,'%20') + 
			'&cs=wgs84';
		
		if (this.requestURL != requestURL) {
			this.requestURL = requestURL;
			new Ajax(
				this.requestURL,
				{
					method: 'get',
					headers: ['Accept','text/json','If-Modified-Since', 'Sat, 1 Jan 2000 00:00:00 GMT'],
					async: true,
					onSuccess: (function (transport) {
						this.handleQueryResult(transport)
					}).bind(this)
				}
			).request();
		}
		return false;
	},
	list: function(ids, postListHandling) {

		if (null != postListHandling) this.plh = postListHandling
		if (ids && (ids.length > 0)) {
			var requestURL = WebAppDir + '/proxy.jsp?call=4' +
				'&from=0' + 
				'&hitsperpage=-1' + 
				'&ids=' + encodeURIComponent(ids) + 
				'&cs=wgs84';

			new Ajax(
				requestURL,
				{
					method: 'get',
					headers: ['Accept','text/json','If-Modified-Since', 'Sat, 1 Jan 2000 00:00:00 GMT'],
					async: true,
					onSuccess: (function (transport) {
						this.handleListResult(transport)
						if (this.plh) this.plh();
					}).bind(this)
				}
			).request();
			GEvent.trigger(this.mapControler.app,'useraction');
		}
	},
	handleQueryResult: function(transport) {
		this.deregisterEvents();
		try {
			var result = Json.evaluate('(' + transport.replace(/[^[\x0A\0xD\x20-\xFF]/g,"") + ')');
			if (result.address) {
				this.mapControler.setCurrentPosition(result.address, this.cAddressText);
				this.mapControler.centerMap(this.mapControler.app.CurPosMarker.getLatLng());
			}
			this.result = result;
		} catch (ex) {
		}
		this.registerEvents();
		GEvent.trigger(this,'searchsubmit',this);
	},
	handleListResult: function(transport) {
		this.deregisterEvents();
		try {
			var result = Json.evaluate('(' + transport.replace(/[^[\x0A\0xD\x20-\xFF]/g,"") + ')');
			this.mapControler.setResultMarkers(result,this.optimizeView);
			if (result.routes != null) {
				for (var i=0;i<result.routes.length; i++) {
					for (var j=0; j < result.routes[i].vertex.length; j++) {
						result.routes[i].vertex[j] = new GLatLng(result.routes[i].vertex[j][1], result.routes[i].vertex[j][0]);
					}
					new PolyLine(this.mapControler.map, result.routes[i].vertex, true, this.optimizeView, this.mapControler.routeColor);
				}
			}
			this.optimizeView=true;
			this.result = result;
		} catch (ex) {
		}
		this.registerEvents();
		GEvent.trigger(this,'searchsubmit',this);
	},
	setRoute: function (id, maxLayerDistance, color) {
		this.mapControler.setRoute(id, maxLayerDistance, color)
	},
	hasRoute: function () {
		return null != this.mapControler.routeID;
	}
});

LayerContainer = new Class({
	initialize: function(mapControler) {
		this.layers = new Array();
		this.mapControler = mapControler;
		this.layerBounds = this.mapControler.map.getBounds();
		GEvent.addListener(this.mapControler.map,'moveend',this.refreshAll.bind(this));
		GEvent.addListener(this.mapControler.map,'zoomend',this.refreshAll.bind(this));
	},
	loadLayer: function(layerID) {
		var size = this.mapControler.map.getSize();
		
		var sw = this.mapControler.map.fromContainerPixelToLatLng(
			new GPoint(
				0 - size.width * LayerContainer.PRELOAD_FACTOR,
				size.height * LayerContainer.PRELOAD_FACTOR
			)
		);
		var ne = this.mapControler.map.fromContainerPixelToLatLng(
			new GPoint(
				size.width * LayerContainer.PRELOAD_FACTOR,
				0 - size.height * LayerContainer.PRELOAD_FACTOR
			)
		);
		this.layerBounds = new GLatLngBounds(sw,ne);
		var url = WebAppDir + '/proxy.jsp?call=2&layer=' + layerID +
			'&ll=' + this.layerBounds.getSouthWest().lng() + ',' +  this.layerBounds.getSouthWest().lat() +
			'&ur=' + this.layerBounds.getNorthEast().lng() + ',' +  this.layerBounds.getNorthEast().lat() + 
			'&cs=wgs84';
		if (mapControler.routeID) {
			url += '&r=' + mapControler.routeID + "&d=" + mapControler.maxLayerDistance
		}
		new Ajax (
             url,	
			 {
				method: 'get',
				headers: ['Accept','text/json','If-Modified-Since', 'Sat, 1 Jan 2000 00:00:00 GMT'],
				async: true,
				onSuccess: this.addLayer.bind(this)
			 }
		).request();
	},
	addLayer: function(transport) {
		var jsonResponse = Json.evaluate('(' + transport.replace(/[^[\x0A\0xD\x20-\xFF]/g,"") + ')');

		var pois = jsonResponse.pois;
		var id = jsonResponse.id;

		this.removeLayer(id);

		var layer = new MarkerManager(this.mapControler.map);
		Object.extend({isvalid: true, isactive: true, id: id },layer);
		layer.id = id;
		layer.isvalid = true;
		layer.isactive = true;

		var markers = new Array();
		var unlimitedZoom = false;
		if (jsonResponse.pois && (jsonResponse.pois.length > 0)) {
			for (i=0; i < pois.length; i++) {
				var poiIcon = new GIcon();
				unlimitedZoom = unlimitedZoom || pois[i].unlimitedZoom;
				if ((!unlimitedZoom && (this.mapControler.map.getZoom() < LayerContainer.VISIBILITY_MAX_ZOOM))
					||
					(unlimitedZoom && (this.mapControler.map.getZoom() < LayerContainer.VISIBILITY_UNLIMITED_ZOOM))
				) {
					layer.isvalid = false;
					layer.isactive = false;
					markers = new Array();
					i = pois.length;
				} else {
					poiIcon.image = POI_PATH + pois[i].icon;
					poiIcon.iconSize = new GSize(pois[i].iconHeight,pois[i].iconWidth);
					poiIcon.iconAnchor = new GPoint(pois[i].iconOffsetX,pois[i].iconOffsetY);
					poiIcon.infoWindowAnchor = new GPoint(pois[i].bubbleOffsetX,pois[i].bubbleOffsetY);
					var marker = new GMarker(new GLatLng(pois[i].gcY, pois[i].gcX), { icon: poiIcon, draggable: false, title: pois[i].name });
					marker.bindInfoWindow(this.mapControler.getInfoWindowHtml(pois[i]));
					GEvent.addListener(marker,'infowindowopen', (function(hit) {
						this.hitInInfoWindow = hit;
					}).bind(this.mapControler,pois[i]));
					markers.push(marker);
				}
			}
		}
		if (unlimitedZoom) {
			layer.addMarkers(markers,LayerContainer.VISIBILITY_UNLIMITED_ZOOM);
			if (markers.length > 0) {
				uLayer = new Array(markers[Math.floor(markers.length/2)]);
				layer.addMarkers(uLayer,0);
			}
			layer.maxZoom = LayerContainer.VISIBILITY_UNLIMITED_ZOOM;
		} else {
			layer.addMarkers(markers,LayerContainer.VISIBILITY_MAX_ZOOM);
			layer.maxZoom = LayerContainer.VISIBILITY_MAX_ZOOM;
		}
		this.layers.push(layer);
		if (layer.isvalid) this.showLayer(id);
	},
	getLayer: function(id) {
		for (i=0;i < this.layers.length; i++) {
			if (this.layers[i].id == id) 
				return this.layers[i];
		}
		return null;
	},
	refreshAll: function() {
		var currentBounds = this.layerBounds; 
		for (i=0;i < this.layers.length; i++) {
			var layer = this.layers[i];
			if (!currentBounds.containsBounds(this.mapControler.map.getBounds())) {
				layer.isvalid = false;
				this.refreshLayer(layer.id);
			} else if (!layer.isvalid && !layer.isactive) {
				this.refreshLayer(layer.id);
			}
		}
	},
	refreshLayer: function(id) {
		var layer = this.getLayer(id);
		if (layer) {
			if (((layer.maxZoom != LayerContainer.VISIBILITY_UNLIMITED_ZOOM) && (this.mapControler.map.getZoom() < LayerContainer.VISIBILITY_MAX_ZOOM)) ||
				((layer.maxZoom == LayerContainer.VISIBILITY_UNLIMITED_ZOOM) && (this.mapControler.map.getZoom() < LayerContainer.VISIBILITY_UNLIMITED_ZOOM))) {
				this.hideLayer(layer.id);
				
			} else if (!layer.isvalid || !layer.isactive) {
				this.loadLayer(layer.id);
			}
			else {
				this.showLayer(layer.id);
			}
		}
	},
	showLayer: function(id) {
		var layer = this.getLayer(id);
		if (layer) {
			if (((layer.maxZoom != LayerContainer.VISIBILITY_UNLIMITED_ZOOM) && (this.mapControler.map.getZoom() >= LayerContainer.VISIBILITY_MAX_ZOOM)) ||
				((layer.maxZoom == LayerContainer.VISIBILITY_UNLIMITED_ZOOM) && (this.mapControler.map.getZoom() >= LayerContainer.VISIBILITY_UNLIMITED_ZOOM))) {
				layer.refresh();
				layer.isactive = true;
	            GEvent.trigger(this.mapControler.app,'poilist_show',id);
			}
		} else this.loadLayer(id);
	},
	hideLayer: function(id) {
		var layer = this.getLayer(id);
		if (layer) {
			layer.clearMarkers();
			layer.refresh();
			layer.isactive=false;
		}
	},
	setVisible: function(id, visible) {
		if (visible) {
			if (this.mapControler.map.getZoom() < LayerContainer.VISIBILITY_MAX_ZOOM) {
				this.mapControler.map.setCenter(this.mapControler.map.getCenter(),LayerContainer.VISIBILITY_MAX_ZOOM);
			}
			this.showLayer(id);
		}
		else this.removeLayer(id);
        GEvent.trigger(this.mapControler.app,'poilist_change',id);
	},
	hasVisibleLayers: function() {
		for (i=0;i < this.layers.length; i++) {
			if (this.layers[i].isactive) 
				return true;
		}
		return false;
	},
	removeAllLayers: function() {
		for (i=0;i < this.layers.length; i++)
			this.removeLayer(this.layers[i].id);
	},
	removeLayer: function(id) {
		for (i=0;i < this.layers.length; i++) {
			if (this.layers[i].id == id) {
				this.layers[i].clearMarkers();
				this.layers[i].refresh();
				this.layers.splice(i,1);
	            GEvent.trigger(this.mapControler.app,'poilist_hide',id);
				return;
			}
		}
	}
});
LayerContainer.VISIBILITY_MIN_ZOOM = 17;
LayerContainer.VISIBILITY_MAX_ZOOM = 13;
LayerContainer.VISIBILITY_UNLIMITED_ZOOM = 9;
LayerContainer.PRELOAD_FACTOR = 1.3;


LocalSearchMapControler = new Class({
	initialize: function(mapApplication) {
		this.app = mapApplication;
		this.map = mapApplication.map;
		this.searchResultLayer = new MarkerManager(this.map);
		this.resultDisplayed = false;
		this.isAddressChanged = false;
		this.poiLayers = new LayerContainer(this);
		this.mapCenter = this.map.getCenter();
	},
	refreshLayers: function() {
		this.poiLayers.refreshAll();
	},
	focusHit: function (hitNo) {
		try {
			hitMarker = this.searchResultLayer.findMarkerById('hit_' + hitNo);
			if (hitMarker) {
				this.map.setCenter(hitMarker.position);
				hitMarker.showInfoWindow();
			}
		} catch (e) {
		} 
		GEvent.trigger(this.app,'useraction',this);
	},
	centerHome: function() {
		this.map.setCenter(this.mapCenter,LocalSearchMapControler.POSITION_ONLY_ZOOM);
		this.refreshLayers();
		GEvent.trigger(this.app,'useraction',this);
	},
	centerMap: function(position) {
		if (!position) position = new GLatLng(this.app.DefaultMapCenter.x, this.app.DefaultMapCenter.y);
		this.map.setCenter(position);
		this.refreshLayers();
		this.mapCenter = position;
	},
	setCurrentPosition: function(address, addressText) {
		this.isAddressChanged=false;
		if (this.app.CurPosMarker) this.map.removeOverlay(this.app.CurPosMarker);
		if (address || this.app.CurPosMarker) {
			if (address && this.app.CurPosMarker) {
				if ((address.gcY != this.app.CurPosMarker.getLatLng().lat()) ||
					(address.gcX != this.app.CurPosMarker.getLatLng().lng()))
						this.isAddressChanged = true;
			} else this.isAddressChanged = true;
		} else this.isAddressChanged = true;
		if (address) {
			var position = new GLatLng(address.gcY, address.gcX);
			this.centerIcon = new GIcon();
			this.centerIcon.image = MARKER_PATH + "/standort_1_schatten.png";
			this.centerIcon.iconSize = new GSize(41,55);
			this.centerIcon.iconAnchor = new GPoint(5,50);
			this.centerIcon.infoWindowAnchor = new GPoint(30,15);
			if (!addressText) addressText = 'Ihr Standort'; 
			var toolTip = addressText + ': ' + address.name;
			this.app.CurPosMarker = new GMarker(position, { icon: this.centerIcon, draggable: false, title: toolTip });
			var bubbleHtml = '<span><strong>' + addressText + '</strong><br/>' + address.name + '</span>';
			this.app.CurPosMarker.bindInfoWindow(bubbleHtml);
			this.map.addOverlay(this.app.CurPosMarker);
			this.mapCenter = position;
			
			if ($('position')) {
				GEvent.addDomListener($('position'),'click',
					this.app.CurPosMarker.openInfoWindow.bind(
						this.app.CurPosMarker,
						bubbleHtml
					)
				);
			}
		} else this.app.CurPosMarker = null;
	},
    setRoute: function (id, maxLayerDistance, color) {
        this.routeID = id;
        this.maxLayerDistance = maxLayerDistance;
        if (color && (0 != color.indexOf('#')) && (color != 'transparent')) {
                color = '#' + color
        }
        this.routeColor = color;
	},
	setResultMarkers: function (result, optimizeView) {
		this.setCurrentPosition(result.address);
		if (!result.hits && optimizeView) this.centerHome();

		if (result.hits) {
			for (i=0; i < result.hits.length; i++) {
				this.addResultMarker(result.hits[i]);
			}
			this.searchResultLayer.refresh();
			this.resultDisplayed = true;
			if (optimizeView) this.setOptimizedView(result);
		}
		if (this.isAddressChanged && this.app.CurPosMarker) GEvent.trigger($('position'),'click');
	},
	clearResult: function() {
		this.searchResultLayer.clearMarkers();
		this.resultDisplayed = false;
	},
	addResultMarker: function (hit){
		if (hit.gcX && hit.gcY && (hit.gcX > 0) && (hit.gcY > 0) ) {
			var iconID = hit.hitNo;
			var position = new GLatLng(hit.gcY,hit.gcX);
			var hitIcon = new GIcon();
			if (hit.customerType > 0) 
				hitIcon.image = MARKER_PATH + '/nadel_blau_' + iconID + '.png';
			else
			hitIcon.image = MARKER_PATH + '/nadel_orange_' + iconID + '.png';
			hitIcon.shadow = MARKER_PATH + '/nadel_schatten.png';
					hitIcon.shadowSize = new GSize(46,44);
			hitIcon.iconSize = new GSize(22,44);
			hitIcon.iconAnchor = new GPoint(11,44);
			hitIcon.infoWindowAnchor = new GPoint(15,15);
			var marker = new GMarker(position, { icon: hitIcon, draggable: false, title: hit.name });
			var bubbleHtml = this.getInfoWindowHtml(hit);
			marker.bindInfoWindow(bubbleHtml);
			
			GEvent.addListener(marker,'infowindowopen', (function(hit) {
				this.hitInInfoWindow = hit;
			}).bind(this,hit));
			
			if ($('hit_' + hit.hitNo)) {
				GEvent.addDomListener($('hit_' + hit.hitNo),'click', 
						(function() {
							marker.openInfoWindow(
									bubbleHtml
							)
						}).bind(this)
				);
			}
			this.searchResultLayer.addMarker(marker,LocalSearchMapControler.RESULT_MAX_ZOOM);
		}
	},
	getInfoWindowHtml: function (hit) {
		var trefferIcon = "images/treffer_info_icon.gif";
		html = '<h3 style="border: none"><div style="width: 250px; margin-right: 1em; line-height: 1.2em">' + hit.name + '</div></h3>';
		html += '<div class="pl_blau80_o m_o03" style="width: 360px">';
		if (hit.logo && (hit.logo.length > 0)) {
			if (hit.logolink && (hit.logolink.length > 0)) {
				html += '<a href="' + hit.logolink + '" rel="nofollow">';
			}
			html += '<img src="' + hit.logo + '&width=150&height=150&keepRatio=true" alt="' + hit.name + '" class="noborder float_right m_140">'
			if (hit.logolink && (hit.logolink.length > 0)) {
				html += '</a>';
			}
		}
		html += '<p class="m_o03">'
		html += hit.street + '&nbsp;' + hit.streetNo + '<br/>';
		if (hit.locationInfo && (hit.locationInfo.length > 0)) {
			html += hit.locationInfo + '<br/>';
		}
		html += hit.zip + ' ' + hit.city + '<br/>';
        if ((hit.bookinglink==null) || (hit.bookinglink.length == 0)) {
			if (hit.phone && (hit.phone.length > 0))
				html += '<br/>' + hit.phone;
		} else {
			html += '<br/><a href="' + hit.bookinglink + '" target="_blank">&Uuml;bernachtungen buchen</a>';
		}
		html += '</p>';
        if ((hit.bookinglink==null) || (hit.bookinglink.length == 0)) {
			if (hit.mail && (hit.mail.length > 0))
				 html += 'E-Mail: <a href="mailto:' + hit.mail + '">' + hit.mail + '</a><br/>';
			if (hit.homepage && (hit.homepage.length > 0) && (hit.homepage != hit.detailsLink)) {
				 if (hit.homepage.indexOf("http") != 0) hit.homepage = "http://" + hit.homepage;
				 html += '<a title="Homepage" href="#" onclick=window.open("' + hit.homepage + '","hitdetails","height=600,width=600,resizable=yes,scrollbars=yes,status=no,toolbar=yes,location=yes,menubar=yes").focus()>' + (hit.homepageLabel.length>0?hit.homepageLabel:'Homepage von ' + hit.name) + '</a><br/>';
			}
		}
		if (hit.id)
			html += '<a href="' + YellowPageEntryURL.replace(/___SADB_ID___/,hit.id) + '" title="Eintragsdetails anzeigen">Eintragsdetails anzeigen</a><br/>';
		if (favControler && favControler.isLoggedIn())
			html += '<div id="favAnchor"><a title="Zu Lieblingsliste hinzuf&uuml;gen" href="javascript:void(0);" onclick="favControler.displayWindow($(\'favAnchor\'))">Zu Lieblingsliste hinzuf&uuml;gen</a></div>';
		html += '</div>';
		return html;
	},
	setOptimizedView: function(result) {
		if (!(result.hasHits || result.address)) return;

		var hasCenter = result.address && result.address.gcX && (result.address.gcX > 0) && result.address.gcY && (result.address.gcY > 0);

		// get required view size
		var minX = hasCenter?result.address.gcX:Number.MAX_VALUE;
		var maxX = hasCenter?result.address.gcX:0;
		var minY = hasCenter?result.address.gcY:Number.MAX_VALUE;
		var maxY = hasCenter?result.address.gcY:0;
		if (result.hasHits) {
			for (i=0; i < result.hits.length; i++) {
				if (result.hits[i].gcX && result.hits[i].gcX && (result.hits[i].gcX > 0) && (result.hits[i].gcY > 0)) {
					if (result.hits[i].gcX < minX) minX = result.hits[i].gcX;
					if (result.hits[i].gcX > maxX) maxX = result.hits[i].gcX;
					if (result.hits[i].gcY < minY) minY = result.hits[i].gcY;
					if (result.hits[i].gcY > maxY) maxY = result.hits[i].gcY;
				}
			}
		}

		if ((minX == Number.MAX_VALUE) || (maxX == 0) || (minY == Number.MAX_VALUE) || (maxY == 0)) return;
		
		try {
			min = this.map.fromLatLngToContainerPixel(new GLatLng(minY,minX));
			max =  this.map.fromLatLngToContainerPixel(new GLatLng(maxY,maxX));
			var bounds=null;
			if ((min.x > 0) && (min.y > 0) && (max.x > 0) && (max.y > 0)) { 
				min.x = min.x*.95;min.y = min.y*1.05;
				max.x = max.x*1.05;max.y = max.y*.75;
				bounds = new GLatLngBounds(this.map.fromContainerPixelToLatLng(min),this.map.fromContainerPixelToLatLng(max));
			} else {
            	bounds = new GLatLngBounds(new GLatLng(minY,minX),new GLatLng(maxY,maxX));
            }
			var zl = this.map.getBoundsZoomLevel(bounds ,this.map.getSize());
			this.map.setCenter(bounds.getCenter(),zl);
			this.mapCenter = bounds.getCenter();
		} catch (e) {
		}
	}
});
LocalSearchMapControler.DEFAULT_ZOOM = 14;
LocalSearchMapControler.RESULT_MIN_ZOOM = 17;
LocalSearchMapControler.RESULT_MAX_ZOOM = 9;
LocalSearchMapControler.POSITION_ONLY_ZOOM = 16;

LayerList = new Class({
	initialize: function(container, layerList) {
		if (!container || !layerList || (layerList.length == 0)) return;
		for (var i=0; i < layerList.length; i++) {
			if (!layerList[i].layerIsHidden) this.addLayer(container, layerList[i]);
		}
	},
	addLayer: function (container, layer) {
		var li = new Element('li');
		var checkbox = new Element('input');
		checkbox.id = layer.layerId;
		checkbox.name = layer.layerId;
		checkbox.type = 'checkbox';
		checkbox.injectInside(li);
		var label = new Element('label');
		label.setProperty('for',layer.layerId);
		label.setStyle('display','inline');
		label.setHTML('&nbsp;' + layer.layerName);
		label.injectInside(li);
		li.injectInside(container);
		checkbox.checked = layer.layerIsSelected
		if (window.ie) {
			checkbox.onclick = function () {
				mapControler.poiLayers.setVisible(layer.layerId,$(layer.layerId).checked)
			}
		} else {
			checkbox.onchange = function () {
				mapControler.poiLayers.setVisible(layer.layerId,$(layer.layerId).checked)
			}
		}
	}
});
	

GMapApp = new Class({
	initialize: function(mapElem, size, options) {
		this.map = new GMap2($(mapElem), { size: size });
		this.DefaultMapCenter = new GLatLng(GMapApp.DefaultMapCenterX,GMapApp.DefaultMapCenterY);
		if (options.center) this.mapCenter = options.center;
		else this.mapCenter = this.DefaultMapCenter;
		var zoom = LocalSearchMapControler.DEFAULT_ZOOM;
		if (options.zoom) zoom = options.zoom;
		this.map.setCenter(this.mapCenter,zoom);
		this.CurPosMarker = new GMarker(this.mapCenter);
	}
});
GMapApp.DefaultMapCenterX = 53.55052821972251;
GMapApp.DefaultMapCenterY = 9.992684353061003;

FavListCategory = new Class ({
	initialize: function(internalName,name) {
		this.internalName=internalName;
		this.name=name;
	}
});

FavList = new Class ({
		initialize: function(uuid,name,category, description) {
			this.uuid=uuid;
			this.name=name;
			this.category=category;
			this.description=description;
		},
		display: function (container) {
		}
	});
FavList.DEFAULT_NAME='Neue Lieblingsliste';
FavList.DEFAULT_DESCRIPTION='Dies ist meine Lieblingsliste';
	
	
FavListControler = new Class ({
	initialize: function() {
		this.lists = null;
		this.categories = null;
		this.favListWindow = null;
		this.cContainer = null;
		this.getLists();	  		
		new Ajax(
			FavListControler.URL_CATEGORIES,
			{
				method: 'get',
				headers: ['Accept','text/json','If-Modified-Since', 'Sat, 1 Jan 2000 00:00:00 GMT'],
				async: true,
				onSuccess: this.handleCategoryResult.bind(this),
				onError: ( function () {
					this.categories = null;
				}).bind(this)
			}
		).request();
		GEvent.addListener(mapControler.map,'infowindowclose',this.closeWindow.bind(this));
	},
	getLists: function() {
		new Ajax(
			FavListControler.URL_LISTS,
			{
				method: 'get',
				headers: ['Accept','text/json','If-Modified-Since', 'Sat, 1 Jan 2000 00:00:00 GMT'],
				async: true,
				onSuccess: this.handleListResult.bind(this),
				onError: ( function () {
					this.lists = null;
				}).bind(this)
			}
		).request();
	},
	isLoggedIn: function() {
		return (this.categories && (this.categories.length > 0));
	},
	handleListResult: function (transport) {
		try {
			var result = Json.evaluate('(' + transport.replace(/[^[\x0A\0xD\x20-\xFF]/g,"") + ')');
			this.lists = new Array();
			for(var i=0; i < result.length; i++) {
				this.lists.push(new FavList(result[i].uuid,result[i].name,result[i].category,result[i].description));
			}
		} catch (e) {
			this.lists = null;
		}
	},
	handleCategoryResult: function (transport) {
		try {
			var result = Json.evaluate('(' + transport.replace(/[^[\x0A\0xD\x20-\xFF]/g,"") + ')');
			this.categories = new Array();
			for(var i=0; i < result.length; i++) {
				this.categories.push(new FavListCategory(result[i].categoryInternalName,result[i].name));
			}
		} catch (e) {
			this.categories = null;
		}
	},
	addToList: function(sadbid, listid, listname, listcategory) {
		if (null != sadbid) {
			var createURL = FavListControler.URL_STORE + '&locationId=' + sadbid;
			if (null != listid) {
				createURL += '&listId=' + listid; 
				createURL += '&createList=false'; 
			} else {
				createURL += '&createList=true'; 
				if (null != listname) createURL += '&listName=' + listname; 
				else createURL += '&listName=' + FavList.DEFAULT_NAME;
				if (null != listcategory) createURL += '&listCategory=' + listcategory; 
				else createURL += '&listCategory=' + FavList.CATEGORY;
			}
			new Ajax(
				createURL,
				{
					method: 'get',
					headers: ['Accept','text/json','If-Modified-Since', 'Sat, 1 Jan 2000 00:00:00 GMT'],
					async: true,
					onSuccess: this.handleListResult.bind(this),
					onError: ( function () {
						this.lists = null;
					}).bind(this)
				}
			).request();
			var html = '<div style="font-style: italic; color: #3D3D3D">Eintrag wurde zur Lieblingsliste hinzugef&uuml;gt</div>';
			this.cContainer.setHTML(html);
			this.closeWindow();
			this.getLists();	  		
		}
	},
	displayWindow: function(container) {
		if (container && this.isLoggedIn()) {
	  		if (!this.favListWindow) {
				this.favListWindow = new Element("div");
				this.favListWindow.setAttribute('id', 'favLists');
				this.favListWindow.setAttribute('class', 'favlistDiv');
				this.favListWindow.style.visibility = "hidden";
				this.favListWindow.style.display = "none";
				this.favListWindow.injectInside(document.body);
			}	

				var coords = container.getCoordinates();
			this.favListWindow.setStyle('position','absolute');
			this.favListWindow.setStyle('left',coords.left);
			this.favListWindow.setStyle('width',coords.width);
			this.favListWindow.setStyle('padding','0.3em');
			this.favListWindow.setStyle('background-color','#E7EEF3');
			this.favListWindow.setStyle('border-style','solid');
			this.favListWindow.setStyle('border-color','#105D8D');
			this.favListWindow.setStyle('border-width','1px');
			this.favListWindow.setStyle('top',coords.top + coords.height -1);
			this.favListWindow.style.visibility = "visible";
			this.favListWindow.style.width = coords.width;
			this.favListWindow.style.display = "block";
			this.favListWindow.style.zIndex = 10000;
			
			var html='<img src="http://maps.google.de/intl/de_de/mapfiles/iw_close.gif" alt="Schliessen" title="Schlie&szlig;en" style="float: right" onclick="favControler.closeWindow()"/>'
			for(var i=0;i<this.lists.length;i++) {
				if (i==0) html+= '<strong>Eintrag einer bestehenden Lieblingsliste hinzuf&uuml;gen:</strong><br/><ul style="list-style-type: none">';
				html += '<li><a href="javascript:void(0)" onclick="favControler.addToList(\'' + mapControler.hitInInfoWindow.id + '\',\'' + this.lists[i].uuid + '\',\'' + this.lists[i].name + '\',\'' + this.lists[i].listCategory + '\')" title="' + this.lists[i].description + '">' + this.lists[i].name + '</a></li>';
				if (i==this.lists.length-1) html+= '</ul>';
			}
			html += '<strong>Neue Lieblingsliste anlegen:</strong><br/>';
			html += '<div style="float: left; width: 80px; margin-top: .3em; padding: 0;">';
			html += '<label for="favListName">Listenname</label>';
			html += '</div>';
			html += '<div style="float: left; margin-top: .3em; margin-left: 0px; padding: 0;">';
			html += '<input id="favListName" type="text" value="' + FavList.DEFAULT_NAME + '" style="width: 14em" title="Name der neuen Lieblingsliste eingeben"/>';
			html += '</div>';
			html += '<div style="clear: both"></div>';
			html += '<div style="float: left;width: 80px; margin-top: .3em; padding: 0;">';
			html += '<label for="favListCategory">Kategorie</label>';
			html += '</div>';
			html += '<div style="float: left; margin-top: .3em; margin-left: 0px; padding: 0;">';
			html += '<select id="favListCategory" style="width: 14.5em" title="Kategorie der neuen Lieblingsliste ausw&auml;hlen">';
			for(var i=0;this.categories && i<this.categories.length;i++) {
				html += '<option value="' + this.categories[i].internalName + '">' + this.categories[i].name + '</option>';
			}
			html += '</select>';
			html += '</div>';
			html += '<div style="clear: both"></div>';
			html += '<div style="float: left; margin-top: .3em; margin-left: 0px; padding-left: 80px; margin-bottom: .3em;">'
			html += '<input style="margin-right: .3em;" type="button" value="Hinzuf&uuml;gen" title="Eintrag der neuen Lieblingsliste hinzuf&uuml;gen" onclick="favControler.addToList(\'' + mapControler.hitInInfoWindow.id + '\',null,$(\'favListName\').value,$(\'favListCategory\').value,\'' + FavList.DEFAULT_DESCRIPTION + '\')"/>';
			html += '<input style="margin-right: .3em;" type="button" value="Abbrechen" title="Abbrechen" onclick="favControler.closeWindow()"/>';
			html += '</div>';
			html += '<div style="clear: both"></div>';
			this.favListWindow.setHTML(html);
			this.cContainer = container;
		}
	},
	closeWindow: function() {
  		if (this.favListWindow) {
			this.favListWindow.style.visibility = "hidden";
			this.favListWindow.style.display = "none";
		}	  			
	}
});
FavListControler.URL_LISTS = CMSWebAppDir + '/servlet/export/sse/favoriteLists?view=asJson';
FavListControler.URL_CATEGORIES = CMSWebAppDir + '/servlet/export/sse/favoriteListCategories?view=asJson';
FavListControler.URL_STORE = CMSWebAppDir + '/servlet/feedback/favoriteList?action=createEntry&sadbEntry=true';

function initMap(mapDescription) {
	//create the main map control
	 if (!GBrowserIsCompatible()) return;
	 	
	var mapOptions = new Object(); 
	var optimize = true;
		// set map center
	if (mapDescription.config.center) {
		mapDescription.config.center=mapDescription.config.center.split(',');
		mapOptions.center=new GLatLng(mapDescription.config.center[1], mapDescription.config.center[0]);
		optimize=false;
	}
	// set map zoomlevel
	if (mapDescription.config.zoomlevel) {
		try { mapOptions.zoom=parseInt(mapDescription.config.zoomlevel);} catch(e) {}
	}
	var mapSize = new GSize(488, 300);
	if ($('map') && $('map').getSize().y > 10) {
		mapSize = new GSize($('map').getSize().x, $('map').getSize().y);
	}
	var mapApp = new GMapApp('map',mapSize, mapOptions);

	//add some default controls supported by the API
	mapApp.map.addControl(new GSmallZoomControl());
	mapApp.map.addControl(new GScaleControl());


	// initialize mapcontroler and register relevant events
	mapControler = new LocalSearchMapControler(mapApp);
	mapControler.centerMap(mapOptions.center)
	// initialize favcontroler and register relevant events
	favControler = new FavListControler();		
	// initialize searcher
	searcher = new EmbeddedLocalSearch(mapControler);
	searcher.deregisterEvents();
	searcher.optimizeView=optimize
	if (mapDescription.route) {
		searcher.setRoute(mapDescription.route.id, mapDescription.route.maxLayerDistance, mapDescription.route.color);
		if (!mapDescription.serviceIDs) mapDescription.serviceIDs = [];
		mapDescription.serviceIDs.push(mapDescription.route.id);
	}
	
	
	if (mapDescription.config.baseUrl && (mapDescription.config.baseUrl.length > 0)) {
		YellowPageEntryURL = mapDescription.config.baseUrl;
	}

	new LayerList($('layers'), mapDescription.layers);
	
	if ((mapDescription.serviceIDs && (mapDescription.serviceIDs.length > 0)) 
		|| (mapDescription.layers && (mapDescription.layers.length > 0))) {
		var ids = ' ';
		for(var i=0;i < mapDescription.serviceIDs.length; i++) {
			if (i > 0) ids += ",";
			ids += mapDescription.serviceIDs[i];
		}
		searcher.list(ids, function() {
			// display pois
			if (mapDescription.layers && (mapDescription.layers.length > 0)) {
				for(var i=0; i < mapDescription.layers.length; i++) 
					if (mapDescription.layers[i].layerIsHidden || mapDescription.layers[i].layerIsSelected) 
						mapControler.poiLayers.showLayer(mapDescription.layers[i].layerId);
			}
		});
	}
	if (mapDescription.address) {
		searcher.search(mapDescription.address.streetaddress, mapDescription.address.text,false);
	}
	searcher.registerEvents();
	window.addEvent('unload',searcher.deregisterEvents.bind(searcher));
	reloadAdsPreventHack=true;
}

var adlWallPaperLeft = '819';

var searcher = null;
var mapControler = null;
var favControler = null;

window.addEvent('unload',GUnload);
// eof
