//<![CDATA[

// ====== Array for decoding the failure codes ======
var geocode_status=[];
geocode_status[G_GEO_SUCCESS]            = "Success";
geocode_status[G_GEO_MISSING_ADDRESS]    = "Missing Address: The address was either missing or had no value.";
geocode_status[G_GEO_UNKNOWN_ADDRESS]    = "Unknown Address:  No corresponding geographic location could be found for the specified address.";
geocode_status[G_GEO_UNAVAILABLE_ADDRESS]= "Unavailable Address:  The geocode for the given address cannot be returned due to legal or contractual reasons.";
geocode_status[G_GEO_BAD_KEY]            = "Bad Key: The API key is either invalid or does not match the domain for which it was given";
geocode_status[G_GEO_TOO_MANY_QUERIES]   = "Too Many Queries: The daily geocoding quota for this site has been exceeded.";
geocode_status[G_GEO_SERVER_ERROR]       = "Server error: The geocoding request could not be successfully processed.";

var geocode_accuracy=[];
geocode_accuracy[0]='';
geocode_accuracy[1]='Country level accuracy.';
geocode_accuracy[2]='Region (state, province, prefecture, etc.) level accuracy.';
geocode_accuracy[3]='Sub-region (county, municipality, etc.) level accuracy.'; 
geocode_accuracy[4]='Town (city, village) level accuracy.';
geocode_accuracy[5]='Post code (zip code) level accuracy.';
geocode_accuracy[6]='Street level accuracy.';
geocode_accuracy[7]='Intersection level accuracy.';
geocode_accuracy[8]='Address level accuracy.';


// Purpose: Make sure GBrowserIsCompatible is true
//          Create the GMap object and set initial map
//          Handle URL search string
//          Handle back button use.
//          
//          A hidden form variable called firstload is used to determine if this is the first
//          page load.  If it is not then it must be a Back Button or application link.
//          Application link refers to links within the Atlas app such as Help or Itinerary.
//
//          Linking will always be the same as a first load.
//          In this case the hidden form variables are always wiped out.
function load() {

	if (GBrowserIsCompatible()) {
	geocoder = new GClientGeocoder();
	map = new GMap2(document.getElementById("map"));
	
	map.setCenter(new GLatLng(50.2923,-107.6191), 3);	
	map.addControl(new GLargeMapControl());                // Adding ZoomControl to Google map
	map.addControl(new GMapTypeControl());                 // Adding Three Buttons to Google map Example Hybrid	 			


	var firstload=new getObj('first_load');
	
	// this is the first page load
	if (firstload.obj.value=='') {		
		firstload.obj.value='false';
		//alert('firstload now set to'+firstload.obj.value);
		if (IsEmptyString(window.location.search)==false) {
			//alert('HandleSearchArgs');
			HandleSearchArgs();
		}
	} else {
	// not the first load
	// I think lastcommand will always be '' and we will always jump to HandleBackButton
		var lastcommand=new getObj('last_command'); 		
		if (lastcommand.obj.value=='link'){
			//alert('HandleSearchArgs\nlastcommand='+lastcommand.obj.value);
			HandleSearchArgs();					
		}else {		
			//alert('HandleBackButton\n'+lastcommand.obj.value);
			HandleBackButton();	
		}		
	}  

	}
}

function HandleSearchArgs() {
var minlat='';
var maxlat='';
var minlon='';
var maxlon='';
var what='';
var where='';
var zoomlevel='';
var srch = window.location.search;
var txtWhat=new getObj('txtWhat');
var txtWhere=new getObj('txtWhere');
var bMapBounds=false;


if (IsEmptyString(srch)==false) {
	// trim the leading '?'
	srch=srch.substr(1,srch.length);
} else {
	return;
}	

// parse 4 coords, what and where, zoomlevel
args=srch.split('&');
for (var i=0;i<args.length;i++) {
	if (args[i].search('minlat')>-1) {
	minlat=args[i].split('=')[1];
	} else if (args[i].search('maxlat')>-1) {
	maxlat=args[i].split('=')[1];
	} else if (args[i].search('minlon')>-1) {
	minlon=args[i].split('=')[1];	
	} else if (args[i].search('maxlon')>-1) {
	maxlon=args[i].split('=')[1];
	} else if (args[i].search('what=')>-1) {
	what=args[i].split('=')[1];	
	} else if (args[i].search('where=')>-1) {
	where=args[i].split('=')[1];	
	} else if (args[i].search('zoomlevel=')>-1) {
	zoomlevel=args[i].split('=')[1];		
	}		
}

// populate the what and where input boxes
if (IsEmptyString(what)==false)
	txtWhat.obj.value=decodeURI(what); 	
if (IsEmptyString(where)==false)
	txtWhere.obj.value=decodeURI(where);

geocodeLat=999;
geocodeLon=999;
geocodeText=''; 
if (!((minlat=='')||(maxlat=='')||(minlon=='')||(maxlon=='')))
	bMapBounds=true;
	
if (bMapBounds==true) {	
	var frmMinLat=new getObj('minlat');
	var frmMaxLat=new getObj('maxlat');
	var frmMinLon=new getObj('minlon');
	var frmMaxLon=new getObj('maxlon');	
	frmMinLat.obj.value=minlat;
	frmMaxLat.obj.value=maxlat;
	frmMinLon.obj.value=minlon;
	frmMaxLon.obj.value=maxlon;
	var centerx = (parseFloat(frmMaxLon.obj.value) + parseFloat(frmMinLon.obj.value))/2;	
	var centery = (parseFloat(frmMaxLat.obj.value) + parseFloat(frmMinLat.obj.value))/2;	
	geocodeLat=centery;
	geocodeLon=centerx;
	geocodeText=where; 
	geocodeZoomLevel=parseInt(zoomlevel);
	map.setCenter(new GLatLng(centery,centerx),parseInt(zoomlevel));
	if (IsEmptyString(where)==false){
		AddGeocodeMarker();
		ZoomToGeocodeMarker();
	}
	
//alert('args handler form variables:\n'+frmMinLat.obj.value+','+frmMinLon.obj.value+', '+frmMaxLat.obj.value+', '+frmMaxLon.obj.value);
}
	
// submit query if we have map extent or what keyword(s)
map.clearOverlays();
if (bMapBounds==true){
	CallQueryService(1);
} else if (IsEmptyString(what)==false) {
	CallQueryService(1);
}

}


function HandleBackButton(){
	var txtWhat=new getObj('txtWhat');
	var txtWhere=new getObj('txtWhere');
	var lastcommand=new getObj('last_command');
	var frmMinLat=new getObj('minlat');
	var frmMaxLat=new getObj('maxlat');
	var frmMinLon=new getObj('minlon');
	var frmMaxLon=new getObj('maxlon');	
	var zoomlevel= new getObj('current_zoom');	
	//alert('lastcommand: '+lastcommand.obj.value);
	
	// update itinerary text
	UpdateItineraryText();
	
	// set geocode values to null
	geocodeLat=999;
	geocodeLon=999;
	geocodeText=''; 
	geocodeZoomLevel=zoomlevel.obj.value;		
	
	// do an update
	if (lastcommand.obj.value=='refreshmap') {	
		var centerx = (parseFloat(frmMaxLon.obj.value) + parseFloat(frmMinLon.obj.value))/2;	
		var centery = (parseFloat(frmMaxLat.obj.value) + parseFloat(frmMinLat.obj.value))/2;
		map.setCenter(new GLatLng(centery,centerx),parseInt(geocodeZoomLevel));	
		RefreshMap();		
	} else if (lastcommand.obj.value=='submit') {
		SubmitQuery();		
	} else {
		//alert('else...nothing');
	}
	
}

function DoGeocode(sWhere) {
	// swap two character Where Text with full state name
	if (sWhere.length==2) {
	  for (var i=0;i<=STATES_TWO_DIGIT.length;i++) {
		if (sWhere.toUpperCase()==STATES_TWO_DIGIT[i])
			sWhere=STATES_FULL_NAME[i];	  
	  }
	}

	if (geocoder) {	
	geocoder.getLocations(sWhere, getLocations_handler);
	};
}
//]]>


function getLocations_handler(response) {
// zoom levels 0 to 17
// google map defaults: address-16, city-13, state-10	
	var wherebox=new getObj('txtWhere');
	var currentPage=new getObj('current_page');
	currentPage.obj.value=1;
	var requested_page=1;	
	
	if (!response || response.Status.code != 200) {
		HideElement('loading_graphic');
		map.clearOverlays();
		var div = document.getElementById('toc_div');
		var notFoundMessage='<p>We could not understand the location ';
		notFoundMessage+= '<b>'+wherebox.obj.value+'</b></p>';
		notFoundMessage+='<p>Suggestions:</p>';
		notFoundMessage+='<p>Make sure all street and city names are spelled correctly.</p>';
		notFoundMessage+='<p>Make sure your address includes a city and state.</p>';
		notFoundMessage+='<p>Try entering a zip code.</p>';
		div.innerHTML=notFoundMessage;
		geocodeLat=999;
		geocodeLon=999;
		geocodeText='';  		
		return;			
	} else {
		var place = response.Placemark[0];
		//alert(place.address + '\n'+geocode_accuracy[place.AddressDetails.Accuracy]+'-'+place.AddressDetails.Accuracy);
		// vary zoom level according to type of place
		switch (place.AddressDetails.Accuracy) {
		case 1:        // country
			geocodeZoomLevel=3;
			break;
		case 2: 
		case 3:     // state, county
			geocodeZoomLevel=8;
			break;	
		case 4:    // town, zip
		case 5:
			geocodeZoomLevel=11;
			break;	
		case 6:    // street, intersection, address
		case 7: 
		case 8:  
			geocodeZoomLevel=12;
			break;		
		default:
			geocodeZoomLevel=13;
		}
		
		// Assign the geocoded data to global variables
		var point = new GLatLng(place.Point.coordinates[1],place.Point.coordinates[0]);	
		geocodeLat=point.y;
		geocodeLon=point.x;
		geocodeText=place.address;	
		
		// do something with the geocode results
		map.clearOverlays();
		ZoomToGeocodeMarker();
		AddGeocodeMarker()	;
			
		//				
		CallQueryService(requested_page);
  }
}


// Purpose: Add the geocode marker
function AddGeocodeMarker() {
	
	if (geocodeLat!=999) {		
		var icon = new GIcon();		
		//icon.image = 'icons/icon_square.png';		
		//icon.iconSize = new GSize(15, 15);
		//icon.image = 'http://labs.google.com/ridefinder/images/mm_20_red.png';
		//icon.shadow = 'http://labs.google.com/ridefinder/images/mm_20_shadow.png';
		//icon.iconSize = new GSize(12, 20);
		icon.image = 'icons/geocode_green.png';
		icon.shadow = "http://www.google.com/mapfiles/shadow50.png";		
		icon.iconSize = new GSize(24, 38);		
		icon.shadowSize = new GSize(37, 34);
		icon.iconAnchor = new GPoint(6, 20);
		icon.infoWindowAnchor = new GPoint(5, 1);	
		var point = new GLatLng(geocodeLat,geocodeLon);
		var GCmarker = new GMarker(point,icon);	
		geocodemarkers[0]=GCmarker;

		var displayText='<table border="0" cellspacing="0" cellpadding="0">';
		displayText+='<tr><td colspan=2">'+geocodeText+'</td></tr>';
		var sAddToItinerary = '<tr><td colspan="2"><a href="#" onclick="AddUserItinerary('+ generateUID()+');map.closeInfoWindow();return false;">+ Add To Itinerary</a></td></tr>';
		displayText = displayText + sAddToItinerary;
		
		to_geocodehtmls[0] = displayText + '<tr><td colspan="2">Get directions:&nbsp;<b>To here</b> - <a href="javascript:fromgeocode(0)">From here</a>' +
			'<br>Start address<form action="http://maps.google.com/maps" method="get" target="_blank">' +
			'<input type="text" SIZE=30 MAXLENGTH=40 name="saddr" id="saddr" value="" />&nbsp;' +
			'<INPUT value="Go" TYPE="SUBMIT">' +
			'<input type="hidden" name="daddr" value="' + point.lat() + ',' + point.lng() + 
					"(" + geocodeText + ")" + 
			'"/></td></tr></table>';

		from_geocodehtmls[0] = displayText + '<tr><td colspan="2">Get directions:&nbsp;<a href="javascript:togeocode(0)">To here</a> - <b>From here</b>' +
			'<br>End address<form action="http://maps.google.com/maps" method="get"" target="_blank">' +
			'<input type="text" SIZE=30 MAXLENGTH=40 name="daddr" id="daddr" value="" />&nbsp;' +
			'<INPUT value="Go" TYPE="SUBMIT">' +
			'<input type="hidden" name="saddr" value="' + point.lat() + ',' + point.lng() +
					"(" + geocodeText + ")" + 
			'"/></td></tr></table>';	
	        
		// The inactive version of the direction info
		displayText = displayText + '<tr><td colspan="2">Get directions:&nbsp;<a href="javascript:togeocode(0)">To here</a> - <a href="javascript:fromgeocode(0)">From here</a></td></tr>';
		displayText += '</table>';
				
				
		GEvent.addListener(GCmarker, "click", function() {
			GCmarker.openInfoWindowHtml(displayText);
		});
		map.addOverlay(GCmarker,icon);
	}	
}

function generateUID() {
geocodeUID++;
return geocodeUID;
}

// Purpose: zoom to the geocode point
function ZoomToGeocodeMarker() {	
	if (geocodeLat!=999) {
		map.setCenter(new GLatLng(geocodeLat,geocodeLon), geocodeZoomLevel);
		SetExtentParametersFromMap();		
	}	
}


// Purpose: Set the global/hidden map coord variables used for the WHERE query
//          expression.  Retrieved coords from the GMap object.
function SetExtentParametersFromMap(){
	var minlat=new getObj('minlat');	
	var minlon=new getObj('minlon');
	var maxlat=new getObj('maxlat');	
	var maxlon=new getObj('maxlon');	
	var zoomlevel= new getObj('current_zoom');
	var bounds = map.getBounds();		// GLatLngBounds
	var southWest = bounds.getSouthWest();
	var northEast = bounds.getNorthEast();
	minlat.obj.value=(southWest.y).toFixed(5);
	maxlat.obj.value=(northEast.y).toFixed(5);
	minlon.obj.value=(southWest.x).toFixed(5);
	maxlon.obj.value=(northEast.x).toFixed(5);	
	zoomlevel.obj.value=map.getZoom();
	
	//alert(minlat.obj.value+', '+minlon.obj.value+'\n'+maxlat.obj.value+', '+maxlon.obj.value);
}

