var SERACELL = 0;
var OTHER = 1;
var HOME = 2;

/**
 * empty helper
 */
function nothing() {}

/**
 * Checks wether a String is Numeric
 */
String.prototype.isNumeric = function() {
	return parseFloat(this) + '' == parseFloat(this);
};

/**
 * test if an Object is Numeric
 * @param {Object} obj
 */
function isNumeric(obj) {
	return parseFloat(obj) + '' == parseFloat(obj);
};

/**
 * Determinate Values of GET Parameters
 * @param {string} name
 */
function getParameter(name){
	name = name.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
	var regexS = "[\\?&]"+name+"=([^&#]*)";
	var regex = new RegExp( regexS );
	var results = regex.exec( window.location.href );
	if( results == null )
		return "";
	else
		return results[1];
}

var Seracell = Class.create({
	/**
	 * initialisize Search Object
	 * @param {float} opt1 - initial lat
	 * @param {float} opt2 - initial lng
	 * @param {int} opt3 - initial zoom
	 */
	initialize: function(opt1, opt2, opt3) {
		debugMessage('init Seracellclass');

		// predefined Values
		this.zoomDelay = 1000; // cause Zoom triggers move
		this.maxZoom = 15; // Detail Zoom Level
		this.minZoom = 3;
		this.maxRange = 100;
		this.defaultRange = 40;
		this.minRange = 5;
		this.maxAddress = 8;
		this.blink = 1000;

		var zoom;
		// default values
		this.searchUrl = 'search.php';
		this.updateRequest = true;
		this.homeLocation = null;
		this.nameSearch = null;
		this.setLoadMarker(true);
		this.setShowNonSeracell(false);
		this.setItemIsFocused(false);


		// create default icons
		var basicSmallIcon = new GIcon();
		basicSmallIcon.iconSize = new GSize(12, 20);
		basicSmallIcon.shadowSize = new GSize(22, 20);
		basicSmallIcon.iconAnchor = new GPoint(6, 20);
		basicSmallIcon.infoWindowAnchor = new GPoint(5, 1);
		// normal and Seracell icon
		
		// hier Icon-Änderungen möglich
		this.seracellIcon = new GIcon(basicSmallIcon, "http://labs.google.com/ridefinder/images/mm_20_purple.png", null, "http://labs.google.com/ridefinder/images/mm_20_shadow.png");
		this.normalIcon = new GIcon(basicSmallIcon, "http://labs.google.com/ridefinder/images/mm_20_gray.png", null, "http://labs.google.com/ridefinder/images/mm_20_shadow.png");

		var baseGEIcon = new GIcon();
		baseGEIcon.iconSize=new GSize(32,32);
		baseGEIcon.shadowSize=new GSize(56,32);
		baseGEIcon.iconAnchor=new GPoint(16,32);
		baseGEIcon.infoWindowAnchor=new GPoint(16,0);
		// home location
		this.homeIcon = new GIcon(baseGEIcon, "http://maps.google.com/mapfiles/kml/pal3/icon56.png", null, "http://maps.google.com/mapfiles/kml/pal3/icon56s.png");

		// add Spinner
		if(!$('spinner')) {
			var loadLayer = new Element('div', {id: 'spinner', style: 'display:none;'});
			$$('body')[0].insert(loadLayer);
			var spinnerBg = new Element('div', {id: 'spinnerbg'});
			loadLayer.insert(spinnerBg);
			var imageTag = new Element('img', {src: 'images/ajax_loader.gif'});
			loadLayer.insert({bottom: imageTag});

			var cTop =  ($('mapWrapper').cumulativeOffset().top);
			var cLeft = ($('mapWrapper').cumulativeOffset().left);

			loadLayer.setStyle({width: ($('mapWrapper').getWidth())+'px'});
			loadLayer.setStyle({height: ($('mapWrapper').getHeight()+15)+'px'});
			loadLayer.setStyle({left: cLeft+'px'});
			loadLayer.setStyle({top: cTop+'px'});

			spinnerBg.setStyle({width: ($('mapWrapper').getWidth())+'px'});
			spinnerBg.setStyle({height: ($('mapWrapper').getHeight()+15)+'px'});
		}

		// add function to searchbutton
		Event.observe($('googleForm'), 'submit', function(event) {
			Event.stop(event);
			debugMessage('clicked submit');
			$('formError').innerHTML = '';
			this.searchMarker($F('name'), $F('address'), $F('range'));
		}.bind(this), false);

		// create GMap2
		this.map = new google.maps.Map2($("map"));
		this.map.addControl(new GSmallMapControl());
		this.map.addControl(new GMapTypeControl());

		// GMap Location
		// default:  Deutschlandkarte
		if (!Object.isUndefined(opt1) && Object.isNumber(opt1) &&
			!Object.isUndefined(opt2) && Object.isNumber(opt2)) {
			lat = parseFloat(opt1);
			lng = parseFloat(opt2);

			if (!Object.isUndefined(opt3) && Object.isNumber(opt3)) { // zoom
				zoom = parseFloat(opt3);
			}
		} else {
			lat = 52.52378;
			lng = 13.4119;
			zoom = 10;
		}

		if (Object.isUndefined(zoom) || !Object.isNumber(zoom))
			zoom = 10;

		this.map.setCenter(new GLatLng(lat, lng), zoom);

		// Determinte Get Parameter
		$('name').value = decodeURIComponent(getParameter('name'));
		$('address').value = decodeURIComponent(getParameter('address'));
		var num = decodeURIComponent(getParameter('range'));
		if (num.isNumeric())
			$('range').value = num;

		if (!$F('name').empty() || !$F('address').empty()) {
			this.updateRequest = false;
			this.searchMarker($F('name'), $F('address'), $F('range'));
		}

		// register Map listener
		this.addMapEvents();
	},

	/**
	 * register Map Events
	 */
	addMapEvents: function() {
		GEvent.addListener(this.map, "movestart", function(){
			debugMessage('MoveStart triggered');
			this.updateRequest = true;
		}.bind(this));

		// movelistener
		GEvent.addListener(this.map, "moveend", function(){
			debugMessage('Moveend triggered');
			if (this.loadMarker)
				this.updateMarker();
		}.bind(this));
		// zoomlistener
		GEvent.addListener(this.map, "zoomend", function(oldzoom, newzoom){
			debugMessage('Zoomend triggered');
			if (!this.updateRequest)
				this.updateRequest = true;
			if (this.loadMarker && newzoom > oldzoom) {
				this.updateMarker();
			}
		}.bind(this));
	},

	/**
	 * load markers on Mapchange?
	 * @param {Object} a
	 */
	setLoadMarker: function(a) {
		debugMessage('loadMarkers: '+a);
		if (a)
			this.loadMarker = true;
		else
			this.loadMarker = false;
	},

	/**
	 * Show non Seracell Markers?
	 * @param {Object} a
	 */
	setShowNonSeracell: function(a) {
		if (a)
			this.showNonSeracell = true;
		else
			this.showNonSeracell = false;
	},
	
	setShowAddressLinks: function(a) {
		if (a) {
			$('optionhome2').style.display = 'inline';
		} else {
			$('optionhome2').style.display = 'none';
			$('address').value = '';
			$('range').value = '';
		}
	},
	
	setShowNameLinks: function(a) {
		if (a) {
			$('optionfilter2').style.display = 'inline';
			$('optionfilter').style.display = 'inline';
		} else {
			$('optionfilter2').style.display = 'none';
			$('optionfilter').style.display = 'none';
			$('name').value = '';
		}
	},

	/**
	 * is a Marker focused?
	 * @param {Object} a
	 */
	setItemIsFocused: function(a) {
		if (a)
			this.itemIsFocused = true;
		else
			this.itemIsFocused = false;
	},

	/**
	 * remove last Section from an Address-String splitted by ,
	 * @param {Object} Address
	 */
	prepareAddress: function(address) {
		debugMessage('prepare: '+address+';; type: '+(typeof address));
		if (Object.isString(address)) {
			var tmp = address.split(/,/);
			if (tmp.length == 2) {
				tmp[0] = tmp[0]+ ', (Zentrum)';
			}
			var res = '';
			debugMessage(tmp.toString()+' -- '+tmp.length);
			for (var i = 0; i < tmp.length - 1; i++) {
				res += tmp[i];
				if (i+2 < tmp.length)
					res += ',';
			}
			debugMessage(res);
			return res;
		}
		return '';
	},

	/**
	 * replace , with <br />
	 * @param {Object} Address
	 */
	prepareAddress2: function(address) {
		if (Object.isString(address)) {
			var tmp = address.split(/,/);
			var res = '';

			for (var i = 0; i < tmp.length; i++) {
				res += tmp[i].strip();
				if (i+1 < tmp.length)
					res += '<br />';
			}
			return res;
		}
		return '';
	},

	/**
	 * Set Custom Location-Address
	 * @param {Object} Address
	 */
	setHomeLocationAddress: function(address) {
		debugMessage('set Address:'+address);
		if (Object.isString(address))
			this.homeLocationAddress = this.prepareAddress2(address);
		else
			this.homeLocationAddress = null;
		debugMessage(this.homeLocationAddress);
	},

	// Set Custom Location
	setHomeLocation: function(lat, lng) {
		debugMessage('set Home: '+lat+' && '+lng);
		if (this.homeLocation != null)
			this.resetHomeLocation(false);

		if (isNumeric(lat) && isNumeric(lng)) {
			debugMessage('create');
			var point = new GLatLng(parseFloat(lat), parseFloat(lng));
			// create Tooltip/HTML
			var html;
			if (this.homeLocationAddress != null) {
				html = "<p>"+this.homeLocationAddress+"</p>";
			} else {
				html = "<h2>Mein Standort</h2>";
			}

			this.homeLocation = this.createMarker(point, HOME, html);
		}
		debugMessage('end');
	},

	/**
	 * remove Custom Location
	 */
	resetHomeLocation: function(nonewsearch) {
		nonewsearch = typeof(nonewsearch) != 'undefined' ? nonewsearch : true;	
		
		debugMessage('reset Home');
		$('location').style.display='none';
		if (nonewsearch)
			this.setShowAddressLinks(false);
		
		if (this.homeLocation != null) {
			this.homeLocation.remove();
			this.homeLocation = null;
			// remove distance
			var marker = this.map.getFirstMarker();
			while (marker != null) {
				marker.getUserData().getElementsByClassName('distance')[0].style.display = 'none';
				marker.setTooltip(marker.getUserData2());
				marker = this.map.getNextMarker();
			}
			var tags = $('sidebarList').getElementsByClassName('distance');
			for (var i = 0; i < tags.length; i++) {
				tags[i].style.display = 'none';
			}
		}
	},

	/**
	 * Search by Name?
	 * @param {Object} name
	 */
	setNameSearch: function(name) {
		if (this.name != null)
			this.resetNameSearch();

		this.nameSearch = name;
		this.setLoadMarker(false);
		this.setShowNameLinks(true);
	},

	/**
	 * restore default Search Parameters
	 * @param {Object} reload
	 */
	resetNameSearch: function(reload) {
		if (this.nameSearch != null) {
			this.nameSearch = null;
			this.setShowNameLinks(false);
			this.setLoadMarker(true);

			if (reload) {
				this.updateRequest = true;
				this.initMarker();
			}
		}
	},

	/**
	 * create a Marker
	 * @param {GLatLng} point - coordinates
	 * @param {int} type - SERACELL, HOME, OTHER
	 * @param {string} html - Tooltip/Sidebar
	 */
	createMarker: function(point, type, html) {
		//debugMessage("create Marker");
		if (typeof point != "undefined" && typeof html != "undefined") {
			var icon;
			var wrapHTML;
			if (type == SERACELL) {
				icon = this.seracellIcon;
				wrapHTML = new Element('div');

			} else if (type == HOME) {
				icon = this.homeIcon;
				wrapHTML = new Element('div', {'class': 'home'});

			} else {
				icon = this.normalIcon;
				wrapHTML = new Element('div', {'class': 'none'});
			}

			var marker = new PdMarker(point, icon);

			// calc distance
			var htmlD = html;
			if (this.homeLocation != null) {
				htmlD = htmlD+"<p></p><p class=\"distance\">Entfernung zur ausgew&auml;hlten Adresse: "+(this.homeLocation.getLatLng().distanceFrom(point)/1000).toFixed(2)+"km</p>";
			}

			// create List & Tooltip-Element
			var liWrap = new Element('li');

			wrapHTML.innerHTML = htmlD;
			liWrap.insert(wrapHTML);

			// create Tooltip
			marker.setTooltip(htmlD);
			marker.setUserData2(html)
			marker.setUserData(liWrap);
			marker.setOpacity(90);

			// mouseOver
			liWrap.observe('mouseover', function(event){
				//marker.blink(true, this.blink);
				if (type != HOME)
					marker.setImage("images/purple_blink.gif");
				marker.topMarkerZIndex();
				liWrap.addClassName('highlight');
			});
			// mouseOut
			liWrap.observe('mouseout', function(event){
				if (type != HOME)
					marker.restoreImage();
				marker.restoreMarkerZIndex();
				liWrap.removeClassName('highlight');
			});

			// clicks
			if (type != HOME) {
				Event.observe(liWrap, 'click', this.itemClickEvent.bindAsEventListener(this, marker));
				GEvent.addListener(marker, 'click', this.itemClickEvent.bindAsEventListener(this, marker));
			}
			return marker;
		}
		debugMessage("error adding");
		return null;
	},

	/**
	 * Marker click event
	 * @param {Object} event
	 * @param {PDMarker} curmarker
	 */
	itemClickEvent: function(event, curmarker) {
		debugMessage('clicked item: save view &amp; focus');
		if (this.itemIsFocused) {
			this.map.setCenter(curmarker.getLatLng(), this.maxZoom);
		} else {
			this.showSpinner(true);
			this.map.savePosition();
			this.setLoadMarker(false);
			this.setItemIsFocused(true);
			var marker = this.map.getFirstMarker();
			while (marker != null) {
				if (marker.getId() != curmarker.getId() && marker != this.homeLocation) {
					marker.hide();
					marker.getUserData().hide();
				}
				marker = this.map.getNextMarker();
			}
			this.map.setCenter(curmarker.getLatLng(), this.maxZoom);
			var restore = new Element('a', {'href': 'javascript:nothing()'});
			var restoreLi = new Element('li', {'id': 'back'});
			restoreLi.insert({'bottom': restore});
			restore.innerHTML = 'Zur&uuml;ck zur Klinikliste';
			Event.observe(restore, 'click', this.itemRestoreEvent.bindAsEventListener(this, restoreLi));
			$('sidebarList').insert({'bottom': restoreLi});
			this.showSpinner(false);
		}
	},

	/**
	 * Marker restore last View Event
	 * @param {Object} event
	 * @param {HTMLElement} li
	 */
	itemRestoreEvent: function(event, li) {
		debugMessage('clicked link: restore view');
		this.showSpinner(true);
		var marker = this.map.getFirstMarker();
		while (marker != null) {
			marker.show();
			marker.getUserData().show();
			marker = this.map.getNextMarker();
		}
		this.map.returnToSavedPosition();
		li.remove();
		this.setItemIsFocused(false);
		if (this.name != null)
			this.setLoadMarker(false);
		else
			this.setLoadMarker(true);
		this.showSpinner(false);
	},

	/**
	 * Request Markers with help of Search Parameters
	 * @param {string} name
	 * @param {float} lat
	 * @param {float} falselng
	 * @param {int} range
	 */
	loadSearchPoints: function(name, lat, lng, range) {
		debugMessage('start request: parameters (lat => '+lat+', lng => '+lng+', name => '
						+name+', range => '+range+')');
		new Ajax.Request(this.searchUrl, {
			asynchronous:true,
			evalScripts:false,
			method:'get',
			onSuccess: function(request){
				debugMessage('got valid response');
			}.bind(this),
			onFailure: function(request) {
				debugMessage('got invalid response');
			}.bind(this),
			onComplete: function(request) {
				debugMessage('finished request');
				this.showSpinner(false);
				if (this.nameSearch != null)
					this.setLoadMarker(false);
				else
					this.setLoadMarker(true);
			}.bind(this),
			parameters:	'mode='+3+
						'&lat='+lat+
						'&lng='+lng+
						'&name='+encodeURIComponent(name)+
						'&range='+range
			}
		);
	},

	/**
	 * load visible Marker (rectangle)
	 * @param {int} mode
	 * @param {float} llat
	 * @param {float} llng
	 * @param {float} rlat
	 * @param {float} rlng
	 */
	loadVisiblePoints: function(mode, llat, llng, rlat, rlng){
		debugMessage('start request: parameters (mode => '+mode+', llat => '+llat+', llng => '+llng+', rlat => '
						+rlat+', rlng => '+rlng+')');
		new Ajax.Request(this.searchUrl, {
			asynchronous:true,
			evalScripts:false,
			method:'get',
			onSuccess: function(request){
				debugMessage('got valid response');
			}.bind(this),
			onFailure: function(request) {
				debugMessage('got invalid response');
			}.bind(this),
			onComplete: function(request) {
				debugMessage('finished request');
				this.showSpinner(false);
			}.bind(this),
			parameters:	'mode='+mode+
						'&lc='+llat+','+llng+
						'&rc='+rlat+','+rlng
			}
		);
	},

	/**
	 * Show HomeLoaction on Map/Sidebar
	 */
	showHomeLocation: function() {
		debugMessage('show Home Loc');
		if (this.map.getZoom() <= this.minZoom) {
			$('sidebarList').innerHTML = '<li>Bitte vergr&ouml;ßern Sie den Kartenausschnitt.</li>'
		} else if (this.homeLocation != null) {
			debugMessage('show');
			this.map.addOverlay(this.homeLocation);

			this.setShowAddressLinks(true);
			$('location').style.display = 'block';
			$('locationList').innerHTML = '';
			$('locationList').insert({'top': this.homeLocation.getUserData()});
		}
	},

	/**
	 * Show loading Spinner
	 * @param {bool} a
	 */
	showSpinner: function(a) {
		debugMessage('show spinner: '+a);
		if ($('spinner'))
			if (a)
				$('spinner').show();
			else
				$('spinner').hide();
	},

	/**
	 * Request Marker on move or Zoom
	 */
	updateMarker: function() {
		debugMessage('update visible Markers');
		this.initMarker();
	},

	/**
	 * load marker for initial view
	 */
	initMarker: function() {
		debugMessage('load (init) visible Markers');
		if (this.updateRequest)
			this.updateRequest = false;
		else
			return;

		this.showSpinner(true);

		//this.setIsSearch(false);
		this.resetNameSearch();
		this.setLoadMarker(true);
		this.loadVisiblePoints(
			1,
			this.map.getBounds().getSouthWest().lat(),
			this.map.getBounds().getSouthWest().lng(),
			this.map.getBounds().getNorthEast().lat(),
			this.map.getBounds().getNorthEast().lng());
	},

	/**
	 * Clear Address choice
	 */
	clearChoice: function() {
		$('choice').getElementsByTagName('ul')[0].innerHTML = '';
		$('choice').style.display="none";
	},

	/**
	 * Clear Form errors
	 */
	clearError: function() {
		$('formError').innerHTML = '';
	},

	/**
	 * clear Sidebar
	 */
	clearSidebar: function() {
		$('sidebarList').innerHTML = '';
	},

	/**
	 * Determinate Coordinates from Address and request Markers
	 * @param {string} name
	 * @param {string} Address
	 * @param {string} range
	 */
	searchMarker: function(name, address, range) {
		debugMessage('search requested');
		this.clearChoice();
		this.clearError();

		if (name.blank() && address.blank()) {
			var li = new Element('li');
			li.innerHTML = 'Geben Sie bitte den Namen einer Klinik oder eine Adresse ein.';
			$('formError').insert({'bottom': li});
			return;
		}
		if (address.strip() != '') {
			debugMessage('Geocode Address');
			// geocode
			var geocoder = new GClientGeocoder();
			geocoder.setBaseCountryCode('de');

			geocoder.getLocations(address + ', germany', function(response){
				debugMessage('got response: '+response.Status.code);
				if (Object.isUndefined(response) || response.Status.code != 200) {
					var li = new Element('li');
					if (response.Status.code == 602) {
						li.innerHTML = 'Die eingegebene Adresse wurde nicht gefunden.';
					} else {
						li.innerHTML = 'Bei der Anfrage trat ein Fehler auf. Bitte versuchen Sie es sp&auml;ter erneut. ';
					}

					$('formError').insert({'bottom': li});
					return;
				}


				if (response.Placemark.length > 1) {
					debugMessage('mehrdeutiges Ergebnis');
					if (response.Placemark.length > this.maxAddress) {
						var li = new Element('li');
						li.innerHTML = 'Zu viele Ergebnisse für diese Adresse. Bitte pr&auml;zisieren Sie Ihre Auswahl.';
						$('formError').insert({'bottom': li});
					} else {
						for (var i = 0; i < response.Placemark.length; i++) {
							$('choice').style.display = "block";
							var ulTag = $('choice').getElementsByTagName('ul')[0];
							var litag = new Element('li');
							var atag = new Element('a');
							this.lastResponse = response;
							atag.innerHTML = this.prepareAddress(response.Placemark[i].address);
							atag.href = 'javascript:nothing()';
							atag.alt = 'lat=' + response.Placemark[i].Point.coordinates[1] +
							'&' +
							'lng=' +
							response.Placemark[i].Point.coordinates[0];

							Event.observe(atag, 'click', function(event){
								this.clearChoice();
								this.setHomeLocationAddress(Event.element(event).innerHTML);
								$('address').value = Event.element(event).innerHTML;
								var coords = Event.element(event).alt.toQueryParams();
								this.searchMarkerLatLng(name, coords['lat'], coords['lng'], range);
							}.bind(this));

							litag.insert({'bottom': atag});
							ulTag.appendChild(litag);
						}
					}
				} else
					if (response.Placemark.length == 1) {
						debugMessage('eindeutiges Ergebnis');
						this.setHomeLocationAddress(this.prepareAddress(response.Placemark[0].address));
						var coords = response.Placemark[0].Point.coordinates;
						var lat = coords[1];
						var lng = coords[0];
						this.searchMarkerLatLng(name, lat, lng, range);
					}
					else {
						$('formError').innerHTML = '<li><p>Die eingegebenen Suchparameter ergaben keinen Treffer.</p></li>';
					}
			}.bind(this));
		} else {
			debugMessage('search by name');
			this.searchMarkerLatLng(name, '', '', '');
		}
	},

	/**
	 * Prepare Marker search
	 * @param {string} name
	 * @param {float} lat
	 * @param {float} lng
	 * @param {Object} range
	 */
	searchMarkerLatLng: function(name, lat, lng, range){
		debugMessage('Startsearch with: name: '+name+'; lat: '+lat+'; lng: '+lng+'; range: '+range);
		this.showSpinner(true);
		debugMessage('check range');
		if (isNumeric(range)) {
			debugMessage('isnumeric');
			range = parseFloat(range);
			if (range > this.maxRange)
				range = this.maxRange;

			if (range < this.minRange)
				range = this.minRange;
		} else {
			debugMessage('!numeric');
			range = this.defaultRange;
		}
		
		if (name.strip() != "") {
			this.setNameSearch(name);
		} else
			this.resetNameSearch();

		if (!isNumeric(lat) || !isNumeric(lng)) {
			this.resetHomeLocation();
			$('range').value = '';
		} else {
			this.setHomeLocation(lat,lng);
			$('range').value = range;
		}

		

		
		this.loadSearchPoints(name, lat, lng, range);
	},

	/**
	 * Clear GMap and Components
	 */
	clear: function() {
		debugMessage('clear overlay');
		this.map.clearOverlays();
		this.clearChoice();
		this.clearError();
		this.clearSidebar();
	},

	/**
	 * Add a new Marker to Map
	 *
	 * @param {int} nr
	 * @param {string} html
	 * @param {float} lat
	 * @param {float} lng
	 * @param {int} type
	 */
	addMarker: function(nr, html, lat, lng, type) {
		debugMessage('AddPlace: '+nr+'; lat: '+lat+', lng: '+lng+', type: '+type+', html: '+html.escapeHTML());

		if (type > 0 || this.showNonSeracell) {
			if (Object.isNumber(lat) && Object.isNumber(lng)) {
				var point = new GLatLng(parseFloat(lat), parseFloat(lng));
				var marker;

				if (type) {
					marker = this.createMarker(point, SERACELL, html);
				} else {
					marker = this.createMarker(point, OTHER, html);
				}

				// add to map
				if (marker != null && this.map.getZoom() > this.minZoom) {
					//if (this.map.getBounds().containsLatLng(marker.getLatLng())) {
						this.map.addOverlay(marker);
						$('sidebarList').insert({'bottom': marker.getUserData()});
				//	} 
				}
			}
		}
	},

	zoomToFit: function() {
		debugMessage('zoomToFit');
		if (this.map.getMarkerCount() == 0)
			return;
		debugMessage('reallyZoom');
		this.setLoadMarker(false);
		var bounds = new GLatLngBounds();
		var marker = this.map.getFirstMarker();
		while (marker != null) {
			bounds.extend(marker.getLatLng());
			marker = this.map.getNextMarker();
		}
		if (this.homeLocation != null)
			bounds.extend(this.homeLocation.getLatLng());
		var zoom = this.map.getBoundsZoomLevel(bounds);

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

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

		this.map.setZoom(zoom);
   		this.map.setCenter(bounds.getCenter());
		//this.map.zoomToMarkers(10,5);
		this.setLoadMarker(true);
	}
});