function mapinit() {

	$.ajaxSetup({beforeSend: function(XMLHttpRequest) {
		$("#spotlightSpinner").show();
	}, complete: function(XMLHttpRequest, textStatus) {
		$("#spotlightSpinner").hide();
	}});
	
	var zIcon = new GIcon(G_DEFAULT_ICON, CLOUD_FRONT + 'static/maps/icons/markerz.png');
	var fPlaceFieldText = 'Start typing the name of a city or town...';
	
	//http://docs.jquery.com/Plugins/Autocomplete/autocomplete#url_or_dataoptions
	var autocompleteOptions = { delay: 400, minChars: 3, selectFirst: false};
	var ignoreMapMove = false;
	var previousNorthEast = undefined;
	var gMoveListener = undefined;

	loadConveyor();
	
	if (GBrowserIsCompatible()) {

		//User profile map
		if($("#userProfileMap").length == 1) {
			
			var userProfileMap = new GMap2(document.getElementById("userProfileMap"), {size:new GSize(674,280)});
			userProfileMap.setCenter(new GLatLng(31.95216223802497, 9.140625), 1);	
			userProfileMap.setUIToDefault();
			userProfileMap.disableScrollWheelZoom();
			
			$("div.zubBadge", "#sliderContent").click(function() {
				
				var latlng = new GLatLng($("span.lat",this).text(), $("span.lng",this).text());
				userProfileMap.setCenter(latlng, 12);
				
			}).each(function() {
				
				//Don't add the 'you can buy x more this week' to the map.
				if(!$(this).hasClass('suggestion')) {
					var latlng = new GLatLng($("span.lat",this).text(), $("span.lng",this).text());
					mkr = new GMarker(latlng, {title: $('p.title a', this).text(), icon: zIcon});
					
					mkr.bindInfoWindowHtml('<div class="zubBadge sold" style="margin:0">' + $(this).html() + '</div>');
					
					GEvent.addListener(mkr, "click", function(latlng) {
						userProfileMap.setCenter(latlng, 12);
					});
					
					userProfileMap.addOverlay(mkr);
				}
				
			});
			
		}
		
		//Main spotlight map.
		var map = undefined;
		
		if($("#spotlightMap").length == 1) {
			map = new GMap2(document.getElementById("spotlightMap"),  {size:new GSize(678,256)});
		} else {
			map = new GMap2(document.getElementById("spotlightBasketMap"),  {size:new GSize(426,356)});
		}
		map.setCenter(new GLatLng(31.95216223802497, 9.140625), 1);	
		map.setUIToDefault();
		map.disableScrollWheelZoom(); 
		
		//For finding places with Google.
		var geocoder = new GClientGeocoder();
		
		//Setup a new marker manager, this lets us put lots of pins on!
		mgr = new MarkerManager(map);

		//When the google map is moved.	
		gMoveListener = GEvent.addListener(map, "moveend", function() {
			mapMoved();
		});
	
		GEvent.addListener(map, "zoomend", function(oldLevel, newLevel) {
			
			//console.debug("Old:"+oldLevel);
			//console.debug("New:"+newLevel);
			//mgr.refresh();
			mgr.clearMarkers();
			previousNorthEast = undefined;
			if(oldLevel > 10 && newLevel <= 10) {
				showPanel("#spotlightGetGoing");
			}
		});
		
		bindAutoComplete();
		bindLuckyDip();
		
		//Attached code to Find button
		$("#formFindAPlace").submit(function(e) {
			e.preventDefault();
			showAddress($("#spotlightSearchField").val());
		});

		if($("#zublat").length == 1) {

			var zubLat = $("#zublat").text();
			var zubLng = $("#zublng").text();
			
			if (true || (zubLat != 0 && zubLng != 0)) //this check is wrong. 0 is a valid long and lat.
			{
				centerLatLng(zubLat, zubLng);
				
				//Setup the zub map.
				if($("#zubMap").length==1) 
				{

                	var zubMap = new GMap2(document.getElementById("zubMap"));
					zubMap.setCenter(new GLatLng(zubLat, zubLng), 12);
					zubMap.setUIToDefault();
	
					var latlng = new GLatLng(zubLat, zubLng);
					mkr = new GMarker(latlng, {title: $("h2.title a").text(), icon: zIcon});
						
					zubMap.addOverlay(mkr);		
				}
			}
			
		}

		mgr.refresh();
	}

	function mapMoved() {
	
		//console.debug("Map moved");
		$("#spotlightNoResults").hide();
		$("#spotlightSearchField").get(0).blur();
		
		//We might have set a flag somewhere in code to prevent this event running.
		if(ignoreMapMove) {
			//debug("Map move ignored");
			return false;
		}
		
		//Get the Zom level.
		var zoom = map.getZoom();
		
		//if(zoom > 10) {
		
		var center = map.getCenter();
		var bounds = map.getBounds();
		var southWest = bounds.getSouthWest();
		var northEast = bounds.getNorthEast();
		var infoWindow = map.getInfoWindow();			//Get current infor window.

		//If we have a previous lat/lng, see if it was a big move. If it was only a little move, don't bother ajaxing by returning from this function.
		if(previousNorthEast!=undefined) {
		
			var latspan = (northEast.lat() - southWest.lat()) / 2;
			var lngspan = (northEast.lng() - southWest.lng()) / 2;

			var bigMove = false;
			
			if(previousNorthEast.lat() < (northEast.lat() - latspan) || previousNorthEast.lat() > (northEast.lat() + latspan)) {
				bigMove = true;					
			}
			
			if(previousNorthEast.lng() < (northEast.lng() - lngspan) || previousNorthEast.lng() > (northEast.lng() + lngspan)) {
				bigMove = true;					
			}
				
			if(!bigMove) {
				return false;
			}
		}
		
		previousNorthEast = northEast;
		
		//Give geocoder results a slant based on the current viewport.
		geocoder.setViewport(bounds);
		geocoder.reset();
		
		//When we're zoomed in closer than level 10.
		if(zoom > 10) {

			//console.debug("Loading pins");
			
			$("#spotlightGetGoing2").hide();
			
			
			
			//Load the Zub pins for the given viewport.
			$.getJSON("/zw/ajax/zubs-geo-area/?clat=" + center.lat() + "&clng=" + center.lng() + "&swlat=" + southWest.lat() + "&swlng=" + southWest.lng() + "&nelat=" + northEast.lat() + "&nelng=" + northEast.lng() + "&zoom=" + zoom,
				function(data) {		
					
					$("#spotlightSpinner").show();
					if(data.length==0) {
						showPanel("#spotlightGetGoing");
						return false;
					}
					
					var viewportMarkers = [];

					$.each(data, function(i,item){

						
						var latlng = new GLatLng(item.T, item.G);
						
						//Is this a Zub or a place available to buy?
						if(item.Z==undefined) {
							mkr = new GMarker(latlng, {title: item.N});							//Place available to buy.
							$("div.zubBadge","#spotlightResultTemplate").attr("class", "zubBadge forsale");
							
							if(LOGGED_IN) {
								$("p.link","#spotlightResultTemplate").html('<a href="/register/basket/?zid=' + item.I + '">Buy</a>');
								$("p.title","#spotlightResultTemplate").html('<strong><a href="/register/basket/?zid=' + item.I + '" title="'+item.N+'">' + trimString(item.N,15) + '</a></strong>&nbsp;<img class="flag" src="' + CLOUD_FRONT + 'static/flags/16x13/' + item.O + '.png" />');
							} else {
								$("p.link","#spotlightResultTemplate").html('<a href="/zw/auth?redirect=' + escape('/register/basket/?zid=' + item.I) + '&zid=' + item.I + '&tmessage=login-to-buy" class="lnkLogin">Buy</a>');
								$("p.title","#spotlightResultTemplate").html('<strong><a href="/zw/auth?redirect=' + escape('/register/basket/?zid=' + item.I) + '&tmessage=login-to-buy" class="lnkLogin" title="'+item.N+'">' + trimString(item.N,15) + '</a></strong>&nbsp;<img class="flag" src="' + CLOUD_FRONT + 'static/flags/16x13/' + item.O + '.png" />');
							}
							
							$("p.info","#spotlightResultTemplate").html('For Sale');
						} else {
							mkr = new GMarker(latlng, {title: item.N, icon: zIcon});			//Zub.
							$("div.zubBadge","#spotlightResultTemplate").attr("class", "zubBadge sold");
							if(item.F == 1) {
								$("p.info","#spotlightResultTemplate").html(item.F + ' follower');
							} else {
								$("p.info","#spotlightResultTemplate").html(item.F + ' followers');
								
							}
							$("p.link","#spotlightResultTemplate").html('<a href="/'+item.K+'">Visit</a>');
							$("p.title","#spotlightResultTemplate").html('<strong><a href="/'+item.K+'" title="'+item.N+'">' + trimString(item.N,15) + '</a></strong>&nbsp;<img class="flag" src="' + CLOUD_FRONT + 'static/flags/16x13/' + item.O + '.png" />');
							
						}
							
						//When a user clicks a pin, we want to find the nearby pins and load them in the side.
						GEvent.addListener(mkr, "click", function(latlng) {
							loadResults(viewportMarkers, latlng);
						});
						
						$("a.icon","#spotlightResultTemplate").html('<img src="' + CLOUD_FRONT + 'static/zubs/levels/' + item.L + '.png" />');
						
						infoWindowHtml = $("#spotlightResultTemplate").html();
						mkr.bindInfoWindowHtml(infoWindowHtml);

						mgr.addMarker(mkr, zoom);
							
						viewportMarkers.push({html: infoWindowHtml, marker: mkr});
						
					});
					
					
					//If the results pane isn't visible yet, pop up the info window for the marker closest to the middle.
					if($("#spotlightResults").is(':hidden')) {
						
						showPanel("#spotlightResults");
						
						//Find distance of each marker from the middle.
						for (i=0; i<viewportMarkers.length; i++) {
							viewportMarkers[i].dist = viewportMarkers[i].marker.getLatLng().distanceFrom(center);
					    }
						
						//Sort them.
						viewportMarkers.sort(function (a,b) {
							return (a.dist - b.dist);
						});
												
						//Show info window - we put in a timeout to prevent another ajax map move.
						ignoreMapMove = true;
						setTimeout(function() {
							ignoreMapMove = false;
						},500);
						viewportMarkers[0].marker.openInfoWindowHtml(viewportMarkers[0].html);
						
						//Mimic marker clock.
						loadResults(viewportMarkers, viewportMarkers[0].marker.getLatLng());
						
					}		
					
					//If the info window isn't displayed, load results orientated around the center.
					if(infoWindow.isHidden()) {
						loadResults(viewportMarkers, center);
					} else {
						loadResults(viewportMarkers, infoWindow.getPoint());	//Results loaded around the info window.
					}
					
					$("#spotlightSpinner").hide();
					
				});
			
		}
		
		//console.debug("Zoom:" + zoom);
		//console.debug("SW:"+southWest);
		//console.debug("NE:"+northEast);
		//console.debug("CENTER:"+center.toString());
		
	}
	
	function loadResults(viewportMarkers, latlng) {
		
		//Loop through each of the viewport pins and find how close it is to the lat/lng specified.
		for (i=0; i < viewportMarkers.length; i++) {
			viewportMarkers[i].dist = viewportMarkers[i].marker.getLatLng().distanceFrom(latlng);
	    }
		
		//Sort the pins with closest distance first.
		viewportMarkers.sort(function (a,b) {
			return (a.dist - b.dist);
		});
		
		//if there is no nearby place, do not show 'Nearby...'
		if( viewportMarkers.length < 2) {
			//hide nearby places
			$("#spotlightResults h5").hide();
		}else{
			//show
			$("#spotlightResults h5").show();
		}
		
		//Load the results pane with the first 3 closest places.
		$("#spotlightResult1").html('');
		$("#spotlightResult2").html('');
		$("#spotlightResult3").html('');// empty the content of the array(Ferenc)
		for (i=0; i<4; i++) {
			$("#spotlightResult" + i).html('');
			$("#spotlightResult" + i).html(viewportMarkers[i].html);
			
			if(i > 0) {
				$("div.zubBadge","#spotlightResult" + i).addClass('mini');
			}
			$("#spotlightSpinner").hide();
		}
		
		showPanel("#spotlightResults");
		
	}
	
	function prepForFind() {
		var infoWindow = map.getInfoWindow();
		infoWindow.hide();
		previousNorthEast = undefined;
		showPanel("#spotlightGetGoing");
		$("#spotlightSearchField").get(0).blur();
	}
	
	function showAddress(address) {
		
		prepForFind();
		
		//Make sure we don't have a previous auto complete in the box.
		if($("#spotlightAutoCompleteLatLng").val()!='') {
			centerOnAutoCompleteLatLng();
			return false;
		}
				
		if (geocoder) {
			geocoder.getLocations(
				address,
				function(locations) {
					
					//Did Google find something?
					if(locations.Placemark==undefined) {
						showPanel("#spotlightNoResults");

					} else {
						
						//Yes... one result or many?
						if(locations.Placemark.length == 1) {
							
							//One result
							// Retrieve the latitude and longitude
							centerLatLng(locations.Placemark[0].Point.coordinates[1], locations.Placemark[0].Point.coordinates[0]);
						      
							return false;
							
						} else {
							
							//Many results - show did you mean?
							$("#spotlightDidYouMeanSuggestions").html("");
							
							//Loop through each of the locations.
							$.each(locations.Placemark, function(i,item) { 
								$("#spotlightDidYouMeanSuggestions").append("<li><a href=\"#" + item.id + "\">" + item.address + "</a></li>");
							});
							
							showPanel("#spotlightDidYouMean");
							
							$("#spotlightDidYouMeanSuggestions").wrapInner("<ul></ul>");
							
							//Attach action to did you mean links
							$("a", "#spotlightDidYouMeanSuggestions").live("click", function(e) {
								
								e.preventDefault();
								
								//Get the ID of the suggestion that was clicked.
								var id = $(this).attr("href").replace(/^(.*#)/, "");

								//Loop through the locations returned and jump the map to the selected point.
								$.each(locations.Placemark, function(i,item) { 
									if(item.id == id) {
										
										centerLatLng(item.Point.coordinates[1], item.Point.coordinates[0]);
										return false;
									}
								});

								return false;
							});
							
						}
						
						
						
					}
					
				});
	    }
	}

	function showPanel(idToShow) {
		$("div.spotlightResultPanel").hide();
		$(idToShow).show();
		//console.debug(idToShow);
	}
	
	function centerLatLng(lat, lng) {
		// Retrieve the latitude and longitude
		point = new GLatLng(lat, lng);
		// Center the map on this point
		map.setCenter(point, 12);
	}
	
	function bindAutoComplete() {
		
		if($("#spotlightSearchField").val()==''){
			$("#spotlightSearchField").val(fPlaceFieldText);
		}
		
		//For the search field, setup the text inside and attach the autocomplete.
		$("#spotlightSearchField").click(function(){
			if($(this).val()==fPlaceFieldText){
				$(this).val('');
			}
		}).blur(function(){
			/*if($(this).val()==''){
				$(this).val(fPlaceFieldText);
			}*/
		}).autocomplete('/zw/ajax/location-autocomplete/',autocompleteOptions).result(function(event, data, formatted) {
			//When an autocomplete result is selected.
			if (data) {
				prepForFind();
				
				//Put auto complete value in to hidden field for later use.
				$("#spotlightAutoCompleteLatLng").val(data[1]);
				
				centerOnAutoCompleteLatLng();
			}
		}).keydown(function() {
			$("#spotlightAutoCompleteLatLng").val('');
		});
		
	}
	
	function bindLuckyDip() {
		
		var randomnumber=Math.floor(Math.random()*11);
		
		$("#btnSpotlightLuckyDip").click(function(e){
			e.preventDefault();
			$.getJSON("/zw/ajax/random-location/?r="+randomnumber,
				function(data){
					prepForFind();
					fPlaceFieldText = data.QUESTION;
					$("#spotlightSearchField").val(fPlaceFieldText).effect("highlight", {color:"#EB1049"}, 500);;                                                                                                                                   
					centerLatLng(data.LATITUDE, data.LONGITUDE);
			});
		});
		
	}
	
	function centerOnAutoCompleteLatLng() {
		
		nameiso=$("#spotlightAutoCompleteLatLng").val().split(",");
		
		$.getJSON("/zw/ajax/zubs-auto-complete/?name=" + nameiso[0] + "&iso=" + nameiso[1],
				
				function(data){
					
					if(data.length == 1){
					
						centerLatLng(data[0].T, data[0].G);
						
					} else {

						var bounds = new GLatLngBounds();
						
						GEvent.removeListener(gMoveListener);
						
						showPanel("#spotlightTooMany");
						
						$.each(data, function(i,item){
							
							//var zIcon = new GIcon(G_DEFAULT_ICON, CLOUD_FRONT + 'static/maps/icons/markerz.png');
							var latlng = new GLatLng(item.T, item.G);
							
							bounds.extend(latlng);
							var zIcon = new GIcon(G_DEFAULT_ICON, CLOUD_FRONT + 'static/maps/icons/magnify.png');
							
							zIcon.shadow = CLOUD_FRONT + 'static/maps/icons/magnifyshadow.png';
							zIcon.iconSize = new GSize(28.0, 28.0);
						    zIcon.shadowSize = new GSize(43.0, 28.0);
						    
							var zSize = new GSize(24, 24);
							zIcon.iconSize = zSize;
							mkr = new GMarker(latlng, {icon: zIcon});
							
							GEvent.addListener(mkr, 'click', function(latlng) {
								map.clearOverlays();
								centerLatLng(latlng.lat(), latlng.lng());
							});
							
							map.addOverlay(mkr);
							
							//getBoundsZoomLevel();
						});
				
						 map.setZoom(map.getBoundsZoomLevel(bounds));
						 map.setCenter(bounds.getCenter());
						 
						 gMoveListener = GEvent.addListener(map, "moveend", function() {
							mapMoved();
						 });
						 
					}
					
			
				});
	
	}
	
	
	
}


function loadConveyor() {
	
	//vars
	var conveyor = $(".content-conveyor", $("#sliderContent"));
	var singleItem = $(".zubBadge", $("#sliderContent"));
	
	if(singleItem.length > 3) {
		itemWidth = 230;
		
		//set length of conveyor
		conveyor.css("width", singleItem.length * itemWidth);
		
	    //config
	    var sliderOpts = {
		  max: (singleItem.length * itemWidth) - 699,
	      slide: function(e, ui) { 
	        conveyor.css("left", "-" + ui.value + "px");
	      }
	    };
	
	    //create slider
	    $("#slider").slider(sliderOpts);
	}
}
