// <--
// Set the global variables -------------------------------------------------------------------
var map;
var cluster;
var baseIcon;
var currentZoom;
var currentBounds;				
var debug = false;
var response = new Object();
var json = new Object();
var jsonUrl = '/scripts/load_data.php';
var clusterMarkerPath = '/media/images/maps/cluster.php';
var resultsBarWidth = 380;
var loaded = 0;
var gmarkers = [];
var markerClusterer;

// A function to create the marker and set up the event window ---------------------------------------
function createPoint(item) { 
	// Create new icon 
	newPointIcon = new GIcon(baseIcon); 
	newPointIcon.image = markerPath + item.icon;
	newPointIcon.iconAnchor = new GPoint(5, 5);
	newPointIcon.infoWindowAnchor = new GPoint(7, 6);
		
	//iconwidth:12, iconheight:10, iconanchor:[5,5], infowindowanchor:[6,5]
	
	// Retrieve the latitude and longitude
	var point = new GLatLng(item.lat, item.lng);
	var marker = new GMarker(point, newPointIcon);
	
	// Add information to marker on click 
	GEvent.addListener(marker, "click", 
		function() {
			//marker.openInfoWindowHtml(info+'<br />'+country+'<br /><br /><a href="javascript:loadPoint('+id+')">View the info div in the Facebox</a>');
			marker.openInfoWindowHtml('<a href="javascript:loadPoint(' + item.id + ');">' + item.name + '</a><br />' + item.info + '<br /><img src="/sites/' + site +'/adverts/gold.gif" border="0" style="margin:7px 10px 2px 10px;" width="220" height="40" />');
		}
	);
	
	// Save the info we need to use later for the side bar
    gmarkers.push(marker);

	// Add item to side bar
	$("div#mapResultsDisplay").append('<span><a href="javascript:openGoogleBubble(' + (gmarkers.length-1) + ')">' + item.name + '</a> ' + item.category + '</span>');

	return marker;
} 

// This function picks up the click and opens the corresponding info window
function openGoogleBubble(i) {
    closePoint();
	GEvent.trigger(gmarkers[i], "click");
}

function createCluster(item) { 
	// Calculate the width of the icon
	if (item.width == 0) {
		width = 18 + parseInt(item.info.length) * 5;
	} else {
		width = item.width;	
	}
	width_half = parseInt(width/2);
	
	// Create custom icon
	newClusterIcon = new GIcon(baseIcon); 
	newClusterIcon.image = clusterMarkerPath + '?text=' + item.info + '&total=' + item.total + '&width=' + width;
	newClusterIcon.iconSize = new GSize(width, 28); 
	newClusterIcon.iconAnchor = new GPoint(width_half, 14);
	
	// Retrieve the latitude and longitude
	var point = new GLatLng(item.lat, item.lng); 
	var marker = new GMarker(point, newClusterIcon);
	
	// Add information to marker on click 
	GEvent.addListener(marker, "click", 
		function() {
			// Set the country in the session
			$.get("/scripts/search_save.php", { country: item.id } );
						
			map.setCenter(new GLatLng(item.lat, item.lng), parseInt(item.zoom));
		}
	);
	
	return marker;
} 

// Load the data for this site ----------------------------------------------------------------------
function loadData() {
	// Show loading message
	$("div#mapSearch").hide();
	$("div#mapLoading").show();
	
	// Clear all overlays
	clearMapOverlays();
	
	// Get current zoom
	currentZoom = map.getZoom();
	
	// Empty results bar
	$("div#mapResultsDisplay").empty();
	
	// Show hide default text
	if (currentZoom > startZoom) {
		$("div#mapResultsDefault").hide();
	} else {
		$("div#mapResultsDefault").show();
	}
	
	// Wait while the Google map layers are loading
	$("#progressMessage").text('Loading Google map layers...');
	//waitForData();
		
	// Now show that the map points are loading
	$("#progressMessage").text('Loading map points...');
		
	// Create the boundary for the data to provide 
	bounds = map.getBounds(); 
	currentBounds = bounds;
	southWest = bounds.getSouthWest(); 
	northEast = bounds.getNorthEast();
	
	boundsVars = 'nelng=' + northEast.lng() + '&nelat=' + northEast.lat() + '&swlng=' + southWest.lng() + '&swlat=' + southWest.lat();
	var searchVars = 'zoom=' + currentZoom + '&startzoom=' + startZoom;
	
	// Log the URL for testing 
	if (debug == true) {
		GLog.writeUrl(jsonUrl + '?' + boundsVars + '&' + searchVars); 
	}
	
	// Get the data
	url = jsonUrl +'?' + boundsVars + '&' + searchVars;
	//alert(url);
	//alert('davo');
	
	$.getJSON(url, function(data) { 
			num_points = 0;
			num_displayed = 0;
			
			// Change loading message
			$("#progressMessage").text('Plotting points...');
			json = data;
			
			$.each(data.items, 
				function(i, item){
					if (item.type == 'cluster') { 
						num_points += parseInt(item.total);
						marker = createCluster(item);
						map.addOverlay(marker);
					} else {
						num_displayed++; 
						num_points++;
						marker = createPoint(item);
					}
					map.addOverlay(marker);  // comment this out this when using the cluster plugin
				}
			);
			
			// Add the cluster points to the map
			//options = { gridSize: 20, maxZoom: 10 };
            //markerClusterer = new MarkerClusterer(map, gmarkers, options);
            
			$("div#mapResultsDisplay").append('<div class="clear"></div>');
			
			// Set the total points and number displayed message
			$("#mapMessagesPoints").text(num_points);
			$("#mapMessagesDisplayed").text(num_displayed);
			
			// Show completed message and hide loader
			$("#mapLoading").hide();
			$("#mapSearch").show();
		}
	);
}

// Load the data point -------------------------------------------------------------------------
function loadPoint(id) {
	// Close the map and open the info pane
	//$("#map").hide("slow");
	//$("#mapPointInfo").show("slow");
	$("#map").css('display', 'none');
	$("#mapPointInfo").css('display', 'block');
	
	// Show loader while we are loading results
	$("#mapPointInfo").html('<p align="center">Loading <img src="/media/images/icons/dots.gif" alt="Loading" border="0" /></p>');
	
	// Load the data point
	$("#mapPointInfo").load("/scripts/load_point.php", {cmd: 'submit', id: id}, initFancyBox);
	
	
	/*
	$.ajax({
		type: "POST",
		url: "/scripts/load_point.php",
		data: "id="+ id +"&cmd=submit",
		success: 
			function(data){
				$("#mapPointInfo").html(data);
				//alert( "Data Saved: " + msg );
			}
	});
	*/
}

function closePoint() {
	// Close the nfo pane and show the map
	if ($('#mapPointInfo').is(':visible')) {
    	$("#mapPointInfo").css('display', 'none');
    	$("#map").css('display', 'block');
    }
    	
	resizeMap();
}

// If the map moves or zoom changes --------------------------------------------------------------
function mapMoveEnd() { 
	var newbounds = map.getBounds(); 
	var percentmoved_vertically = Math.abs((newbounds.getSouthWest().lat()-currentBounds.getSouthWest().lat()) / (currentBounds.getNorthEast().lat()-currentBounds.getSouthWest().lat())); 
	var percentmoved_horizontally = Math.abs((newbounds.getSouthWest().lng()-currentBounds.getSouthWest().lng()) / (currentBounds.getNorthEast().lng()-currentBounds.getSouthWest().lng())); 
		
	// If the map has not moved much do nothing
	//var tolerance = 0.02;
	var tolerance = 0.1;
	if (percentmoved_vertically < tolerance && percentmoved_horizontally < tolerance && map.getZoom() == currentZoom) { 
		return; 
	} 
	
	// Map has moved significantly reload markers
	loadData();
} 

function mapZoomChange() { 
	// If we have changed zoom levels remove the cluster icons
	clearMapOverlays();
	
	// Load new points
	loadData();
} 

// Clear map of points
function clearMapOverlays() {
    //alert('clear');
    map.clearOverlays(); 
    
	if(markerClusterer != null) {
        markerClusterer.clearMarkers();
    }
    
    gmarkers =  [];
}

// Resizing -----------------------------------------------------------------------------------------
function windowHeight() {
	// Standard browsers (Mozilla, Safari, etc.)
	if (self.innerHeight)
		return self.innerHeight;
	// IE 6
	if (document.documentElement && document.documentElement.clientHeight)
		return document.documentElement.clientHeight;
	// IE 5
	if (document.body)
		return document.body.clientHeight;
	// Just in case.
	return 0;
}

function resizeMap() {
	//alert(document.getElementById('mapInfo').offsetHeight);
	var mapheight = windowHeight() - document.getElementById('mapInfo').offsetHeight - document.getElementById('header').offsetHeight - 5 - 20; // 5 for border and 20 for padding
	var resultsheight = windowHeight() - document.getElementById('header').offsetHeight - 5;
	
	document.getElementById('map').style.height = mapheight + 'px';
	document.getElementById('mapPointInfo').style.height = mapheight + 'px';
	document.getElementById('mapResults').style.height = resultsheight  + 'px';
	
	//alert(mapheight +' '+ resultsheight);
}

/*
function resizeMap() {
	var m = $("#map"); 
	var sidebar = 0;
	
	var newwidth  = cliwidth - 4 - resultsBarWidth;
	var newheight = cliheight - 4 - 15 - 80 - 20; 
	
	m.width(newwidth);
	m.height(newheight);
	
	//alert('Width:' + newwidth + ' Height:' + newheight);
	map.checkResize();
}
*/

// Default location ---------------------------------------------------------------------------------
function defaultLocation() {
	var location = new GLatLng(centerLatitude, centerLongitude);
	map.setCenter(location, startZoom);
	
	closePoint();
	
	// Plot point in centre of map (for debugging) 
	//alert(centerLatitude +' '+ centerLongitude);
	//var point = new GLatLng(centerLatitude, centerLongitude);
	//var marker = new GMarker(point);
	//map.addOverlay(marker);
}
		
// Add logo at bottom of the map --------------------------------------------------------------------
var PromoControl = function(promoArray) {
	this.url_ = promoArray[0];
	this.imageURL_ = promoArray[1];
	this.imageWidth_ = promoArray[2];
	this.imageHeight_ = promoArray[3];
};

PromoControl.prototype = new GControl(true);

PromoControl.prototype.initialize = function(map) {
	url = this.url_;
	imageURL = this.imageURL_;
	imageWidth = this.imageWidth_;
	imageHeight = this.imageHeight_;
	
	var container = document.createElement("div");
	container.innerHTML = '<img style="cursor:pointer" src="'+imageURL+'" border="0" />';
	container.style.width = imageWidth+'px';
	container.style.height = imageHeight+'px';
		
	GEvent.addDomListener(container, "click", function() {
		document.location = url;
	});
	
	map.getContainer().appendChild(container);
	
	return container;
};

PromoControl.prototype.getDefaultPosition = function() {
	return new GControlPosition(G_ANCHOR_BOTTOM_LEFT, new GSize(70, 0));
};

// A function to debug the map ----------------------------------------------------------------------
function debugMap(map, state) {
if ( state == 'true' ) {
		for(i in map) { 
			GLog.write(i); 
		}
	}
}

// Load the map ---------------------------------------------------------------------------------
function mapInit() {
	if (GBrowserIsCompatible()) {		
        // Resize map needs to be after the set center as well
        resizeMap();
		
		// Load map
		map = new GMap2(document.getElementById("map"), {backgroundColor: '#FFFFFF'});
		
		// Set initial view
		defaultLocation();
		
		// Add map controls
		map.addControl(new GLargeMapControl());			// show the zoom in zoom out
	  	map.addControl(new PromoControl(promoArray));	// add copyright logo
		map.addControl(new GMapTypeControl());			// show the map | satellite | hybrid
		map.addControl(new GOverviewMapControl());		// show mini map in the corner 
		
		// Capture moving and zooming changes
		GEvent.addListener(map, "moveend", mapMoveEnd); 
		GEvent.addListener(map, "zoomend", mapZoomChange);
		
		// Load base icon
		baseIcon = new GIcon();
		baseIcon.image = "/media/images/maps/marker.png";
		//basePointIcon.shadow = "/media/images/maps/shadow.png";
		baseIcon.iconSize = new GSize(14, 14);
		//basePointIcon.shadowSize = new GSize(12, 10);
        		
		// Load data
		loadData();

		// Set to hybrid view
		map.setMapType(G_HYBRID_MAP); 
		
		// Add an encoded polyline.
		/*
	    var encodedPoints = "PJLJKJJMIKLHKLJJLKKKLIKIKKNJJJJLKMIIJJKNJJMKKLKPKLJLJIMIKILMIIOJKJLJJMKKHNKKLFNKLMJKMJJLJLJJLILFOGMIP<br>chqxHoiqSdbKfi@foLouMee@grOakFoB|cDals@dxGirAfDwm\qhUajq@mgD{|At|HenK}dK~eJq`@wQtcBa|`@sjBoyCocG|_G}xFw|Ao`Dc|Yt}Izm@cDwiXquMk`R|`AeaJx_EauBz~EbpDxbA`qEfrAkw]}sO}vR|aIciKfwFbiDb~Ms_Lf_AahQb_HuGqqBawi@p|XqtlArsIhhIjbMjgD~{IrjIrcBmbFnaLjvMrhW{{AtIgo{@nzFi}Bwm@gqNllRaiKt@u~Qb}SrfLbpKui_@``WyrEf{Qjik@j{SjbG{fGpzC{ZjxWtv^vh^vnHdfAnaLraNdxG{iCxoIth@f_HylMzzOijN|qTxpJzzC~bJup@leN`uD|il@acSvuHkfCttUkuDskCgpF`nIfq@xpJwfNxgVulDfym@obVcoCeiKvtNkzRm~HewMwwCt~C~eVp~XhkObhJn`i@ijGnsw@i^pqBaoQk|McaJxhP}{WshNgrH~mWiiFb|~@pnFrnF{kEhlIabRbRujIr_LlIv{l@ijGd`P_|IuGcw[hePscIvtNpxBbeNb_NldYulJzhVgoLbx\seK|hBgyf@tyL}n_@o~rA{`Vs|lA<br>";
	    var encodedLevels = "B????????????????????????????????????B";
	
	    var encodedPolyline = new GPolyline.fromEncoded({
			color: "#FF0000",
			weight: 2,
			points: encodedPoints,
			levels: encodedLevels,
			zoomFactor: 2,
			numLevels: 18
		});
		map.addOverlay(encodedPolyline);
		
		GDownloadUrl('http://country.ws.gmapify.fr/?country=BELGIUM', function(data, responseCode)
		{
			if((200==responseCode)&&(0!=data.length))
			{
				try{
					var iStart = 0;
					var arePoints = false;
					var polylineLevels = "";
					//File structure is [encoded Levels<br>encoded Polylines<br>...]
					do
					{
						var iEnd = data.indexOf("<br>",iStart);
						if( false == arePoints)
						{//Levels
							polylineLevels = data.substring(iStart,iEnd);
							arePoints = true;
						}
						else
						{//Points
							var polygon = new  GPolygon.fromEncoded({
							 polylines: [{color: "#ffff00", weight: 2, opacity:1.0,
							 points: data.substring(iStart,iEnd),
							 levels: polylineLevels,
							 zoomFactor: 2, numLevels: 18}], 
							fill: true, color:" #ffff00", opacity: 0.3, outline: true});
							googleMap.addOverlay(polygon);
							arePoints = false;
						}
						iStart = iEnd + 4;//jump above '<br>' to the next polylines
					}while( data.length > iStart)
				}catch(e){
					//here code to deal with errors;
				}
			}
			else
			{
				//here code to deal with errors;
			}
		});
		*/

		//alert('nelng=' + northEast.lng() + '&nelat=' + northEast.lat() + '&swlng=' + southWest.lng() + '&swlat=' + southWest.lat());
	
		//map.addOverlay(polygon); 
	} else {
      alert("Sorry, the Google Maps API is not compatible with this browser");
    }
	
	// Search ----------------------------------------------------------
	var options = { 
		beforeSubmit:  clearMap,
		success: 			loadData					// post-submit callback 
	}; 
	
	// Bind the form
	$('#formSearch').ajaxForm(options);
	
	function clearMap() {
		// Hide the search box
		if ($('#advancedSearch').is(':visible')) {
			toggleText();
		}
		
		// Close the detail point if it is open
		closePoint();
		
		// Show the reset search button
		$('#clearsearch').show();
		
		// Clear all existing markers
		clearMapOverlays();
	}

	// Initialise functions --------------------------------------------
	$("a.showhide").click(toggleText);		
}

// Set fancy box for the detail page --------------------------
function initFancyBox()
{
    $("a.fancy").fancybox({
        'transitionIn'			        : 'elastic',
        'transitionOut'			    : 'elastic',
        'hideOnContentClick'	: true,
        centerOnScroll             : true
    });
}

// Show hide text ------------------------------------------------------------------------------------------------------- 
function toggleText() {
	$('#advancedSearch').slideToggle("fast");
	$('a.showhide span').toggle();

	return false;
}

// Check uncheck boxes-----------------------------------------------------------------------------------------------
function setAllCheckboxes(div, action) {
	$(div + " input[type='checkbox']").attr('checked', action);
	
    return false;        
}

// Onload -----------------------------------------------------------------------------------------------------------------
window.onresize = resizeMap;

$(document).ready(mapInit); 
window.onunload=GUnload;
// -->
