var g_latField = null;
var g_lonField = null;

/**
 * 
 * @param latField
 * @param lonField
 * @return
 */
function setGlobals(latField, lonField) {
	
	g_latField = latField;
	g_lonField = lonField;
}

/**
 * 
 * @return
 */
function isW3CGeoLocationSupported() {
	
	return typeof(navigator.geolocation) != "undefined" && 
	       typeof(navigator.geolocation.getCurrentPosition) != "undefined";
}

/**
 * 
 * @return
 */
function areGoogleGearsSupported() {
	
	return window.google && google.gears;
}
 
/**
 * 
 * @return
 */
function isGPSEnabledBlackBerry() {
	
	return window.blackberry && blackberry.location.GPSSupported;
}

/**
 * 
 * @return
 */
function loadBlackBerryCoordinatesCallback() {
	
	g_latField.value = blackberry.location.latitude;
	g_lonField.value = blackberry.location.longitude;
}

/**
 * 
 * @param latField
 * @param lonField
 * 
 * @return
 */
function loadBlackBerryCoordinates(latField, lonField) {
	
	 // because of BlackBerry callback
	 setGlobals(latField, lonField);

	 blackberry.location.onLocationUpdate("loadBlackBerryCoordinatesCallback()");
	 blackberry.location.setAidMode(2);		// 0 - Cell Site, 1 - Assisted, 2 - Autonomous
	 blackberry.location.refreshLocation();
}

/**
 * 
 * @return
 */
function getGeolocation() {
	 
	 if (isW3CGeoLocationSupported()) {
		 return navigator.geolocation; 
	 } else if(areGoogleGearsSupported()) {
		 return google.gears.factory.create('beta.geolocation');
	 } else {
		 return null;
	 }
}

/**
 * 
 * @param latField
 * @param lonField
 *
 * @return
 */
function fillGeoLocation(latField, lonField, highAccuracy) {
	 
	 var geolocation = getGeolocation();
	 if (geolocation) {
		 
		 geolocation.getCurrentPosition(
					
			/* Fill in the coordinates */
			function(position) {
				
				latField.value = position.coords.latitude;
				lonField.value = position.coords.longitude;
			},
			
			/* Handler if location could not be found */
			function(error) {
				if (highAccuracy) {
					fillGeoLocation(latField, lonField, false);
				}
			},
			
			{ enableHighAccuracy:highAccuracy, maximumAge:0 }
	     );
		 
	 } else if(isGPSEnabledBlackBerry()) {
		 loadBlackBerryCoordinates(latField, lonField);
	 }
}