// instance variables
var map = null;
var icon = null;

// constants
var STAGE_0 = 0;
var STAGE_CLICKED_CENTRE = 10;
var STAGE_CLICKED_DIR = 20;
var degreesPerRadian = 180.0 / Math.PI;
	
// the stage we are at
var stage;

// the 2 points clicked
var pointCentre;
var pointDir;

// geocoders
var localSearch = new GlocalSearch();
var geocoder = new GClientGeocoder();

//Main
function load() {
     
	this.map = initMap();
	this.icon = initIcon();
	initPoints();// initialise and default
	
	// listen for a click
	GEvent.addListener(map, "click", function(marker, point) {
		switch(stage){
			case STAGE_0 : 
				// We are at stage 0, they have just clicked for the first time.
				// pan there
				map.panTo(point);
				// add the compass
				map.addOverlay(new GMarker(point, icon, true ));
				// we have to make it inert otherwise point isn't populated.... :(
				//map.addOverlay(new GMarker(point, icon));
				// save the point
				pointCentre=point;
				// move on
				stage = STAGE_CLICKED_CENTRE;
				break;

			case STAGE_CLICKED_CENTRE :
				// save the point
				pointDir=point;
				// compute dir
				var bearing = getBearing(pointCentre,pointDir);
				// draw polyline
				map.addOverlay(new GPolyline(new Array(pointCentre, pointDir)));
				// display the info
				var infoMarker = new GMarker(pointCentre);
				map.addOverlay(infoMarker);
				//var info = "  geo:lat=" + pointCentre.lat()+ " geo:long="+pointCentre.lng()+" geo:dir="+bearing+"     ";
				var info = " geo:lat=" + pointCentre.lat()+ " geo:long="+pointCentre.lng()+" geo:dir="+bearing+" geotagged";
				infoMarker.openInfoWindowHtml("<br/><span style='font-size:10px; font-family:verdana'>"+info+"</span>");
				// and here
				document.getElementById('tags').value=info;
				//focus and select it...
				document.getElementById('tags').focus();
				document.getElementById('tags').select();
				//update viewr link
				document.getElementById('footerLink').href = "javascript:openExternal('http://www.quakr.co.uk/quakr/viewr?lat="+pointCentre.lat()+"&lon="+pointCentre.lng()+"');";
				document.getElementById('footerLink').style.display="block";
				
				// when close the popup, go back to start
				GEvent.addListener(map.getInfoWindow(),"closeclick", function(marker, point) {
					// move on - back to beginning.. (todo.. go on to alt?)
					initPoints();
				});
				stage = STAGE_CLICKED_DIR;
				break;	
				
			case STAGE_CLICKED_DIR :
				initPoints();
				break;	
		}

    });// end event listener
}

function initPoints(){
	// remove overlays
	map.clearOverlays();
	// stage 0
	stage = STAGE_0;
	// the 2 points clicked
	pointCentre = null;
	pointDir = null;
}

function initMap(){
	var map = new GMap2(document.getElementById("map"));
	map.addControl(new GLargeMapControl());
	map.addControl(new GMapTypeControl());
	map.setCenter(new GLatLng(51.50308,-0.117588), 13);// start in london?
	return map;
}

function initIcon(){
	var icon = new GIcon();
	//icon.image = "http://quakr.co.uk/~katie/quakrtaggr/compass.png";
	icon.image = "compass.png";
	icon.iconSize = new GSize(300, 300);
	icon.iconAnchor = new GPoint(150, 150);
	icon.infoWindowAnchor = new GPoint(5, 1);
	return icon;
}

// see http://www.econym.demon.co.uk/googlemaps/examples/arrows.htm and T. Vincenty, Survey Review, 23, No 176, p 88-93,1975.      
function getBearing( from, to ) { 
	// Convert to radians.
	var lat1 = from.latRadians();
	var lon1 = from.lngRadians();
	var lat2 = to.latRadians();
	var lon2 = to.lngRadians();
	// Compute the angle.
	var angle = - Math.atan2( Math.sin( lon1 - lon2 ) * Math.cos( lat2 ), Math.cos( lat1 ) * Math.sin( lat2 ) - Math.sin( lat1 ) * Math.cos( lat2 ) * Math.cos( lon1 - lon2 ) );
	if ( angle < 0.0 ) angle  += Math.PI * 2.0;
	// And convert result to degrees.
	angle = angle * degreesPerRadian;
	// round it
	return Math.round(angle);
}

function writeAlt(alttoadd) {
	var current = document.getElementById('tags').value;
	if (current.indexOf('geotagged') == -1) {
		//not picked a spot yet
		alert("Pick someplace on the map first...");
	} else if (alttoadd == '70' && current.indexOf('geo:alt') == -1) {
		//default value=70 and not already added...
		alert("That's the default value - no need to add it...");
	} else if (current.indexOf('geo:alt') == -1) {
		//nothing added and not 70 (or it would have been caught already)
		document.getElementById('tags').value += " geo:alt="+alttoadd;
	} else if (current.indexOf('geo:alt') != -1) {
		//already something in so need to...
		if (alttoadd == '70') {
			// replace it...
			document.getElementById('tags').value = current.replace(/\ geo:alt=\d+/,"");
		} else {
			//remove it...
			document.getElementById('tags').value = current.replace(/\ geo:alt=\d+/," geo:alt="+alttoadd);
		}
	}
	//focus and select it...
	document.getElementById('tags').focus();
	document.getElementById('tags').select();
}

function writeTilt(tilttoadd) {
	var current = document.getElementById('tags').value;
	if (current.indexOf('geotagged') == -1) {
		//not picked a spot yet
		alert("Pick someplace on the map first...");
	} else if (tilttoadd == '90' && current.indexOf('ge:tilt') == -1) {
		//default value=90 and not already added...
		alert("That's the default value - no need to add it...");
	} else if (current.indexOf('ge:tilt') == -1) {
		//nothing added and not 90 (or it would have been caught already)
		document.getElementById('tags').value += " ge:tilt="+tilttoadd;
	} else if (current.indexOf('ge:tilt') != -1) {
		//already something in so need to...
		if (tilttoadd == '90') {
			// replace it...
			document.getElementById('tags').value = current.replace(/\ ge:tilt=\d+/,"");
		} else {
			//remove it...
			document.getElementById('tags').value = current.replace(/\ ge:tilt=\d+/," ge:tilt="+tilttoadd);
		}
	}
	//focus and select it...
	document.getElementById('tags').focus();
	document.getElementById('tags').select();
}

function writeZoom(zoomtoadd) {
	var current = document.getElementById('tags').value;
	if (current.indexOf('geotagged') == -1) {
		//not picked a spot yet
		alert("Pick someplace on the map first...");
	} else if (zoomtoadd == '1' && current.indexOf('quakr:zoom') == -1) {
		//default value=1 and not already added...
		alert("That's the default value - no need to add it...");
	} else if (current.indexOf('quakr:zoom') == -1) {
		//nothing added and not 1 (or it would have been caught already)
		document.getElementById('tags').value += " quakr:zoom="+zoomtoadd;
	} else if (current.indexOf('quakr:zoom') != -1) {
		//already something in so need to...
		if (zoomtoadd == '1') {
			// replace it...
			document.getElementById('tags').value = current.replace(/\ quakr:zoom=\d+/,"");
		} else {
			//remove it...
			document.getElementById('tags').value = current.replace(/\ quakr:zoom=\d+/," quakr:zoom="+zoomtoadd);
		}
	}
	//focus and select it...
	document.getElementById('tags').focus();
	document.getElementById('tags').select();
}

function openExternal(extUrl) {
	var isOpen;
	isOpen = window.open(extUrl,'Quakr_Viewr','scrollbars=yes,toolbar=no,location=no,status=no,menubar=no,resizable=no,width=1000,height=650');
	isOpen.focus();
}

//http://www.tomanthony.co.uk/blog/geocoding-uk-postcodes-with-google-map-api/ 
function usePointFromPostcode(postcode, callbackFunction) {
  localSearch.setSearchCompleteCallback(null,
    function() {
      if (localSearch.results[0]) {    
        var resultLat = localSearch.results[0].lat;
        var resultLng = localSearch.results[0].lng;
        var point = new GLatLng(resultLat,resultLng);
        callbackFunction(point);
      }else{
        alert("Postcode not found!");
      }
    });  
  localSearch.execute(postcode + ", UK");
}
function setCenterToPoint(point) {
	map.setCenter(point, 15);
}
function showNonUkAddress(address) {
  geocoder.getLatLng(
    address,
    function(point) {
      if (!point) {
        alert(address + " not found");
      } else {
        map.setCenter(point, 15);
      }
    }
  );
}