	
	// request variables
	var requestCommand;
	var requestTarget;
	var requestCallbackFunction;

/*    $(window).load(function() {
	    $(document).ready(function() {
	        setDefaultPropertyTypeValues();
	        setDefaultDistrito('NEW');
	        setSearchRules();
	    });
	});
*/
    // Events
	$(document).ready(function() {

	    $('#pesquisamapa1').click(function() {
	        ShowMap();
	    });
	    $('#pesquisamapa2').click(function() {
	        ShowMap();
	    });
	    $('#escondermapa1').click(function() {
	        HideMap();
	    });
	    $('#escondermapa2').click(function() {
	        HideMap();
	    });
	});

	function ShowMap() {
	    // Show Map if it exists
	    if ($("#zonamapa").length) {
	        if ($('#zonamapa').is(':hidden')) {
	            $('#zonasitepromo').fadeOut('slow', function() {
	                $('#zonamapa').css('visibility', 'visible').hide().fadeIn('slow', function() { });
	            });
	        }
	    }
	}

	function HideMap() {
	    // Show Map if it exists
	    if ($("#zonasitepromo").length) {
	        if ($('#zonamapa').is(':visible')) {
	            $('#zonamapa').fadeOut('slow', function() {
	                $('#zonasitepromo').css('visibility', 'visible').hide().fadeIn('slow', function() { });
	            });
	        }
	    }
	}

	function loadMap() {
	        if (GBrowserIsCompatible()) {
	            // Subscribe event ZOOMEND
	            GEvent.addListener(map, "zoomend", function(oldzoom, zoom) {
	                //
	                loadingTooltip.style.visibility = 'visible';
	                // Request Properties Ajax Call
	                RequestProperties(map.getBounds());
	            });

	            // Subscribe event MOVEEND
	            GEvent.addListener(map, "dragend", function() {
	                //
	                loadingTooltip.style.visibility = 'visible';
	                // Request Properties Ajax Call
	                RequestProperties(map.getBounds());
	            });

	            // Request Properties Ajax Call
	            RequestProperties(map.getBounds());
	        }
	}

	function RequestProperties(bounds){
		// Strip Bounds
		var southWestPoint = bounds.getSouthWest();
		var northEastPoint = bounds.getNorthEast();
		var SWLat = southWestPoint.lat();//-3;
		var SWLng = southWestPoint.lng();
		var NELat = northEastPoint.lat();//+3;
		var NELng = northEastPoint.lng();

		// Set ajax call
		var url = wServiceRequesterURL;
		// Set command type
		if(map.getZoom() <= 6){requestCommand = 'REQUEST_PROPERTIES_TOP_LEVEL'; requestTarget = 'TOPLEVEL_DISTRITOS'; requestCallbackFunction = Properties_ShowResponse_Toplevel;}
		if(map.getZoom() > 6 && map.getZoom() <= 8){requestCommand = 'REQUEST_PROPERTIES_TOP_LEVEL'; requestTarget = 'TOPLEVEL_CONCELHOS'; requestCallbackFunction = Properties_ShowResponse_Toplevel;}
		if ($("#propertytype").val() != 0) {
		    if (map.getZoom() >= 9) { requestCommand = 'REQUEST_PROPERTIES'; requestTarget = 'PROP_' + $("#propertytype").val(); requestCallbackFunction = Properties_ShowResponse; }
		} else {
		    if (map.getZoom() >= 9) { requestCommand = 'REQUEST_PROPERTIES'; requestTarget = 'DESTAQUES'; requestCallbackFunction = Properties_ShowResponse; }
		}
		// set request params
		var pars = 'COMMAND='+requestCommand+'&TARGET='+requestTarget+'&SWLatitude='+SWLat+'&SWLongitude='+SWLng+'&NELatitude='+NELat+'&NELongitude='+NELng;

		// ajax request
		$.ajax({
		    type: "GET",
		    url: url,
		    data: pars,
		    success: requestCallbackFunction
		});
	}
	
	function Properties_ShowResponse(transport){
		// read Xml nodes
		var markerNodes = transport.getElementsByTagName('markers')[0];
		// Clear map markers
		top.map.clearOverlays();
		// Create Markers
		if (markerNodes != null) {
		    for (var i = 0; i < markerNodes.childNodes.length; i++) {//percorrendo os filhos do nó
		        if (markerNodes.childNodes[i].nodeType == 1) {//ignorar espaços em branco
		            var newLat = markerNodes.childNodes[i].attributes[0].value;
		            var newLng = markerNodes.childNodes[i].attributes[1].value;
		            var newID = markerNodes.childNodes[i].attributes[2].value;
		            var newName = markerNodes.childNodes[i].attributes[3].value;
		            var newType = markerNodes.childNodes[i].attributes[4].value;
		            var newTitle = markerNodes.childNodes[i].attributes[5].value;
		            var newLocation = markerNodes.childNodes[i].attributes[6].value;
		            var newArea = markerNodes.childNodes[i].attributes[7].value;
		            var newValor = markerNodes.childNodes[i].attributes[8].value;
		            var newIsDestaque = markerNodes.childNodes[i].attributes[9].value;
		            var point = new GLatLng(newLat, newLng);

		            // Create Property icon
		            var newIcon = new GIcon();

		            // Check Property Type
		            if (newType.toUpperCase() == 'ALOJAMENTO') {
		                newIcon.image = "images/bannercasapreto.gif";
		            }
		            if (newType.toUpperCase() == 'COMERCIAL') {
		                newIcon.image = "images/bannercasaazul.gif";
		            }
		            if (newType.toUpperCase() == 'TURISMO RURAL') {
		                newIcon.image = "images/bannercasaverde.gif";
		            }

		            newIcon.iconSize = new GSize(16, 16);
		            newIcon.iconAnchor = new GPoint(6, 20);
		            newIcon.infoWindowAnchor = new GPoint(5, 1);

		            // Create Marker
		            var marker = new GMarker(point, newIcon);
		            marker.tooltip = '<div class="googletooltip">&nbsp;<b>' + newName + '</b><br/>&nbsp;' + newTitle.substring(0, 25) + '...<br/>&nbsp;' + newLocation + '</div>';
		            // 
		            AddGMapEvents(marker, newID);
		            // 
		            map.addOverlay(marker);
		        }
		    }
		}
		loadingTooltip.style.visibility = 'hidden';

	}
	
	function Properties_ShowResponse_Toplevel(transport){
		// read Xml nodes
		var markerNodes = transport.getElementsByTagName('markers')[0];
		// Clear map markers
		top.map.clearOverlays();
		// Create Markers
		if (markerNodes != null) {
		    for (var i = 0; i < markerNodes.childNodes.length; i++) {//percorrendo os filhos do nó
		        if (markerNodes.childNodes[i].nodeType == 1) {//ignorar espaços em branco
		            var newLat = markerNodes.childNodes[i].attributes[0].value;
		            var newLng = markerNodes.childNodes[i].attributes[1].value;
		            var newName = markerNodes.childNodes[i].attributes[2].value;
		            var newTotal = markerNodes.childNodes[i].attributes[3].value;

		            // create GPoint
		            var point = GetMapPoint(newLat, newLng);

		            // Create Property icon
		            var newIcon = new GIcon();
		            if (map.getZoom() <= 6) { newIcon.image = "images/flag_green.gif"; }
		            if (map.getZoom() > 6 && map.getZoom() <= 8) { newIcon.image = "images/flag_blue.gif"; }
		            newIcon.iconSize = new GSize(16, 16);
		            newIcon.iconAnchor = new GPoint(6, 20);
		            newIcon.infoWindowAnchor = new GPoint(5, 1);

		            // Create Marker
		            var marker = new GMarker(point, newIcon);
		            // Set marker tooltip
		            if (map.getZoom() <= 6) { marker.tooltip = '<div class="googledistritotooltip">&nbsp;<b>Distrito: ' + newName + '</b><br/>&nbsp;Imóveis: ' + newTotal + '</div>'; }
		            if (map.getZoom() > 6 && map.getZoom() <= 8) { marker.tooltip = '<div class="googledistritotooltip">&nbsp;<b>Concelho: ' + newName + '</b><br/>&nbsp;Imóveis: ' + newTotal + '</div>'; }

		            // 
		            AddGMapEvents_Toplevel(marker);
		            // 
		            map.addOverlay(marker);
		        }
		    }
		}
		loadingTooltip.style.visibility='hidden';
	}
	
	function AddGMapEvents(marker, id){
		GEvent.addListener(marker, "click", function() {
		    //window.location = mainURL + 'propertydetails.asp?ID=' + id;
		    window.open(mainURL + 'propertydetails.asp?ID=' + id);
		});
		GEvent.addListener(marker,"mouseover", function() {
				ShowTooltip(marker);
		}); 
		GEvent.addListener(marker,"mouseout", function() {
				tooltip.style.visibility='hidden';
		}); 
	}
	
	function AddGMapEvents_Toplevel(marker){
		GEvent.addListener(marker, "click", function() {
				var newZoom;
				if(map.getZoom() <= 6){newZoom = 8;}
				if(map.getZoom() > 6 && map.getZoom() <= 8){newZoom = 9;}
				top.map.setCenter(marker.getPoint(), parseInt(newZoom));
		});
		GEvent.addListener(marker,"mouseover", function() {
				ShowTooltip(marker);
		}); 
		GEvent.addListener(marker,"mouseout", function() {
				tooltip.style.visibility='hidden';
		}); 
	}

    // ====== This function displays the tooltip ======
	// it can be called from an icon mousover or a side_bar mouseover
	function ShowTooltip(marker) {
		tooltip.innerHTML = marker.tooltip;
		var point=map.getCurrentMapType().getProjection().fromLatLngToPixel(map.fromDivPixelToLatLng(new GPoint(0,0),true),map.getZoom());
		var offset=map.getCurrentMapType().getProjection().fromLatLngToPixel(marker.getPoint(),map.getZoom());
		var anchor=marker.getIcon().iconAnchor;
		var width=marker.getIcon().iconSize.width;
		var height=tooltip.clientHeight;
		var pos = new GControlPosition(G_ANCHOR_TOP_LEFT, new GSize(offset.x - point.x - anchor.x + width, offset.y - point.y -anchor.y -height)); 
		pos.apply(tooltip);
		tooltip.style.visibility="visible";
	}
	
	function GetMapPoint(latitude, longitude){
		if((latitude != '0' && longitude != '0') && (latitude.length > 0 && longitude.length > 0)){
			if(latitude.indexOf(',') > -1){latitude = latitude.replace(',','.');}
			if(longitude.indexOf(',') > -1){longitude = longitude.replace(',','.');}
			
			return new GLatLng(latitude, longitude);
		}
	}

	function SetMapPoint(latitude, longitude, zoom){
		if((latitude != '0' && longitude != '0') && (latitude.length > 0 && longitude.length > 0)){
			if(latitude.indexOf(',') > -1){latitude = latitude.replace(',','.');}
			if(longitude.indexOf(',') > -1){longitude = longitude.replace(',','.');}
			if(top.map != null){
				if(longitude < -10){if(parseInt(zoom) > 10){zoom = '10';}}
				top.map.setCenter(new GLatLng(latitude, longitude), parseInt(zoom));
			}
		}
	}
