// 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').innerHTML = "<b>Retrieved " + length + " bits</b>";
	else
		$('status').innerHTML = "<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.setMapType(G_SATELLITE_MAP);
		this.map.setCenter( point, 15 );
		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').innerHTML = "";
			}
		});
		GEvent.addListener( this.map, "mousemove", function( latlng ) {
			if( latlng ) {
				$('status').innerHTML = 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 );
	var marker = new GMarker(point);
	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').src = '/bitimage?imagekey=' + bit.pictureKey;
		$('enlargepicture').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').innerHTML = clipHtml;
		$('triptitle').firstChild.nodeValue = bit.tripTitle;
		$('triptitle').href = '/showtrip?trip=' + bit.tripKey;
		$('author').firstChild.nodeValue = bit.author;
		$('author').href = '/showauthor?author=' + bit.authorKey;
		$('caption').innerHTML = bit.caption;    // should be safe since it is escaped on entry
		if( bit.linkUrl ) {
			$('bitlinklabel').firstChild.nodeValue = 'Link:';
			$('bitlink').href = bit.linkUrl;
			if( bit.linkText ) {
				$('bitlink').innerHTML = bit.linkText;  // should be safe since it is escaped on entry
			}
			else {
				$('bitlink').firstChild.nodeValue = bit.linkUrl;
			}
		}
		else {
			$('bitlinklabel').firstChild.nodeValue = '';
			$('bitlink').firstChild.nodeValue = '';
			$('bitlink').href = '';
		}
		
		$('bitdesc').firstChild.nodeValue = 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').innerHTML = "<b>retrieving area bits</b> " + symb + "</b>";
		}, 200 );
}