//var flagContactDetailsClicked = 0;
var map;
var locationFound = false;
var mapInitialised = false;
var mozzBoxFound = false;
var mozzDefaultLat = 52.21;
var mozzDefaultLng = 0.12;
var mozzBox = null;
var locationDrawnOnMap = false;
var locationFoundBeforeMapInitialised = false;

function initialiseGMap() {
    if (GBrowserIsCompatible()) {
        map = new GMap2(document.getElementById("map_canvas"));
        map.addControl(new GSmallMapControl());
        map.addControl(new GMapTypeControl());
        map.enableContinuousZoom();
        //map.enableScrollWheelZoom();
        
        if (locationFoundBeforeMapInitialised) {
            drawCircle();
        } 
        map.setCenter(mozzBox.getCenter(), map.getBoundsZoomLevel(mozzBox) - 1);
        
        
        //pointer icon
        //var point = new GLatLng(mozzLat, mozzLng);
        //map.addOverlay(new GMarker(point));
    }
    mapInitialised = true;
}


function initialisePage() {
    if (GBrowserIsCompatible()) {
        //set default mozzbox coordinates
        var sizeOfDefaultMozzBox = 1;
        mozzBox = new GLatLngBounds(new GLatLng(mozzDefaultLat-sizeOfDefaultMozzBox,mozzDefaultLng-sizeOfDefaultMozzBox), new GLatLng(mozzDefaultLat+sizeOfDefaultMozzBox,mozzDefaultLng+sizeOfDefaultMozzBox));
        // then draw the google map
        initialiseGMap();
        // now find my location from fire eagle
        getLocation();
    }
}

function checkInitOK() {
    if ((!locationFound) || (!mapInitialised)) {
        document.getElementById('mozzloc').innerHTML = '[Failed to find]';
        document.getElementById('mozztimezone').innerHTML = '-';
        document.getElementById('mozzlocdate').innerHTML = '-';
    }
}

function drawCircle() {
    if (!locationDrawnOnMap) {
        //draw a green see-through circle
        var box = new GGroundOverlay("images/round_area.png", mozzBox);
        map.addOverlay(box);
        locationDrawnOnMap = true;
    }
}

function resetMap() {
    if (GBrowserIsCompatible()) {
        if (mapInitialised) {
            drawCircle();
            map.setCenter(mozzBox.getCenter(), map.getBoundsZoomLevel(mozzBox) - 1);
        }
    }
}

function eaglePipeCallback(s) {
    //use the attached object to set mozzBox co-ordinates, and write location details to page
	for (i=0; i < s[0].hierarchy[0].location.length; i++) {
		if (s[0].hierarchy[0].location[i].best_guess) {
		    var l = s[0].hierarchy[0].location[i];
			document.getElementById('mozzloc').innerHTML = l.name + '.';
			var dUpdated = new Date();
			dUpdated.setISO8601(l.located_at);
        	document.getElementById('mozzlocdate').innerHTML  = dUpdated.getNiceDate() + '.';
			if (l.georss_box) {
			    mozzBox = new GLatLngBounds(new GLatLng(l.georss_box[0],l.georss_box[1]), new GLatLng(l.georss_box[2],l.georss_box[3]));
			} else if (l.georss_point) {
			    mozzBox = new GLatLngBounds(new GLatLng(l.georss_point[0]-0.01,l.georss_point[1]-0.01),new GLatLng(l.georss_point[0]+0.01,l.georss_point[1]+0.01));
			}
			break
		}
	}

	document.getElementById('mozztimezone').innerHTML = s[0].hierarchy[0].timezone + '.';
	locationFound = true;
	if (mapInitialised) {
	    resetMap();
    } else {
        locationFoundBeforeMapInitialised = true;
    }
}


function getLocation() {
    //attaches a script to the head so it runs.  When it does, it calls eaglePipeCallback
	//var eagleFeedScript  = document.createElement("script");
	//eagleFeedScript.setAttribute("type", "text/javascript");
	//eagleFeedScript.setAttribute("src", "http://www.eaglefeed.me/json/4WVMaPaI3rOC?callback=eaglePipeCallback");
	//document.getElementsByTagName('head')[0].appendChild(eagleFeedScript);
	drawMapBlob(callGoogle());
}

function drawMapBlob(s) {
	var p = s.features[0].geometry.coordinates;
	
    //use the attached object to set mozzBox co-ordinates, and write location details to page
	document.getElementById('mozzloc').innerHTML = s.features[0].properties.reverseGeocode + '.';
	var dUpdated = new Date();
	mEpoch = s.features[0].properties.timeStamp;
	if(mEpoch<10000000000) mEpoch *= 1000; // convert to milliseconds (Epoch is usually expressed in seconds, but Javascript uses Milliseconds)
	dUpdated.setTime(mEpoch);

	var secondsAgo = (new Date() - dUpdated)/1000;
	var ago = secondsAgo;
	var units = 'seconds';
	
	if ((secondsAgo) > 60) {			// one minute
		ago = secondsAgo / 60;
		units = 'minutes';
	}
	if ((secondsAgo) > 3600) {			// one hour
		ago = secondsAgo / 3600;
		units = 'hours';
	}
	if ((secondsAgo) > 3600*24) {			//one day
		ago = secondsAgo / (3600*24);
		units = 'days';
	}

	//dUpdated.setISO8601('2006-09-01');
	document.getElementById('mozzlocdate').innerHTML  = dUpdated.getNiceDate() + ' (about ' + ago.toFixed(1).toString() + ' ' + units + ' ago).';
	longFactor = Math.cos(p[1] * (2 * Math.PI / 360));
	// 1 deg latitude = approx 111km
	boxSize = s.features[0].properties.accuracyInMeters / 111000;
	
	mozzBox = new GLatLngBounds(new GLatLng(p[1] - boxSize, p[0]- boxSize/longFactor),new GLatLng(p[1]+ boxSize,p[0]+ boxSize/longFactor));

	//document.getElementById('mozztimezone').innerHTML = s[0].hierarchy[0].timezone + '.';
	locationFound = true;
	if (mapInitialised) {
	    resetMap();
    } else {
        locationFoundBeforeMapInitialised = true;
    }
}

