
/**
 * Storage container for all map overlays.  
 * 
 * Used for clearing all overlays from the map.
 */
var aOverlays = [];

/**
 * @var google.maps.LatLngBounds
 */
var allowedBounds = google.maps.LatLngBounds;

/**
 * Shadow used for all markers
 */
var shadow = new google.maps.MarkerImage(
	'/mdata/icons/shadow.png',
	new google.maps.Size(37, 34),
	new google.maps.Point(0, 0),
	new google.maps.Point(10, 34)
);

geocoder = new google.maps.Geocoder();


var map; //fix for IE8 - Jason - do not remove
/**
 * 
 * @param latitude
 * @param longitude
 */
function __constructMap(centerLat, centerLong, swLat, swLong, neLat, neLong)
{
	
	map = new google.maps.Map($('#map').get(0), {
		mapTypeControl: true,
		mapTypeId: google.maps.MapTypeId.ROADMAP,
		overviewMapControl: true,
		panControl: true,
		zoomControl: true,
		overviewMapControl: true,
		draggableCursor: 'crosshair',
		center: new google.maps.LatLng(centerLat, centerLong),
		zoom: 12,
		minZoom: 12
	});
	
	allowedBounds = new google.maps.LatLngBounds(
			new google.maps.LatLng(swLat, swLong), 
			new google.maps.LatLng(neLat, neLong));
	map.fitBounds(allowedBounds);
	
	
	google.maps.event.addListener(map, "dragend", function() {
		
		if(!map.getBounds().intersects(allowedBounds)){
	        map.panToBounds(allowedBounds);
	    }
	});
	
	loadMapData();
	
}


/**
 * 
 * @param theform
 * @returns
 */
function changeMapDates() {
	clearOverlays();
	 
	startDate = convertDate($('#start-date').val());
	endDate = convertDate($('#end-date').val());
	
	if (endDate <= startDate)
	{
		alert("The end date cannot be before the start date");
	} 
	else 
	{
		loadMapData();
	}
}

/**
 * .clearOverlays() isn't currently supported in Google Maps APIv3
 * 
 * This achieves the same result
 * 
 * @returns NULL
 */
function clearOverlays() {
	if (aOverlays) {
		for (i in aOverlays) {
			aOverlays[i].setMap(null);
		}
	}
}


/**
 * Adds supplied address to the map.
 * 
 * @param address
 */
function codeAddress() {
    geocoder.geocode( { 'address': $('#address').val()}, function(results, status) {
    	
    	var addressBounds = new google.maps.LatLngBounds(results[0].geometry.location);
    	
    	if (status == google.maps.GeocoderStatus.OK && addressBounds.intersects(allowedBounds)) {
	        map.setCenter(results[0].geometry.location);
	        var marker = new google.maps.Marker({
	        	icon: 'http://www.google.com/mapfiles/arrow.png', 
	            map: map,
	            position: results[0].geometry.location
	        });
	        
	        var infowindow = new google.maps.InfoWindow({
				content: '<div id="bubble">Approximate Location:<br />' + $('#address').val() + '<br /></div>'
			});
	        
	        infowindow.open(map, marker);
	        
	        // Add listener to remove marker for the address
	    	google.maps.event.addListener(marker, "click", function() {
	    		marker.setMap(null);
	    	});
	        
    	}
    	else if(!addressBounds.intersects(allowedBounds))
    	{
    		alert('Sorry, that address is not within the allowed map boundries.');
    	}
    	else 
    	{
    		alert("Geocode was not successful for the following reason: " + status);
    	}
    });
}


/**
 * Converts 8/15/06 to unix timestamp
 * 
 * @param string datestring
 */
function convertDate(datestring) {
	var result   = datestring.match(/\d+/g);
	var thisdate = new Date(result[2], result[0] - 1,result[1]);
	return thisdate.getTime();
}


/**
 * Loads the Map Markers and Polylines into the map
 */
function loadMapData() {
	
	$.get("/mdata/publicmapdata.php?s=" + convertDate($('#start-date').val()) + "&e=" + convertDate($('#end-date').val()), function(data) {
		
		/**
		 * Process markers
		 */
		$(data).find('marker').each(function() {
			var markerData = $(this);
			
			var marker = new google.maps.Marker({
				position: new google.maps.LatLng(markerData.attr('lat'), markerData.attr('lng')),
				icon: '/mdata/icons/' + markerData.attr('icon'),
				shadow: shadow,
				map: map
			});
			
			var infowindow = new google.maps.InfoWindow({
				content: markerData.attr('html').replace(/\\n/g, "<br />")
			});
			
			google.maps.event.addListener(marker, 'click', function() {
				  infowindow.open(map, marker);
			});
			
			aOverlays.push(marker);
		}); 
		

		/**
		 * Process Polylines
		 */
		$(data).find('line').each(function() {
			var line = $(this);
			
			// get any line attributes
			var polyColor = line.attr('color');
			var width  = parseFloat(line.attr('width'));

			// read each point on that line
			var polyPath = [];
			var index = 0;
			$(line).find('point').each(function() {
				var line = $(this);
			   	polyPath[index] = new google.maps.LatLng(
					   	parseFloat(line.attr('lat')), 
					   	parseFloat(line.attr('lng'))
				);

				index++;
			});

			currentPoly = new google.maps.Polyline({
				path: polyPath,
				strokeColor: polyColor,
				stokeOpacity: 1.0,
				strokeWeight: width,
				map: map
			});
			
			aOverlays.push(currentPoly);

		});
	}); 
}
