/***** Just declaring some global variables *****/ 

//Helper variables. Ignore these
var map;
var currentListings = [];
var currentMarkers = [];
var infoWindows = [];
var iterator = 0;
var activeMarker = null;
var markerLimit = 200;
var geocoder;


/***** Do on page load *****/

$(document).ready(function(){
	initializeMap();
	setListeners();
	setPanelListener();
});


/***** Creates the blank roadmap using the zoom and center specified above *****/
		
function initializeMap(){
	
	//set map options
	var myOptions = {
		zoom: 2,
		center: new google.maps.LatLng(20, -10),
		scaleControl: true,
		mapTypeId: google.maps.MapTypeId.ROADMAP,
		bounds: new google.maps.LatLngBounds()
	};
	
	//set container where map should be loaded
	//in this case it's the div with an ID of 'map' 
	var map_canvas = $("#map")[0];
	
	//initialize the map
	map = new google.maps.Map(map_canvas, myOptions);
}


/***** Adds any event listeners to the map  *****/

function setListeners(){
	
	//Creates the listener such that when the bounds of the map are changed, the fetchMarkers function is run
	google.maps.event.addListener(map, 'idle', function() {
		fetchMarkers();
	});
		
}


/***** This function passes the bounds of the map via ajax to the PHP page and returns the resulting markers *****/

function fetchMarkers(){
	
	//alert(map.getBounds().toString());
	
	//get the current bounds of the map	
	map.bounds = map.getBounds();
	
	//pass these bounds to the PHP page
	$.getJSON("ajax/fetchMarkers.php", 
	{
		bounds: map.bounds.toString()
	}, 
	function (data) {
		
		if(data != null && data[0] == 'LIMIT_EXCEEDED') {
			
			//clear all markers
			clearAllMarkers();
			//create centered placemark only if zoom is greater than 2
			if(map.getZoom() > 2){
				createSpecialMarker(data[1]);
			}
		
		} else {
		
			//on completion, returned data is saved...
			currentListings = data;
			//current markers are removed from map
			clearMarkers();
			//new markers are populated on map
			createMarkers();			
			
		}
		
	});			
}



/***** This function removes the current markers from the map except the active ones *****/

function clearMarkers(){

	var tempArray = [];
		    
	for(var i=0; i < currentMarkers.length; i++){
		
    	if(activeMarker == null || currentMarkers[i].title != activeMarker.title){
    		currentMarkers[i].setMap(null);
	    }else{
	    	tempArray.push(currentMarkers[i]);
	    }
    }
    
    currentMarkers = tempArray;
       
}


/***** This function removes all current markers from the map *****/

function clearAllMarkers(){
			
	for(var i=0; i < currentMarkers.length; i++){
		currentMarkers[i].setMap(null);
    }
           
	currentMarkers.length = 0;

}



/***** This function populates the map with markers *****/

function createMarkers(){
	
	if(currentListings == null)
		currentListings = [];
	
	//for each of the records that were returned from the PHP page
	for (var i = 0; i < currentListings.length; i++) {
	
		createMarker(i);
	}
	
}



/***** This function populates the map with a single marker *****/


function createMarker(i){
	
	//create a new marker on map
	var marker = new google.maps.Marker({
		map: map,
		position: new google.maps.LatLng(currentListings[i].lat, currentListings[i].lon)
	});
	var infowindow = new google.maps.InfoWindow({
		content: "<div class='infowindow'><a href='villa.php/"+currentListings[i].homeid+"'>Home ID "+currentListings[i].homeid+" "+currentListings[i].bedrooms+" Bedrooms</a><br><img src="+currentListings[i].pic+" width=200></div>" 
	});
	google.maps.event.addListener(marker, 'click', function() {
		//close any open infowindows 
		for(var j = 0; j < infoWindows.length; j++){
			infoWindows[j].close();
		} 
		infowindow.open(map,marker);
		activeMarker = marker; /* dharker - save the active marker when clicked */
	});
					
	//also place it in this array, so they can be removed when needed
	currentMarkers.push(marker);

	//place infowindow in array
	infoWindows.push(infowindow);

}

 

/***** dharker - This function populates the map with a special centered marker *****/

function createSpecialMarker(count){
	
	var html = count+" properties have been found in this area<br>please zoom in to area of interest to display properties";
	
	var markerLat = ((parseFloat(map.getCenter().lat()) - parseFloat(map.getBounds().getSouthWest().lat())) / 5) + parseFloat(map.getBounds().getSouthWest().lat());
	
	//create a new marker on map
	var marker = new google.maps.Marker({
		map: map,
		position: new google.maps.LatLng(markerLat, map.getCenter().lng()),
		title: html
	});
	
	var infowindow = new google.maps.InfoWindow({
		content: html
	});
	
	google.maps.event.addListener(marker, 'click', function() {
		infowindow.open(map,marker);
	});
					
	//also place it in this array, so they can be removed when needed
	currentMarkers.push(marker);
	
	//place infowindow in array
	infoWindows.push(infowindow);
	
	infowindow.open(map,marker);

}


/******* Sets the click listener on the 'JUMP TO' panel ***********/
function setPanelListener(){
	
	$(".link2").click(function(){

		var values = $(this).attr('rel').replace(' ','');
		var valuesArray = values.split("|");
		var latitude = valuesArray[0];
		var longitude = valuesArray[1];
		var zoom = valuesArray[2];

		map.setCenter(new google.maps.LatLng(latitude, longitude));
		map.setZoom(parseFloat(zoom));
				
		return false;
		
	});
	
}


