// Original JavaScript code by Chirp Internet: www.chirp.com.au
// Please acknowledge use of this code by including this header.

function bearing(from, to)
{
  if(from == null) return false;
  var a, b, c, d, e;
  var toRad = function(input) { return input * Math.PI / 180; }
  a=toRad(from.lat()); b=toRad(from.lng()); c=toRad(to.lat()); d=toRad(to.lng());
  with(Math) {
    e=-atan2(sin(b-d)*cos(c),cos(a)*sin(c)-sin(a)*cos(c)*cos(b-d));
    if(e<0.0) e+=PI*2.0;
    e=e*180.0/PI;
  }
  return parseFloat(e.toFixed(1));
}

function cameraMoved()
{
  var heading = bearing(panorama.getPosition(), mapCenter);
  if(heading) panorama.setPov({ heading: heading, pitch: 0, zoom: 1 });
}
        
function addMarker(latlng)
{
  var image = new g.MarkerImage("/images/mapicon.png", new g.Size(32, 32), new g.Point(0, 0), new g.Point(16, 32));
  var marker = new g.Marker({ map: map, position: latlng, icon: image });
}

var g = google.maps;
var map, panorama;
var sv = new g.StreetViewService();

function displayStreetView(data, status)
{
  if(status == g.StreetViewStatus.OK) {
    document.getElementById('streetview').style['display'] = 'block';
    panorama.setPosition(data.location.latLng);
    panorama.setVisible(true);
  } else {
    document.getElementById('streetview').style['display'] = 'none';
    panorama.setVisible(false);
  }
}

function map_initialize()
{
  var mapOptions = { zoom: 15, center: mapCenter, mapTypeId: g.MapTypeId.TERRAIN };
  map = new g.Map(document.getElementById("map"), mapOptions);
  addMarker(mapCenter);

  panorama = new g.StreetViewPanorama(document.getElementById('streetview'), { navigationControl: false });
  panorama.setPosition(mapCenter);
  map.setStreetView(panorama);

  sv.getPanoramaByLocation(mapCenter, 100, displayStreetView);

  g.event.addListener(panorama, "position_changed", cameraMoved);
}

g.event.addDomListener(window, 'load', map_initialize);

