var map = null;

var mapMarkers = [];
var directionsObj;
var tmpBuffer;


/*
Initiate the main google map
*/
function loadGoogleMap(iLat, iLong, iZoom) {
	if (GBrowserIsCompatible()) {
    	map = new GMap2(document.getElementById("map_canvas"));
        
        map.setCenter(new GLatLng(iLat, iLong), iZoom);
        
		// Create the directions object
		directionsObj = new GDirections(map, document.getElementById('directions_div')); 
		GEvent.addListener(directionsObj, "load", directionsDone);
		GEvent.addListener(directionsObj, "error", directionsError);
        
        // Enable the wheel-scrolling features
		map.enableScrollWheelZoom();
	
		// Add NSEW + large zoom buttons
		map.addControl(new GLargeMapControl());

		// Add the MAP-SATELLITE-HYBRID buttons
    	map.addControl(new GMapTypeControl());     
	}
}


/*
Add a marker at the specified lat/long
*/
function addMapMarker(iLat, iLong, iPopupWindow, iColor, iID) {
	if ((!iLat) || (!iLong)) { return false; }
	
	var tmpPoint = new GLatLng(iLat, iLong);
	var tmpLength = mapMarkers.length;
	
  	var tmpIcon = new GIcon(G_DEFAULT_ICON);
  	tmpIcon.image = "/images/map_btns/" + iColor + "_btn.png";
  	
	mapMarkers[tmpLength] = new GMarker(tmpPoint, {icon:tmpIcon});
	
	GEvent.addListener(mapMarkers[tmpLength], "click", function() {
		currentLocationID = iID;
		mapMarkers[tmpLength].openInfoWindowHtml(iPopupWindow);
	});	

	map.addOverlay(mapMarkers[tmpLength]);
}


/*
Go back to the main info window for the specified marker
*/
function mapInfoBackBtn(iMarker) {
	setTimeout('GEvent.trigger(' + iMarker + ', \'click\');', 10);
}


/*
Show the "Get Directions To This Address" form
*/
function getDirectionsTo(iMarker, iAddress) {
	var tmpCell = findObj('directions_toolbar');
	tmpCell.innerHTML = '<span class="mapLink">Get directions: To here - <a href="javascript:void(0);" onclick="getDirectionsFrom(\'' + iMarker + '\');">From here</a> - <a href="javascript:void(0);" onclick="clearDirections(\'' + iMarker + '\');" class="mapLink">Cancel</a></span><br>';
	
	var tmpDescription = findObj('direction_cell');	
	tmpDescription.innerHTML = '<table width="100%" cellpadding="0" cellspacing="0"><tr><td height="5"></td></tr><tr><td class="mapLink" colspan="2"><b>Start address:</b></td></tr><tr><td rowspan="2" width="20" nowrap></td><td><form action="#" onsubmit="performDirectionsTo(\'' + iMarker + '\', \'' + iAddress + '\'); return false;"><input type="text" name="start_address" id="start_address"><input type="submit" value="Go"></form></td></tr></table>';

	setTimeout('parent.window.findObj(\'start_address\').focus();', 250);
}


/*
Perform the directions to command using the directions object
*/
function performDirectionsTo(iMarker, iAddress) {
	var tmpAddress = findObj('start_address');
	var tmpDirections = findObj('directions_toolbar');
	
	tmpBuffer = tmpDirections.innerHTML;
	tmpDirections.innerHTML = 'Getting Directions <img src="/images/progress_dots.gif">';
	
	//directionsObj.load('from: ' + tmpAddress.value + ' to: ' + iAddress);
	window.open('/directions.php?action=GET_DIRECTIONS&marker=' + iMarker + '&from=' + tmpAddress.value + '&to=' + iAddress, 'directions', 'width=500,height=380,toolbar=0,location=0,directories=0,status=0,menubar=0,scrollbars=0,resizable=1');
}


/*
Show the "Get Directions From This Address" form
*/
function getDirectionsFrom(iMarker, iAddress) {
	var tmpCell = findObj('directions_toolbar');
	tmpCell.innerHTML = '<span class="mapLink">Get directions: <a href=\"javascript:void(0);\" onclick=\"getDirectionsTo(\'' + iMarker + '\', \'' + iAddress + '\');\">To here</a> - From here - <a href="javascript:void(0);" onclick="clearDirections(\'' + iMarker + '\');" class="mapLink">Cancel</a></span><br>';
	
	var tmpDescription = findObj('direction_cell');	
	tmpDescription.innerHTML = '<table width="100%" cellpadding="0" cellspacing="0"><tr><td height="5"></td></tr><tr><td class="mapLink" colspan="2"><b>End address:</b></td></tr><tr><td rowspan="2" width="20" nowrap></td><td><form action="#" onsubmit="performDirectionsFrom(\'' + iMarker + '\', \'' + iAddress + '\'); return false;"><input type="text" name="end_address" id="end_address"><input type="submit" value="Go"></form></td></tr></table>';

	setTimeout('parent.window.findObj(\'end_address\').focus();', 250);
}


/*
Perform the directions to command using the directions object
*/
function performDirectionsFrom(iMarker, iAddress) {
	var tmpAddress = findObj('end_address');
	var tmpDirections = findObj('directions_toolbar');
	
	tmpBuffer = tmpDirections.innerHTML;
	tmpDirections.innerHTML = 'Getting Directions <img src="/images/progress_dots.gif">';
	
	//directionsObj.load('from: ' + iAddress + ' to: ' + tmpAddress.value);
	window.open('/directions.php?action=GET_DIRECTIONS&marker=' + iMarker + '&from=' + iAddress + '&to=' + tmpAddress.value, 'directions', 'width=500,height=380,toolbar=0,location=0,directories=0,status=0,menubar=0,scrollbars=0,resizable=1');
}


/*
We successfully got the directions
*/
function directionsDone() {
	var tmpDirections = findObj('directions_toolbar');
	
	tmpDirections.innerHTML = tmpBuffer;
	tmpBuffer = '';
}


/*
Gettings directions failed
*/
function directionsError(){
	var tmpDirections = findObj('directions_toolbar');
	
	tmpDirections.innerHTML = tmpBuffer;
	tmpBuffer = '';
	
	//toggleLayer('directions_div', 0);
	//toggleLayer('directions_toolbar_div', 0);
	$('#directions_div').show();
	$('#directions_toolbar_div').show();

	if (directionsObj.getStatus().code == G_GEO_UNKNOWN_ADDRESS) {
		alert("No corresponding geographic location could be found for one of the specified addresses. This may be due to the fact that the address is relatively new, or it may be incorrect.\nError code: " + directionsObj.getStatus().code);
		
	} else if (directionsObj.getStatus().code == G_GEO_SERVER_ERROR) {
		alert("A geocoding or directions request could not be successfully processed, yet the exact reason for the failure is not known.\n Error code: " + directionsObj.getStatus().code);
	   
	} else if (directionsObj.getStatus().code == G_GEO_MISSING_QUERY) {
		alert("The HTTP q parameter was either missing or had no value. For geocoder requests, this means that an empty address was specified as input. For directions requests, this means that no query was specified in the input.\n Error code: " + directionsObj.getStatus().code);

	/*
	} else if (directionsObj.getStatus().code == G_UNAVAILABLE_ADDRESS) {
		alert("The geocode for the given address or the route for the given directions query cannot be returned due to legal or contractual reasons.\n Error code: " + directionsObj.getStatus().code);
	*/
	
	} else if (directionsObj.getStatus().code == G_GEO_BAD_KEY) {
		alert("The given key is either invalid or does not match the domain for which it was given. \n Error code: " + directionsObj.getStatus().code);
		
	} else if (directionsObj.getStatus().code == G_GEO_BAD_REQUEST) {
		alert("A directions request could not be successfully parsed.\n Error code: " + directionsObj.getStatus().code);
		
	} else {
		alert("An unknown error occurred.");
	}
}


/*
Clear any active directions
*/
function clearDirections(iMarker) {
	//toggleLayer('directions_div', 0);
	//toggleLayer('directions_toolbar_div', 0);
	
	directionsObj.clear();
	mapInfoBackBtn(iMarker); 
}
