// Google Map
var map = null;
var geocoder = null;
var myPano;
var panoClient;
var marker;
	
    function load(address) {
      if (GBrowserIsCompatible()) {
        map = new GMap2(document.getElementById("map"));
		map.addControl(new GSmallMapControl());
        geocoder = new GClientGeocoder();
		showAddress(address, address);
      }
    }

    function showAddress(address, msg) {
      if (geocoder) {
        geocoder.getLatLng(
          address,
          function(point) {
            if (!point) {
				document.getElementById("map").style.display = 'none';
				document.getElementById("pano").style.display = 'none';
            } else {
			  marker = createMarker(point, msg)
			  map.setCenter(point, 8);
			  map.addOverlay(marker);
			  
			  panoClient = new GStreetviewClient(); 
     		  myPano = new GStreetviewPanorama(document.getElementById("pano"));
			  panoClient.getNearestPanorama(marker.getLatLng(), showPanoData);
            }
          }
        );
      }
    }
	
	function createMarker(point, msg) {
  		var marker = new GMarker(point);
  		GEvent.addListener(marker, "click", function() {
    		marker.openInfoWindowHtml(msg);
  		});
  	return marker;
	}
	
	function showPanoData(panoData) {
      if (panoData.code != 200) {
       // GLog.write('showPanoData: Server rejected with code: ' + panoData.code);
	   document.getElementById("pano").style.display = 'none';
        return;
      }
      var angle = computeAngle(marker.getLatLng(), panoData.location.latlng);
      myPano.setLocationAndPOV(panoData.location.latlng, {yaw: angle});
    }

    function computeAngle(endLatLng, startLatLng) {
      var DEGREE_PER_RADIAN = 57.2957795;
      var RADIAN_PER_DEGREE = 0.017453;

      var dlat = endLatLng.lat() - startLatLng.lat();
      var dlng = endLatLng.lng() - startLatLng.lng();
      // We multiply dlng with cos(endLat), since the two points are very closeby,
      // so we assume their cos values are approximately equal.
      var yaw = Math.atan2(dlng * Math.cos(endLatLng.lat() * RADIAN_PER_DEGREE), dlat)
             * DEGREE_PER_RADIAN;
      return wrapAngle(yaw);
   }

	function wrapAngle(angle) {
    	if (angle >= 360) {
    		angle -= 360;
   		 } else if (angle < 0) {
    		angle += 360;
    	}
   		return angle;
  }