var map=null;
var pano=null;
var pano_client=null;
var pano_marker=null;
var geocoder=null;
var center=null;
var mapInfo=null;
var location_pov_yaw   = null;
var location_pov_pitch = null;

var zoom=16;

function load(address){
	if (GBrowserIsCompatible()) {
		geocoder = new GClientGeocoder();
		//get latitude and longitude
		geocoder.getLatLng(
			address,
			function(point){
				if(!point){
					geocoder_err();
					return;
				}
				//set latlng
				center=point;
				//create map
				map = new GMap2(document.getElementById("map"));
				//center map
				map.setCenter(center,zoom);
				/*
				//add marker to map
				var marker = new GMarker(center);
				map.addOverlay(marker);
				*/
				//open info for building
				if(mapInfo!=null){
					infoOpts = { 'noCloseOnClick' : true };
					map.openInfoWindowHtml(center,mapInfo,infoOpts);
				}
				//add controls
				map.addControl(new GSmallMapControl());
				map.addControl(new GMapTypeControl());
				//update street view when map is clicked
				GEvent.addListener(map, "click", function(overlay, latlng) {
					if (overlay) {
						return;
					}
					map.panTo(latlng);
					pano_client.getNearestPanorama(latlng, pano_updated);
				});
				//move street view when map is dragged
				/*GEvent.addListener(map, "dragend", function() {
					pano_client.getNearestPanorama(map.getCenter(), pano_updated);
				});*/
				//make streetview
				pano_client = new GStreetviewClient();
				pano_client.getNearestPanorama(center, pano_updated);
			}
		);
	}
}

//called when street view data is found
function pano_updated(pano_data){
	if(pano_data.code==200){
		if(!pano){
			init_pano(pano_data.location);
		} else {
			if(pano.isHidden()) pano.show();
			pano.setLocationAndPOV(pano_data.location.latlng,pano_data.location.pov);
			pano_marker.setLatLng(pano_data.location.latlng);
		}
	} else {
		if(pano) pano.hide();
	}
}

function init_pano(location){
	panoOpts = { latlng:location.latlng, pov:location.pov };
	pano = new GStreetviewPanorama(document.getElementById("pano"), panoOpts);
	GEvent.addListener(pano, "error", pano_err);
	GEvent.addListener(pano, "initialized", function(location) {
		map.panTo(location.latlng);
		pano_marker.setLatLng(location.latlng);
	});
	//TODO make streetview marker different from address marker
	pano_marker = new GMarker(location.latlng);
	map.addOverlay(pano_marker);
}

function geocoder_err(){
	//do nothing for now
}

function pano_err(){
	//street view cannot be displayed correctly
	pano.hide();
}


