// Insert names of a callable method
InstallFunction( server, 'GetAreaBits' );
InstallFunction( server, 'GetBitForKey' );

var myBitMap = null;
var areaBitTimer = null

// Callback for after a successful GetBitCount
function onGotAreaBits( response ) {
	var length = response.length;
	myBitMap.replaceBits( response );
	if( areaBitTimer != null ) {
		clearInterval( areaBitTimer );
		areaBitTimer = null;
	}
	if( length < 100 )
		$('#status').html("<b>Retrieved " + length + " bits</b>");
	else
		$('status').html("<b>Retrieved " + length + " most recent bits</b>");
}

function directionDisplay( heading ) {
	var degrees = Number( heading );
	var direction;
	if( degrees >= 0.0 ) {
		if( degrees > 337.5 || degrees <= 22.5 )
			direction = 'North';
		else if( degrees <= 67.5 )
			direction = 'North East';
		else if( degrees <= 112.5 )
			direction = 'East';
		else if( degrees <= 157.5 )
			direction = 'South East';
		else if( degrees <= 202.5 )
			direction = 'South';
		else if( degrees <= 247.5 )
			direction = 'South West';
		else if( degrees <= 292.5 )
			direction = 'West';
		else
			direction = 'North West';
		
		return " - Looking " + direction;
	}
	else
		return "";
}

function BitMap( firstBit ) {
	this.currentBit = null;
	if (GBrowserIsCompatible()) {
		var mapOptions = {
			googleBarOptions : {
				style : "new"
			}
		}

		this.map = new GMap2(document.getElementById("map_canvas"), mapOptions);
		var point;
		if( firstBit ) {
			point = new GLatLng( firstBit.latitude, firstBit.longitude );
			this.setToBit( firstBit.bitKey );
		} else
			point = new GLatLng(37.3, -122.0);
		this.map.setCenter( point, 15 );
		// add 'Earth' as one of the map types
		this.map.addMapType(G_SATELLITE_3D_MAP);
		this.map.setMapType(G_SATELLITE_3D_MAP);
		this.map.setUIToDefault();
		this.map.enableGoogleBar();
		var publisher_id = "pub-9578396205438514";
		
		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').html("");
			}
		});
		GEvent.addListener( this.map, "mousemove", function( latlng ) {
			if( latlng ) {
				$('#status').html(String(latlng.lat()) + ", " + String(latlng.lng()));
			}
		});
		
		this.markMgr = new MarkerManager( this.map );
	}
}

BitMap.prototype.createMarker = function( newBit ) {
	var bit = newBit;
	var point = new GLatLng( bit.latitude, bit.longitude );
	// Create our redtree marker icon
    var rtIcon = new GIcon(G_DEFAULT_ICON);
    rtIcon.image = "http://www.redtree.com/resources/images/btree.gif";

	// Set up our GMarkerOptions object
	markerOptions = { icon:rtIcon };

	var marker = new google.maps.Marker(point, markerOptions);
	GEvent.bind(marker, "click", this, function() {
		this.setToBit( bit.bitKey );
	});
	return marker;
}

BitMap.prototype.replaceBits = function( bits ) {
	this.markMgr.clearMarkers()
	markers = [];
	for( var i = 0; i < bits.length; i++ ) {
		markers.push( this.createMarker( bits[ i ] ));
	}
	this.markMgr.addMarkers( markers, 3 );
	this.markMgr.refresh()
}

BitMap.prototype.setToBit = function( bitKey ) {
	server.GetBitForKey( bitKey, function( bit ) {
		myBitMap.currentBit = bit;
		var picture = $('#picture');
		if( bit.orientation == 0 ) {
			picture.width(400);
			picture.height(300);
		} else {
			picture.width(300);
			picture.height(400);
		}		
		picture.attr('src', '/bitimage?imagekey=' + bit.pictureKey);
		$('#enlargepicture').attr('href', '/?page=bigpicture&imagekey=' + bit.bigPictureKey); 
		clipHtml = '<object classid="clsid:02BF25D5-8C17-4B23-BC80-D3488ABDDC6B" codebase="http://www.apple.com/qtactivex/qtplugin.cab" width="260" height="60" align="middle"><param name="SRC" value="/clip?recordingkey=' +
			bit.recordingKey +'" /><param name="AUTOPLAY" value="false" /><param name="CONTROLLER" value="true" />' +
			'<embed src="/clip?recordingkey=' + bit.recordingKey + '" width="400" height="30" align="middle" autoplay="false" controller="true" pluginspage="http://www.apple.com/quicktime/download/"> </embed></object>';
		$('#clipdiv').html(clipHtml);
		$('#triptitle').text(bit.tripTitle).attr('href', '/showtrip?trip=' + bit.tripKey);
		$('#author').text(bit.author).attr('href', '/showauthor?author=' + bit.authorKey);
		$('#caption').text(bit.caption);
		if( bit.linkUrl ) {
			$('#bitlinklabel').text('Link:');
			$('#bitlink').attr('href', bit.linkUrl);
			if( bit.linkText ) {
				$('#bitlink').text(bit.linkText);
			}
			else {
				$('#bitlink').text(bit.linkUrl);
			}
		}
		else {
			$('#bitlinklabel').text('');
			$('#bitlink').text('').attr('href', '');
		}
		
		$('#bitdesc').text(bit.entryTime + directionDisplay( bit.heading ));
	} );
}

BitMap.prototype.areaBitStatus = function() {
	var count = 0;
	if( areaBitTimer )
		clearIterval( areaBitTimer );
		
	areaBitTimer = setInterval( function() {
		count = count + 1;
		symb = [ '+','-' ][ count % 2 ];
		$('#status').html("<b>retrieving area bits</b> " + symb + "</b>");
		}, 200 );
}