InstallFunction( server, 'getFarBits' );

var ge;
var trails = null;
var bits = null;
var bitsAreDisplayed = 0;

google.load("earth", "1");

function init() {
  google.earth.createInstance('map_canvas', initCallback, failureCallback);
}

function initCallback(pluginInstance) {
	ge = pluginInstance;
	ge.getWindow().setVisibility(true);
	
	// add a navigation control
	ge.getNavigationControl().setVisibility(ge.VISIBILITY_AUTO);
	
	// Create a new LookAt
	var lookAt = ge.createLookAt('');
	lookAt.setLatitude(49.46);
	lookAt.setLongitude(-115.1);
	lookAt.setRange(3500.0);
	lookAt.setTilt(60.0);
	lookAt.setHeading(240.0);
	// Update the view in Google Earth
	ge.getView().setAbstractView(lookAt);
	
	toggleTrails();
	toggleBits();

	// add some layers
	//ge.getLayerRoot().enableLayerById(ge.LAYER_BORDERS, true);
	//ge.getLayerRoot().enableLayerById(ge.LAYER_ROADS, true);
	
}

function failureCallback(errorCode) {
}

function loadTrails() {
	// fetch the KML
	function finished(object) {
		if (!object) {
			// wrap alerts in API callbacks and event handlers
			// in a setTimeout to prevent deadlock in some browsers
			setTimeout(function() {
				alert('Bad or null KML.');
			}, 0);
			return;
		}
		ge.getFeatures().appendChild(object);
		trails = object;
	}

	google.earth.fetchKml(ge, "http://s3.amazonaws.com/redtree/far/fartrails.kmz", finished);
}

function toggleTrails() {
	// remove the old KML object if it exists
	if ( trails ) {
		ge.getFeatures().removeChild(trails);
	}
	trails = null;
	
	// if the checkbox is checked, fetch the KML and show it on Earth
	var trailsCheckbox = document.getElementById('showtrails');
	if (trailsCheckbox.checked)
		loadTrails();
}

function toggleBits() {
	if ( bits ) {
		// remove the old bits if they exist
		if ( bitsAreDisplayed ) {
			for ( var bitNumber in bits ) {
				ge.getFeatures().removeChild( bits[ bitNumber ] );
			}
			bitsAreDisplayed = 0;
		}
		else {
			for ( var bitNumber in bits ) {
				ge.getFeatures().appendChild( bits[ bitNumber ] );
			}
			bitsAreDisplayed = 1;
		}			
	}
	else {
		var bitsCheckbox = document.getElementById('showbits');
		if ( bitsCheckbox.checked )
			showBits();
	}
}

function showBits() {
	bits = new Array;
	bitsAreDisplayed = 1;
	for( var bitNumber in farBits ) {
		var bit = farBits[ bitNumber ];
		var placemark = ge.createPlacemark( '' + bit.id );
		//placemark.setName("TripBit_" + bitNumber);
		bits[ bitNumber ] = placemark;
		
		// Create style map for placemark
		var icon = ge.createIcon('');
		icon.setHref('http://www.redtree.com/resources/images/btree.gif');
		var style = ge.createStyle('');
		style.getIconStyle().setIcon(icon);
		placemark.setStyleSelector(style);
		
		// Create point
		var point = ge.createPoint('');
		point.setLatitude( bit.latitude );
		point.setLongitude(bit.longitude);
		placemark.setGeometry(point);
		
		google.earth.addEventListener(placemark, 'click', function(event) {
			// Prevent the default balloon from popping up.
			event.preventDefault();
			
			var target = event.getTarget();
			var bitId = target.getId();
			var balloon = ge.createHtmlStringBalloon('');
			balloon.setFeature(target);
			balloon.setMaxWidth(700);
			
			balloon.setContentString(
				'<iframe src="http://tumblr.redtree.com/post/' + bitId + '" width=665 height=500>'+
				'Sorry, but your browser does not support iframes</iframe>'
			);
			
			ge.setBalloon(balloon);
		});
		ge.getFeatures().appendChild( placemark );
	}
}

/*
function FarMap( firstBit ) {
	if (google.maps.BrowserIsCompatible()) {
		var mapOptions = {
			googleBarOptions : {
				style : "new"
			}
		}

		this.map = new google.maps.Map2(document.getElementById("map_canvas"), mapOptions);
		this.map.setMapType(G_SATELLITE_MAP);
		// add 'Earth' as one of the map types
		this.map.addMapType(G_SATELLITE_3D_MAP);

		this.map.setUIToDefault();
		this.map.enableGoogleBar();

		// Get the current view
		//var lookAt = this.map.getView().copyAsLookAt(ge.ALTITUDE_RELATIVE_TO_GROUND);
		//lookAt.setTilt(80.0);
		// Update the view in Google Earth
		//ge.getView().setAbstractView(lookAt);
		this.map.setUIToDefault();
		//this.map.enableGoogleBar();
		var publisher_id = "pub-9578396205438514";
		
		geoXml = new GGeoXml("http://s3.amazonaws.com/redtree/far/fartrails.kmz");
		this.map.addOverlay(geoXml);
		
		var adsManagerOptions = {
		 maxAdsOnMap : 1,
		 style: 'adunit'
		 // The channel field is optional - replace this field with a channel number
		 // for Google AdSense tracking
		 // channel: 'your_channel_id' 
		};
		
		adsManager = new GAdsManager( this.map, publisher_id, adsManagerOptions);
		adsManager.enable();
*/
/*
		var bounds = this.map.getBounds();
		var southWest = bounds.getSouthWest();
		var northEast = bounds.getNorthEast();
		var nsew = {
			"n": northEast.lat(),
			's': southWest.lat(),
			'e': northEast.lng(),
			'w': southWest.lng()
			};			
	
		server.GetAreaBits( nsew, onGotAreaBits );
		this.areaBitStatus();
		GEvent.bind( this.map, "moveend", this, function() {
			var bounds = this.map.getBounds();
			var southWest = bounds.getSouthWest();
			var northEast = bounds.getNorthEast();
			var nsew = {
				"n": northEast.lat(),
				's': southWest.lat(),
				'e': northEast.lng(),
				'w': southWest.lng()
				};			
			server.GetAreaBits( nsew, onGotAreaBits );
			this.areaBitStatus();
		});
		
		GEvent.addListener( this.map, "mouseout", function( latlng ) {
			if( latlng ) {
				$('status').innerHTML = "";
			}
		});
		GEvent.addListener( this.map, "mousemove", function( latlng ) {
			if( latlng ) {
				$('status').innerHTML = String(latlng.lat()) + ", " + String(latlng.lng());
			}
		});
		
		this.markMgr = new MarkerManager( this.map );
*/
/*
	}
}
*/

