if (!("console" in window) || !("firebug" in console))
{
    var names = ["log", "debug", "info", "warn", "error", "assert", "dir", "dirxml",
    "group", "groupEnd", "time", "timeEnd", "count", "trace", "profile", "profileEnd"];

    window.console = {};
    for (var i = 0; i < names.length; ++i)
        window.console[names[i]] = function() {}
}




// ******************************************************************************
// Global Constants and Variables
// ******************************************************************************

var baseURL = document.getElementsByTagName('base')[0].href;



// ******************************************************************************
// Main Classes
// ******************************************************************************

var GeoSearch = Class.create();
GeoSearch.prototype = {

	// ******************************************************************************
	// Constants
	// ******************************************************************************
	Version : '0.9',


	minZoom : 5,
	maxZoom : 19,
	zoomMap : new Array(null,6,7,10,10,14,15,15,15, 15),

	minLocations : 5,

//	resultListSorting : 'postcode',
	resultListOffset : 0,

	baseURL : $$('base').first().href,
	dbPath :  'typo3temp/',
	resPath : 'typo3conf/ext/bad_locations/res/',
    	imagePath : 'icons/',

	errorMsg : {
		noAddress : new Template('<h2>'+bad_gmapTxtLang[0]['search_1']+'</h2><p> </p>'),
		wrongAddress : new Template('<h2>'+bad_gmapTxtLang[0]['search_2']+'</h2><p>'+bad_gmapTxtLang[0]['search_3']+'</p><br><p>'+bad_gmapTxtLang[0]['search_4']+'</p><br>'+bad_gmapTxtLang[0]['search_5']+''),
		suggest : new Template('<h2>'+bad_gmapTxtLang[0]['search_6']+'</h2><div style="overflow:auto" >#{list}</div>')
	},



	// dom ids
	mapContainer : 'gmap_canvas',
	routeContainer : 'route',

	searchFormId : 'badform',
	searchButtonId : 'badButton4a44a1298792f',

	filterFormId : 'badfilterform',
	filterAllId : 'allnza',

	resultListSearchFormId : 'searchForm',
	resultListContainerId : 'resultListContainer',
	resultListLoadingId : 'gs_loading_resultList',
	resultListLoadingWrapId : 'gs_loadingWrap_resultList',

	notifyId : 'gs_notify',

	modalBlockerId : 'gs_blocker',
	modalDialogId : 'gs_modal',
	modalDialogContentId : 'gs_modal_content',
	modalDialogCloseId : 'gs_modal_close',

	modalLoadingId : 'gs_loading',


	// ******************************************************************************
	// vars
	// ******************************************************************************
	map : null,

	mapCenterLat : 51.06901665960392,
	mapCenterLng : 10.37109375,
	mapZoom : 5,

	locationBubble : null,

	locuid: bad_locuid,
	zoomuid: 0,

	geocoder : null,
	icons : [],
	activeSearchPoint : null,
	activeSearchString : null,
	activeMarker : null,


	// dom Elements
	route : null,
	form : null,
	searchForm : null,
	searchButton : null,
	filterForm : null,
	resultListContainer : null,

	resultListParam : '',
	sword : '',

	options : {
	    mapCenterLat : null,
	    mapCenterLng : null,
	    mapZoom : null,

	    gmapTxtLang : {
		phone : bad_gmapTxtLang[0]["phone"],
		fax : bad_gmapTxtLang[0]["fax"],
		location : bad_gmapTxtLang[0]["location"],
		request : bad_gmapTxtLang[0]["request"]
	    },
	    badJobMode: false,
	    badSubsMode: false,
	    badSubsModeExt: false,
	    t3pageUid: null,
	    t3contentUid: null,

	    restoreMap : false,
	    sword : null,
	    viewmode : null,
	    showSearch : true,
	    showFilter : true,

	    contactLinkURL : '',

	    nza : {
		fev : 0,
		mpu : 0,
		g35 : 0,
		gfi : 0,

		osc : 0
		/*
		mcb : 0,
		mcp : 0,
		mck : 0
		*/
	    },

    	type : {
		1 : 1,
		2 : 1,
		3 : 1,
	    4 : 1,
	    5 : 1,
		6 : 1
	    }

	},


	// ******************************************************************************
	// Constructor
	// ******************************************************************************
	initialize: function(options) {
       	if((typeof Prototype=='undefined') ||
	    	(typeof Element == 'undefined') ||
	   	    (typeof Element.Methods=='undefined') ||
        	parseFloat(Prototype.Version.split(".")[0] + "." +
	           Prototype.Version.split(".")[1]) < 1.5)
	   		    throw('Die Google Maps Standortsuche benötigt das Prototype JavaScript framework >= 1.5.0');

		if (GBrowserIsCompatible() == false) {
			throw('Die Google Maps Standortsuche ist nicht mit Ihrem Browser kompatibel!');
		}



		Object.extend(this.options, options);

		document.observe('dom:loaded', this.pageLoadHandler.bindAsEventListener(this), false);
   	},


	pageLoadHandler: function() {

	    $(this.modalBlockerId).show();



		// init Map
		this.map = new GMap2(document.getElementById(this.mapContainer));
		this.map.addControl(new GLargeMapControl());
//		this.map.addControl(new GOverviewMapControl());
		this.map.addControl(new GMapTypeControl(), new GControlPosition(G_ANCHOR_TOP_RIGHT, new GSize(5, 5)));
		this.map.addMapType(G_HYBRID_MAP);
		this.map.addMapType(G_PHYSICAL_MAP);

      		if(this.options.mapCenterLat != null) {
		    this.mapCenterLat = this.options.mapCenterLat;
      		}
      		if(this.options.mapCenterLng != null) {
      		    this.mapCenterLng = this.options.mapCenterLng;
      		}
      		if(this.options.mapZoom != null) {
      		    this.mapZoom = this.options.mapZoom;
      		}

      		if(this.options.restoreMap == true) {
		    this.sword = this.options.sword;
      		}

		this.map.setCenter(new GLatLng(this.mapCenterLat, this.mapCenterLng) , this.mapZoom);

  		//this.map.enableScrollWheelZoom();

		// set default MapType
		this.map.setMapType(G_PHYSICAL_MAP);


		// ??? geht nicht ??
		//GEvent.addListener(this.map, 'onload', function(){alert('hallo');} );


  		// init geocoder - Germany
//		var sw = new GLatLng(47.33882269482199, 5.6689453125);
//		var ne = new GLatLng(54.876606654108684, 15.5126953125);


		var sw = new GLatLng(34.379713, -22.060547);
		var ne = new GLatLng(58.676938, 26.982422);


		var bounds = new GLatLngBounds(sw, ne);

		this.geocoder = new GClientGeocoder();
		this.geocoder.setBaseCountryCode('de');
		this.geocoder.setViewport(bounds);



		imagePath = this.baseURL + this.resPath + this.imagePath;

		// init icons
		icon1 = new GIcon();
		icon1.image = imagePath  + '1.png';
		icon1.iconSize = new GSize(15, 19);
		icon1.iconAnchor = new GPoint(7, 16);
		icon1.infoWindowAnchor = new GPoint(7, 10);
    		this.icons[2] = icon1;

		icon2 = new GIcon();
		icon2.image = imagePath  + '2.png';
		icon2.iconSize = new GSize(15, 26);
		icon2.iconAnchor = new GPoint(7, 23);
		icon2.infoWindowAnchor = new GPoint(7, 10);
    		this.icons[3] = icon2;

		icon3 = new GIcon();
		icon3.image = imagePath  + '3.png';
		icon3.iconSize = new GSize(17, 32);
		icon3.iconAnchor = new GPoint(8, 29);
		icon3.infoWindowAnchor = new GPoint(7, 10);
    		this.icons[4] = icon3;

		icon4 = new GIcon();
		icon4.image = imagePath  + '4.png';
		icon4.iconSize = new GSize(17, 27);
		icon4.iconAnchor = new GPoint(8, 24);
		icon4.infoWindowAnchor = new GPoint(7, 10);
    		this.icons[5] = icon4;

		icon4 = new GIcon();
		icon4.image = imagePath  + '5.png';
		icon4.iconSize = new GSize(17, 20);
		icon4.iconAnchor = new GPoint(8, 17);
		icon4.infoWindowAnchor = new GPoint(7, 10);
    		this.icons[6] = icon4;




		// ******************************************************************************

		bubbleHTML = '<div style="display:none" id="#{bubbleId}">';
		bubbleHTML += '<table border="0" cellpadding="0" cellspacing="0" class="badGmap0">';
		bubbleHTML += '<tr><td class="badGmap1">&nbsp;</td><td class="badGmap3"><a id="#{closeId}" href="#">&nbsp;</a></td><td class="badGmap2">&nbsp;</td></tr>';
		bubbleHTML += '<tr><td class="badGmap1a">&nbsp;</td><td class="badGmap4"><div id="#{contentId}"></div>';
		bubbleHTML += '</td><td class="badGmap2a">&nbsp;</td></tr>';
		bubbleHTML += '<tr><td class="badGmap5">&nbsp;</td><td class="badGmap6"><div>&nbsp;</div></td><td class="badGmap7">&nbsp;</td></tr>';
		bubbleHTML += '</table></div>';

		var bubbleTemplate = new Template(bubbleHTML);

		this.locationBubble = new EBubble(this.map, new GSize(300,90), new GPoint(0,0), new GPoint(32,45), {bubbleTemplate : bubbleTemplate});

		// ******************************************************************************
		this.resultListContainer = $(this.resultListContainerId);



		// ******************************************************************************

		if($('route')) {
		    this.route = $('route');
		    this.badGdir = new GDirections(this.map, this.route);
		    GEvent.addListener(this.badGdir, 'load', this.gmapOnGDirectionsLoad.bind(this));
		    GEvent.addListener(this.badGdir, 'error', this.gmapHandleErrors.bind(this));
// klären!
//		    if(badRoutingInfos.length>0) {
//			badStartRouting(badRoutingInfos[0],badRoutingInfos[1],badRoutingInfos[2]);
//		    }
		}


		// ******************************************************************************
	        // handler setups

		if(this.options.showSearch == true){
		    this.searchForm = $(this.searchFormId);
		    Event.observe(this.searchForm, 'submit', this.submitHandler.bindAsEventListener(this), false);

		    this.searchButton = $(this.searchButtonId);
		    Event.observe(this.searchButton, 'click', this.submitHandler.bindAsEventListener(this), false);
		}

		if(this.options.showFilter == true){
		    this.filterForm = $(this.filterFormId);
		    this.filterForm.getElements().each( function(elm){
			Event.observe(elm, 'click', this.changeFilterHandler.bindAsEventListener(this), false);
		    }.bind(this) );

		    Event.observe(this.filterAllId, 'click', this.changeFilterAllHandler.bindAsEventListener(this), false);

		}

		this.drawResultListHandlerSetup();

		// ******************************************************************************
		// load locations
     		new Ajax.Request(this.baseURL + this.dbPath + 'objectData.json', {onSuccess: this.loadLocations.bind(this)});


    },

    loadLocations : function(transport, json)
    {
//	console.info(transport);
		var json = transport.responseText.evalJSON(true);
//	console.info(json);
		this.locations = json.locations.loc;


		if(this.options.showFilter == true){
			// wegen firefox muss nochmal geprüft werden welche checkboxen nach dem RELOAD aktiv sind
			this.filterForm.getElements().each( function(elm){
			this.options.nza[elm.value] = elm.checked;
			}.bind(this));
		}

		this.locations.each(this.addMarker.bind(this));

	    GEvent.addListener(this.map, "moveend", this.drawResultListStartTimmer.bind(this));

		$(this.modalBlockerId).hide();
		$(this.modalLoadingId).hide();


		if(this.options.restoreMap == true) {
			//this.drawResultList();
			this.resultListSetPage();
		}


		// externe suche von xxx
		if(this.options.extern == 'true'){
			this.submitHandler(false);
	
		}
		if(this.zoomuid>0) {
			this.zoomToLocation(this.zoomuid, 8);
			this.zoomuid = 0;
		}
    },

	onMapLoad : function()
	{
		//console.info('test hallo');
		$('gs_blocker').hide();
	},




	dragZoom : function(ev)
	{
		Event.stop(ev);
		//this.map.
	},

   	zoom : function(ev, value)
	{
		Event.stop(ev);

		zoom = this.map.getZoom() + value;

		if(zoom < this.minZoom) zoom = this.minZoom;
		if(zoom > this.maxZoom) zoom = this.maxZoom;

		if(zoom != this.map.getZoom()){
			this.map.setZoom(zoom);
		}
	},


	submitHandler : function(ev)
	{
		if(ev) ev.stop();

//		console.info(this.searchForm.search.value);

		address = this.searchForm.search.value;
		if(address != '')
		{
		    this.sword = address;

		    // test für Postleitzahlen bereich
		    var res = address.match(/^[0-9]{1,4}$/);
		    if(res){
			this.postcodecoder(address);
		    } else {
			// Adress optimierung
			address = address.replace(/ ?deutschland ?| ?germany ?/gi, '') + ', Germany';
			this.geocoder.getLocations(address, this.getLocations.bind(this));
		    }
		}

	},

	changeFilterHandler : function(ev)
	{
	    var allCheckFlag = false;

	    this.filterForm.getElements().each( function(elm){
		if(elm.checked == true) {
		    allCheckFlag = true;
		}
		this.options.nza[elm.value] = elm.checked;
	    }.bind(this) );

	    if(allCheckFlag == true) {
		$(this.filterAllId).checked = false;
	    } else {
		$(this.filterAllId).checked = true;
	    }

	    this.locations.each(this.addMarker.bind(this));
	    this.drawResultListStartTimmer();

	},
	changeFilterAllHandler : function(ev)
	{

		this.filterForm.getElements().each( function(elm){
		    if($(this.filterAllId).checked == true){
			elm.checked = false;
		    } else {
			elm.checked = true;
		    }
		}.bind(this) );

	    this.changeFilterHandler();

	},


	getLocations : function(response)
	{
		//console.info(response);
		statusCode = response.Status.code;
		if(statusCode == 200){

			placemarks = response.Placemark;
			var temp_placemarks = new Array();
			for (var i = 0; i < placemarks.length; i++) {
			    //console.info(placemarks[i])

			    try {

				if(placemarks[i].AddressDetails.Country.CountryNameCode == 'DE'){
					temp_placemarks.push(placemarks[i]);
				}
                             } catch (e) {

		             }

			}

			this.placemarks = temp_placemarks;
			//console.info(this.placemarks);

			if (this.placemarks.length == 0) {
				var content = this.errorMsg.wrongAddress.evaluate({sword : this.searchForm.search.value});
				this.modalDialog(content);
			} else {
				if (this.placemarks.length > 1) {

					var list = '';
					for (var i = 0; i < this.placemarks.length; i++) {

						l = this.placemarks[i].address.replace(/, Germany/, '')

						if(typeof this.placemarks[i].AddressDetails.Country.AdministrativeArea != 'undefined'){
							l += ', ' + this.placemarks[i].AddressDetails.Country.AdministrativeArea.AdministrativeAreaName;
						}

						list += '<p><a href="#" onclick="myGeoSearch.showDialogLocation('+ i +');return false" >' + l + '</a></p>';
					}

					var content = this.errorMsg.suggest.evaluate({list : list});

					this.modalDialog(content);


				} else {
					this.showPlacemark(this.placemarks[0]);
				}
			}



		} else {
			var content = this.errorMsg.wrongAddress.evaluate({sword : this.searchForm.search.value});

			this.modalDialog(content);
		}

	},

	notifyShow : function(content)
	{
		$(this.notifyId).update(content);
		//$(this.notifyId).show();

		new Effect.Appear(this.notifyId, {from:0.0, to:1, duration: 1, afterFinish: this.notifyTimer.bind(this)});
	},
	notifyTimer : function()
	{
		window.setTimeout(this.notifyFadeOut.bind(this), 4000);
	},
	notifyFadeOut : function()
	{
		new Effect.Fade(this.notifyId, { from:1, to:0.0, duration: 1, afterFinish: this.notifyHide.bind(this) });
	},
	notifyHide : function()
	{
		$(this.notifyId).hide();
	},



	modalDialog : function(content)
	{
		$(this.modalBlockerId).show();
		$(this.modalDialogId).show();
		$(this.modalDialogContentId).update(content);


		Event.observe(this.modalDialogCloseId, 'click', this.modalDialogClose.bindAsEventListener(this), false);

	},


	modalDialogClose : function(ev)
	{
		if(ev) Event.stop(ev);

		$(this.modalBlockerId).hide();
		$(this.modalDialogId).hide();

	},

	showDialogLocation : function(placemarkId)
	{
		this.modalDialogClose(false);
		this.showPlacemark(this.placemarks[placemarkId]);

	},


	showPlacemark : function(placemark)
	{
		accuracy = parseInt(placemark.AddressDetails.Accuracy);
		zoom = this.zoomMap[accuracy];

		point = new GLatLng(parseFloat(placemark.Point.coordinates[1]), parseFloat(placemark.Point.coordinates[0]));

		//console.info('zoom='+zoom);
		//console.info('accuracy='+accuracy);

		this.showLocation(point, zoom);
	},


	postcodecoder : function(postcode){
		new Ajax.Request(baseURL + '?eID=postcodeToBoundary&postcode=' + postcode, {onSuccess: this.onloadPostcodeArea.bind(this)});
    },
	onloadPostcodeArea : function(transport, json)
    {
    	var json = transport.responseText.evalJSON(true);
//		console.info(json);


		// test marker
		/*
		var points = json.points.point
		for(i=0;i<points.length-1;i++) {
			var m = new GMarker(new GLatLng(points[i].lat, points[i].lng));
			this.map.addOverlay(m);
		}
		*/

		var swLatLng = new GLatLng(json.sw.lat, json.sw.lng)
		var neLatLng = new GLatLng(json.ne.lat, json.ne.lng)

		// test marker für bound
		/*
		var m = new GMarker(swLatLng, this.icons.center);
		this.map.addOverlay(m);
		var m = new GMarker(neLatLng, this.icons.center);
		this.map.addOverlay(m);
		*/

		bounds = new GLatLngBounds(swLatLng,  neLatLng);

		var zoom = this.map.getBoundsZoomLevel(bounds);
		var point = bounds.getCenter();

		this.showLocation(point, zoom);
    },




	showLocation : function(point, zoom)
	{
		// entfernen des activen distans kreis.
		if(this.activeMarker != null){
			this.map.removeOverlay(this.activeMarker);
		}

		this.activeSearchPoint = point



		// ************************************************************************************************************
		// ermiteln ob um 10 objekte erweitert werden muss
		// ************************************************************************************************************

		// schrit 1: virtuellen GBound mit hilfe von umrechnung der LatLng in PX
		var proj = G_NORMAL_MAP.getProjection();
		var centerPt = proj.fromLatLngToPixel(this.activeSearchPoint, zoom);

		this.canvasHeight = $(this.mapContainer).getHeight();
		this.canvasWidth = $(this.mapContainer).getWidth();

		swPt = new GPoint();
		swPt.x = centerPt.x - (this.canvasWidth/2);
		swPt.y = centerPt.y + (this.canvasHeight/2);

		nePt = new GPoint();
		nePt.x = centerPt.x + (this.canvasWidth/2);
		nePt.y = centerPt.y - (this.canvasHeight/2);

		swLatLng = proj.fromPixelToLatLng(swPt,  zoom);
		neLatLng = proj.fromPixelToLatLng(nePt,  zoom);


		// test marker
		/*
		var m = new GMarker(swLatLng);
		this.map.addOverlay(m);
		var m = new GMarker(neLatLng);
		this.map.addOverlay(m);
		*/

//		this.map.setCenter(this.activeSearchPoint, zoom);


		// ************************************************************************************************************
		// schritt 2: Prüfen welche marker in dem Boundary sind
		// ************************************************************************************************************
		bounds = new GLatLngBounds(swLatLng,  neLatLng);

		var res = false;
		var x = 0;
		var loccur=false;
		for(i=0;i<this.locations.length-1;i++) {

			if(this.locations[i].active == true){
				if(bounds.containsLatLng(this.locations[i].point) == true) {
					loccur=this.locations[i].point;
					x++;
				}
				//console.info('i:' + i, 'x:' + x);
				if(x == this.minLocations) {
				//console.info('ok:' + i);
					res = true;
					break;
				}
			}
		}



		if(res == false){
			var contentPre = bad_gmapTxtLang[0]['search_7'];
			var content = contentPre.replace(/\#\{count\}/,this.minLocations);
			if(this.minLocations>1) this.notifyShow(content);

			this.expandToTen(bounds,loccur);
		} else {
			if(loccur && this.minLocations==1) {
				this.map.setCenter(loccur, zoom);
			}
			else {
				this.map.setCenter(this.activeSearchPoint, zoom);
			}
		}

		this.drawResultListStartTimmer();


		//GEvent.addListener(this.map, "moveend", this.drawResultList.bind(this));
		//GEvent.addListener(this.map, "zoomend", this.drawResultList.bind(this));

		return false;
	},


	expandToTen : function(bounds,loccur)
	{
	    //this.modalDialogClose();

	    // Distance von mapCenter zu jeder location berechnen

	    tempLocationArr = new Array();

		var curpoint=false;
		
	    for(var i=0; i<this.locations.length; i++) {
		var location = this.locations[i];

			if(location.active == true) {
			    location.distance = this.activeSearchPoint.distanceFrom(location.point);
			    tempLocationArr.push(location);
			}
	    }

	    // Locations nach distance sortieren
	    var locationsSorted = tempLocationArr.sortBy(function(s) { return s.distance; })


	    var count = 1;
	    for(var i=0; i < locationsSorted.length; i++) {
			if(!curpoint) {
				curpoint=locationsSorted[i].point;
			}
			if(count > this.minLocations) break;

			var location = locationsSorted[i];
//		if(location.active == true){
		    bounds.extend(location.point);
		    /*
			 icon = new GIcon(G_DEFAULT_ICON);
			 marker = new GMarker(location.point, icon);
			 this.map.addOverlay(marker);
		     */
		    count++;
//		}
	    }
		if(curpoint && this.minLocations==1) {
			this.map.setCenter(curpoint, this.map.getBoundsZoomLevel(bounds));
		}
	    else {
			this.map.setCenter(bounds.getCenter(), this.map.getBoundsZoomLevel(bounds));
		}
	    //this.map.setCenter(this.activeSearchPoint, this.map.getBoundsZoomLevel(bounds));


	    this.activeMarker = new GMarker(this.activeSearchPoint, {icon : this.icons.center, zIndexProcess : function(marker,b){
		z = GOverlay.getZIndex(marker.getPoint().lat()) - 10000;
		//console.info('zindex=' + z)
		return z;
	    }});

/*
	    this.activeMarker = new GMarker(this.activeSearchPoint, this.icons.center);
	    this.map.addOverlay(this.activeMarker);
*/

	    // test marker
	    //var m = new GMarker(this.activeSearchPoint);
	    //this.map.addOverlay(m);


	},

	zoomToLocation : function(locationId, accuracy)
	{

	        //myGeoSearch.clusterer.PopDown();
		this.locationBubble.hide();
		this.map.setCenter(this.locations[locationId].point, this.zoomMap[accuracy]);
	},

	zoomToCluster : function(weIdcvs)
	{
		myGeoSearch.clusterer.PopDown();
		this.locationBubble.hide();

		// Rahmen erstellen
		var bounds = new GLatLngBounds();
		var weIds = weIdcvs.split(',');

		for(var i=0; i < weIds.length; i++) {
			we = this.locations[weIds[i]];
			if(we.active == true) {
				bounds.extend(we.point);
			}
		}

		this.map.setCenter(bounds.getCenter(), this.map.getBoundsZoomLevel(bounds));

	},



	getMarkerZindex : function(type){

	    switch(parseInt(type)) {
		case 2:
		    z = 1000;
		break;
		case 3:
		    z = 3000;
		break;
		case 4:
		    z = 5000;
		break;
		case 5:
		    z = 4000;
		break;
	    }

	    return z;
	},


	addMarker: function(location, id)
	{
		if(this.locuid>0) {
			if(this.locuid==location.uid) {
				this.zoomuid=id;
				this.locuid=0;
			}			
		}

	    // nza filter überprüfen - ebay Style
	    // ***********************************************************************************************************
	    alloff = $H(this.options.nza).all(function(n){
		if(n.value == 0) return true;
	    });
	    if(alloff == true){
		nzaFilter = true;
	    } else {
		nzaFilter = $H(this.options.nza).any(function(n){
		    if(n.value == 0) return false;
		    return n.value == location.nza[n.key];
		});
	    }

	    // ***********************************************************************************************************

	    // adresstype filter überprüfen
	    // ***********************************************************************************************************
	    typeFilter = $H(this.options.type).any(function(n){
		// console.info('value',n.value, n.key)
		if(n.value == 0) return false;
		return n.key == location.type;
	    });

	    // ***********************************************************************************************************

	    if(nzaFilter == true && typeFilter == true) {
		active = true;
	    } else {
		active = false;
	    }


	    if(active == true) {
		if(!location.active) {
		    // obtain the attribues of each marker
		    if(!location.marker){
			location.point = new GLatLng(parseFloat(location.lat), parseFloat(location.lng));

			var marker = new GMarker(location.point, { icon: this.icons[location.type], zIndexProcess: this.getMarkerZindex.bind(this, location.type) } );
			marker.type = location.type;

			    // ***********************************************************************************************************
			    // bubble html begin
			    // ***********************************************************************************************************
			    nzaArr = new Array();
			    if(location.nza.fev == "1") {
				nzaArr.push('FeV');
			    }
			    if(location.nza.mpu == "1") {
				nzaArr.push('MPU');
			    }
			    if(location.nza.g35 == "1") {
				nzaArr.push('G35-Ermächtigung');
			    }
			    if(location.nza.gfi == "1") {
				nzaArr.push('Gelbfieberimpfstelle');
			    }
			    var nzaText = nzaArr.join(', ');



			    html = '<span class="gmTitle">#{com}</span>';
			    if(location.addr)  { html += '<span class="gmAdress"><span class="gmData">#{addr}</span></span>'; }
			    if(location.city) { html += '<span class="gmZip"><span class="gmData">#{zip} #{city}</span></span>'; }
			    if(location.pho)  { html += '<span class="gmPhone">#{gmapTxtLang.phone}: <span class="gmData">#{pho}</span></span>'; }
			    if(location.fax)  { html += '<span class="gmFax">#{gmapTxtLang.fax}: <span class="gmData">#{fax}</span></span>'; }

			    if(!this.options.badJobMode && !this.options.badSubsMode && !this.options.badSubsModeExt) {
				if(location.type == 5) {
				    html += '<span class="gmCountry">#{ctry}</span>';
				    html += '<div class="spacer">&nbsp;</div>';
				    if(location.www) {
					location.wwwx = location.www.replace(/http:\/\/|https:\/\//,'');
					html+='<p class="extLink"><a href="#{www}" target="_blank">#{wwwx}</a></p>';
				    }
				} else {
				    html += '<div class="spacer">&nbsp;</div>';
				    html += '<p class="specialLink"><a href="#" onclick="myGeoSearch.zoomToLocation(#{locationId}, 8);return false" >#{gmapTxtLang.location}</a></p>';
				    html += '<p class="specialLink"><a href="#" onclick="document.location.href=\'#{contactLinkURL}?contact=#{uid}&url=#{self}\';return false">#{gmapTxtLang.request}</a></p>';
				}
			    } else if(this.options.badSubsModeExt) {
				html += '<div class="spacer">&nbsp;</div>';
				html += '<p class="specialLink"><a href="#" onclick="myGeoSearch.zoomToLocation(#{locationId}, 8);return false" >#{gmapTxtLang.location}</a></p>';
				html += '<p class="specialLink"><a href="#" onclick="console.info(\'test\');return false">#{gmapTxtLang.request}</a></p>';
			    } else if(this.options.badSubsMode) {
				if(location.type==4) {
				    html += '<div class="spacer">&nbsp;</div>';
				    html += '<p class="specialLink"><a href="#" onclick="myGeoSearch.zoomToLocation(#{locationId}, 8);return false" >#{gmapTxtLang.location}</a></p>';
				    html += '<p class="specialLink"><a href="#" onclick="console.info(\'test\');return false">#{gmapTxtLang.request}</a></p>';
				} else {
				    html += '<span class="gmCountry">#{ctry}</span>';
				    html += '<div class="spacer">&nbsp;</div>';

//				    if(trim(gmapMarkers[i][12])!='') {
//					var url=gmapMarkers[i][12].replace(/http:\/\/|https:\/\//,'');
//					html += '<p class="extLink"><a href="'+gmapMarkers[i][12]+'" target="_blank">'+url+'</a></p>';
//				    }
				}
			    } else {
				html += '<div class="spacer">&nbsp;</div>';
				html += '<div class="csc-hrline">&nbsp;</div><div class="jobsGmap">';
//				for(var k=0;k<badJobs[i].length;k++) {
//				    html += '<p class="specialLink">'+badJobs[i][k]+'</p>';
//				}
				html += '</div>';
			    }

			    var dataObj = location;
			    dataObj.gmapTxtLang = this.options.gmapTxtLang;
			    dataObj.locationId = id;
			    dataObj.contactLinkURL = this.options.contactLinkURL;
			    dataObj.self = document.location.pathname;

			    var template = new Template(html);
			    var bubbleHTML = template.evaluate(dataObj);

			    // bubble html ende
			    // ***********************************************************************************************************



			    GEvent.addListener(marker, "click", function() {
				this.bubbleClearTimeout()
			    	this.locationBubble.openOnMarker(marker, bubbleHTML);
        		    }.bind(this));

        		    GEvent.addListener(marker, "mouseout", function() {
				//this.locationBubble.hide();
				this.bubblePopUpTimeout()
        		    }.bind(this));

			    /*
			     GEvent.addListener(marker, "click", function() {
			     this.locationBubble.hide();
			     this.zoomToLocation(id, 8);
        		     }.bind(this));
			     */

        		    this.locationBubble.setTimeoutFunc(this.bubblePopUpTimeout.bind(this, 10000))
			    this.locationBubble.setTimeoutFunc2(this.bubblePopUpTimeout.bind(this, 1))

			    location.marker = marker;
			} else {
			    //location.marker.onMap = false;
			}

			//if(location.marker.onMap != true)
			this.map.addOverlay(location.marker);
			location.active = true;
		    }

		} else {
		    if(location.marker){
			this.map.removeOverlay(location.marker);
		    }
		    location.active = false;
		}
/*
		var marker2 = new GMarker(location.point);
		this.map.addOverlay(marker2);
*/

	},


	bubblePopUpTimeout : function(val){
		if(!val) val = 1000;
		this.bubbleClearTimeout()
		this.timerHandler = window.setTimeout(this.hideImmoBubble.bind(this), val)
	},
	bubbleClearTimeout : function(){
		if(typeof this.timerHandler != "undefined")
			window.clearTimeout(this.timerHandler)
	},
	hideImmoBubble : function(){
		this.locationBubble.hide()
	},





	drawResultListStartTimmer : function()
	{
		window.clearTimeout(this.resultListTimer);
		this.resultListTimer = window.setTimeout(this.drawResultList.bind(this), 100);
	},


	drawResultList : function()
	{

		var bounds = this.map.getBounds();

		var locInBound = new Array();
		var weCSV = '';
		var weIdArr = new Array();
		var x = 0;
		for(i=0;i<this.locations.length;i++){
			we = this.locations[i];
			if(we.active){
				if(bounds.containsLatLng(we.point) == true) {
					//console.info('test:' + i);
					weIdArr.push(we.uid);
				}
			}
		}
		var locationCSV = weIdArr.join(',');

		var lat = this.map.getCenter().lat();
		var lng = this.map.getCenter().lng();
		var zoom = this.map.getZoom();

		var paramArr = new Array();
		paramArr.push('id='+ this.options.t3pageUid);
		paramArr.push('cid='+ this.options.t3contentUid);
		paramArr.push('type=2');
		paramArr.push('send=true');
		paramArr.push('mapCenterLat=' + lat);
		paramArr.push('mapCenterLng=' + lng);
		paramArr.push('sword=' + this.sword);
		paramArr.push('mapZoom=' + zoom);
		paramArr.push('searchFormType=map');
		paramArr.push('locations=' + locationCSV);

		for(n in this.options.nza) {
		    if(this.options.nza[n])
			paramArr.push('nza['+ n +']=' + this.options.nza[n])
		}

		paramArr.push('sorting=' + this.resultListSorting);
		paramArr.push('offset=' + this.resultListOffset);

		var param = paramArr.join('&');
		var url = 'index.php';


		if(this.resultListParam != param) {
		    this.resultlistLoadingShow();
		    new Ajax.Updater(this.resultListContainerId, url, {method : 'post', parameters : param, onComplete : this.drawResultListOnReadyHandler.bindAsEventListener(this), evalScripts : true });
		    this.resultListParam = param;
		}

	},

	drawResultListOnReadyHandler : function(ev)
	{
	    this.resultlistLoadingHide();
	    this.drawResultListHandlerSetup();
	},


	drawResultListHandlerSetup : function()
	{
		// *********************************************************
		// Event Handler setup

		// Paging und sorting event (gibt es im moment noch nicht ??)
		if($('resultListSortingSelect')){
			links = $(this.resultListContainerId).select('.jumpPageBlock A');
			links.each(this.resultListBindLinks.bind(this));

			Event.observe($(this.resultListSearchFormId), 'submit', this.resultListSubmitHandler.bindAsEventListener(this) , false);
			Event.observe($('resultListSortingSelect'), 'change', this.resultListChangeHandler.bindAsEventListener(this) , false);
		}

		// Standard Umkreissuche
		$$('.tx-badlocations-pi8-singleData form').each(
		    function(elm){
			Event.observe(elm, 'submit', this.routeSubmitHandler.bindAsEventListener(this) , false);
			Event.observe(elm.route_field, 'focus', this.routeFocusHandler.bindAsEventListener(this) , false);
			Event.observe(elm.route_field, 'blur', this.routeBlurHandler.bindAsEventListener(this) , false);
		    }.bind(this)
		);


		// Propertyicons (Filter) (FeV, MPU...)

	    $$('.propertyIconsRow img').each(
		    function(elm){
			Event.observe(elm, 'mouseover', function(e){
					  badToolTip(1, elm.alt);
					  elm.title = '';
				      } , false);
			Event.observe(elm, 'mouseout',  function(e){
					  badToolTip(0);
				      }, false);

		    }.bind(this)
		);


		// Tochtergeselschaften
		$$('.tx-badlocations-pi8-subline .toggleLink').each(
		    function(elm){
			Event.observe(elm, 'click', this.togglerClickHandler.bindAsEventListener(this), false);
		    }.bind(this)
		);
		
	},



	resultListChangeHandler : function(ev){
		$(this.resultListSearchFormId).sortierungsFlag.value = true;
		this.resultListSubmitHandler(ev);

	},

	resultListSubmitHandler : function(ev)
	{
		ev.stop();

		//param = elm.name + '=' + elm.value + '&sortierungsFlag=' +
		param =  $(this.resultListSearchFormId).serialize();

		//console.info(param)

		url = $(this.resultListSearchFormId).action + '?type=2';
		this.resultlistLoadingShow();
		new Ajax.Updater(this.resultListContainerId, url, {parameters : param, method : 'post', onComplete : this.drawResultListOnReady.bindAsEventListener(this), evalScripts : true });
	},

	resultListBindLinks : function(elm)
	{
		Event.observe(elm, 'click', this.resultListLinkClickHandler.bindAsEventListener(this), false);
	},

	resultListLinkClickHandler : function(ev)
	{
		ev.stop();
		var elm = ev.element();

		url = elm.href + '&type=2';

		//console.info(url);
		this.resultlistLoadingShow();
		new Ajax.Updater(this.resultListContainerId, url, {method : 'get', onComplete : this.drawResultListOnReady.bindAsEventListener(this), evalScripts : true });
	},

	resultListSetPage : function()
	{
		url = 'angebote/suchergebnisse.html?type=2';
		//console.info(url);

		this.resultlistLoadingShow();
		new Ajax.Updater(this.resultListContainerId, url, {method : 'get', onComplete : this.drawResultListOnReady.bindAsEventListener(this), evalScripts : true });
	},


	resultlistLoadingShow : function(){

		h = $(this.resultListContainerId).getHeight();
		$(this.resultListLoadingWrapId).setStyle({height : h + 'px'});

		$('resultListContainerWrap').show();
		$('gs_loadingHead_resultList').show();
		$(this.resultListLoadingWrapId).show();
		$(this.resultListLoadingId).show();

		if($('resultListSortingSelect')) $('resultListSortingSelect').hide();
	},
	resultlistLoadingHide : function(){
		$('gs_loadingHead_resultList').hide();
		$(this.resultListLoadingWrapId).hide();
		$(this.resultListLoadingId).hide();

		if($('resultListSortingSelect')) $('resultListSortingSelect').show();
	},



	togglerClickHandler : function(ev){
	    ev.stop();
	    var elm = ev.element();
	    var toggleElm = elm.up().next();


	    $$('.tx-badlocations-pi8-subline').without(toggleElm.up()).each(function(i){
		i.removeClassName('ACT');
		i.select('.tx-badlocations-pi8-subdesc').first().hide();
	    });

	    toggleElm.toggle();
	    toggleElm.up().toggleClassName('ACT');


	},



	// ***********************************************************************************************
	// gdir routing functions
	// ***********************************************************************************************

	routeSubmitHandler : function(ev){
	    ev.stop();
	    var formElm = ev.element();

	    var locale='de';
	    if(formElm.route_field.value == formElm.route_field.defaultValue) return false;

	    this.route.show();
	    locationStr = 'from: ' + formElm.route_field.value + ' to: ' + formElm.from.value;
	    this.badGdir.load(locationStr, { 'locale': locale });
	},
    routeFocusHandler : function(ev){
	    ev.stop();
	    var elm = ev.element();
	    bad_focusField(elm)
	},
    routeBlurHandler : function(ev){
	    ev.stop();
	    var elm = ev.element();
	    bad_blurField(elm);
	},

	routing : function(){

	},


	gmapHandleErrors : function(){
	    if (this.badGdir.getStatus().code == G_GEO_UNKNOWN_ADDRESS)
		alert(bad_gmapTxtLang[0]['search_8']+this.badGdir.getStatus().code);
	    else if (this.badGdir.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: " + this.badGdir.getStatus().code);
	    else if (this.badGdir.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: " + this.badGdir.getStatus().code);
	    else if (this.badGdir.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: " + this.badGdir.getStatus().code);
	    else if (this.badGdir.getStatus().code == G_GEO_BAD_REQUEST)
		alert("A directions request could not be successfully parsed.\n Error code: " + this.badGdir.getStatus().code);
	    else alert("An unknown error occurred.");
	},
	gmapOnGDirectionsLoad : function(){
	    // Use this function to access information about the latest load()
	    // results.

	    // e.g.
	    // document.getElementById("getStatus").innerHTML = gdir.getStatus().code;
	    // and yada yada yada...
	},



	// ***********************************************************************************************
	// Ajax Response Handler
	// ***********************************************************************************************
	onCreate: function(){

//		this.overlay.create();
//		this.overlay.show();

		Element.show(this.ajaxLoadingIconObj);
	},
	onComplete: function() {

//		if(Ajax.activeRequestCount == 0){
			Element.hide(this.ajaxLoadingIconObj);


//			this.overlay.hide();

		    if(ajaxUpdaterFlag == false){

				ajaxUpdaterFlag = true;
			}

			
//		}
	}
};