var Blat;
var Blng;

var p = {};

function errorCallback(e) {
	s = document.getElementById("geolocation");
	s.innerHTML = e.message;
	s.style.color = "red";
}

function geolocateBrowser() {

	try {
		navigator.geolocation.getCurrentPosition(successCallback, errorCallback, {
			maximumAge: 30000
		});
        return [Blat,Blng];
	} catch(e) {
		try {
			var geolocation = {};
			geolocation = google.gears.factory.create('beta.geolocation');
			geolocation.getCurrentPosition(successCallback, errorCallback);
            return [Blat,Blng];
		} catch(e) {
			try {
				p.coords = google.loader.ClientLocation;
				successCallback(p);
                return [Blat,Blng];
			} catch(e) {
				errorCallback({
					message: "No Geolocation providers found"
				});
                return [Blat,Blng];
			}
		}
	}
    
}


google.load("jquery", "1");
google.load('maps', '2');

function showAddress(response) {
	if (!response || response.Status.code != 200) {
		alert("Status Code:" + response.Status.code);
	} else {
		place = response.Placemark[0];
        Blat = place.Point.coordinates[0];
        Blng = place.Point.coordinates[1];


        city = place.AddressDetails.Country.AdministrativeArea.SubAdministrativeArea.SubAdministrativeAreaName;
        country = place.AddressDetails.Country.CountryNameCode;

        weatherLat = getWeatherFormat(Blat);
        weatherLng = getWeatherFormat(Blng);


        // console.log(response);
	    jQuery('#geolocation').html(
        city+'<br/>'+country+'<br/>'
        //'<b>orig latlng:</b>' + response.name + '<br/>' +
        //'<b>Address:</b>' + place.address + '<br>' +
        //'<b>City:</b>' + place.AddressDetails.Country.AdministrativeArea.SubAdministrativeArea.SubAdministrativeAreaName + '<br>' +
        //'<b>State:</b>' + place.AddressDetails.Country.AdministrativeArea.AdministrativeAreaName + '<br>' +
        //'<b>Accuracy:</b>' + place.AddressDetails.Accuracy + '<br>' +
        //'<b>Country code:</b> '
        //    + place.AddressDetails.Country.CountryNameCode
        );
        jQuery('#lat').html(Blat);
        jQuery('#lng').html(Blng);
        jQuery('#weatherlat').html(weatherLat);
        jQuery('#weatherlng').html(weatherLng);
	}
}

function getWeatherFormat(latOrlng){
    latOrlng = latOrlng +""; // change int to string
    var weatherFormat = latOrlng.replace(".","");
    strLength = weatherFormat.length;
    numberOfDigits = 8;
    while (strLength<numberOfDigits){
      weatherFormat = weatherFormat + "0";
      strLength++;
    }
    return weatherFormat;
}


function successCallback(p) {
	geocoder = new GClientGeocoder();
	var latlng = new GLatLng(p.coords.latitude,p.coords.longitude);
	geocoder.getLocations(latlng, showAddress);
	jQuery('#geolocation').text(p.coords.latitude + ', ' + p.coords.longitude);
    Blat = p.coords.latitude;
    Blng = p.coords.longitude;
}

