var marker;
var overlayInstance = null;
var map;
var client;
var lastMarkerLocation;
var panorama;
var mapT;

function load() {
  client = new GStreetviewClient();
  var latlng = new GLatLng(64.859076, -147.831817);
  map = new GMap2(document.getElementById("map"));
  map.setCenter(latlng, 14);

  var guyIcon = new GIcon(G_DEFAULT_ICON);
  guyIcon.image = "http://maps.google.com/intl/en_us/mapfiles/cb/man_arrow-0.png";
  guyIcon.transparent = "http://maps.google.com/intl/en_us/mapfiles/cb/man-pick.png";
  guyIcon.imageMap = [
        26,13, 30,14, 32,28, 27,28, 28,36, 18,35, 18,27, 16,26,
        16,20, 16,14, 19,13, 22,8
     ];
  guyIcon.iconSize = new GSize(49, 52);
  guyIcon.iconAnchor = new GPoint(25, 35);  // near base of guy's feet
  guyIcon.infoWindowAnchor = new GPoint(25, 5);  // top of guy's head

  marker = new GMarker(latlng, {icon: guyIcon, draggable: true});
  map.addOverlay(marker);
  lastMarkerLocation = latlng;
  GEvent.addListener(marker, "dragend", onDragEnd);
  GEvent.addListener(marker, "click", openPanoramaBubble);
  toggleOverlay();
}

function openPanoramaBubble() {
  var contentNode = document.createElement('div');
  contentNode.style.textAlign = 'center';
  contentNode.style.width = '500px';
  contentNode.style.height = '300px';
  contentNode.innerHTML = 'Loading panorama';
  marker.openInfoWindow("<div id='pano' style='width:400px;height:200px;'></div>", {maxContent: contentNode, maxTitle: "Full screen"});

  panorama = new GStreetviewPanorama(document.getElementById("pano"));
  panorama.setLocationAndPOV(marker.getLatLng(), null);
  GEvent.addListener(panorama, "newpano", onNewLocation);
  GEvent.addListener(panorama, "yawchanged", onYawChange); 

  var iw = map.getInfoWindow();
  GEvent.addListener(iw, "maximizeend", function() {
    panorama.setContainer(contentNode);  
    window.setTimeout("panorama.checkResize()", 5);
  });
}

function toggleOverlay() {
  if (!overlayInstance) {
    overlayInstance = new GStreetviewOverlay();
    map.addOverlay(overlayInstance);
  } else {
    map.removeOverlay(overlayInstance);
    overlayInstance = null;
  }
}

function onYawChange(newYaw) {
  var GUY_NUM_ICONS = 16;
  var GUY_ANGULAR_RES = 360/GUY_NUM_ICONS;
  if (newYaw < 0) {
    newYaw += 360;
  }
  guyImageNum = Math.round(newYaw/GUY_ANGULAR_RES) % GUY_NUM_ICONS;
  guyImageUrl = "http://maps.google.com/intl/en_us/mapfiles/cb/man_arrow-" + guyImageNum + ".png";
  marker.setImage(guyImageUrl);
}

function onNewLocation(lat, lng) {
  var latlng = new GLatLng(lat, lng);
  marker.setLatLng(latlng);
}

function onDragEnd() {
  var latlng = marker.getLatLng();
  if (panorama) {
    client.getNearestPanorama(latlng, onResponse);
  }
}

function onResponse(response) {
  if (response.code != 200) {
    marker.setLatLng(lastMarkerLocation);
  } else {
    var latlng = new GLatLng(response.Location.lat, response.Location.lng);
    marker.setLatLng(latlng);
    lastMarkerLocation = latlng;
    openPanoramaBubble();
  }
}