var lastPanoId = null;         // 最後にいた場所のPanoID
var nowLatLng;
var streetViewClient;
var streetPanorama;
var moveInterval;

function initPanorama(lat, lng){
   streetViewClient = new GStreetviewClient;
   streetPanorama = new GStreetviewPanorama(document.getElementById("pano"));
   nowLatLng = new GLatLng(lat, lng);
   streetViewClient.getNearestPanoramaLatLng(nowLatLng, function(latlng){
	if(latlng == null){
	    document.getElementById("pano").style.display = "none";
	    document.getElementById("pano_desp").style.display = "none";
            return;
        }
	nowLatLng = latlng;
        streetPanorama.setLocationAndPOV(nowLatLng, {yaw: 0, pitch: 0, zoom: -1}); 
        // 5秒後に移動
        moveInterval = setInterval(toNextPanorama, 5000);
   })

}

// 現在の表示位置から一番近いStreetViewDataを取得し、そこから隣接するパノラマに移動する
function toNextPanorama(){
   clearInterval(moveInterval);
   // 現在の表示位置の緯度経度を取得
   streetViewClient.getNearestPanorama(nowLatLng, function(streetData){

        var neighbourCount = streetData.links.length; // 隣接するパノラマの数

        var nextYaw; // 次に向かう方向
	var nextPanoId; // 次に向かうパノラマのID
	if(neighbourCount == 1){
            // 隣接するパノラマが１つだった場合はそこへ移動
            nextYaw = streetData.links[0].yaw;
	    nextPanoId = streetData.links[0].panoId;
        }else{
           while(true){
               i = Math.floor( Math.random() * neighbourCount );
               if(lastPanoId != streetData.links[i].panoId){
                    nextPanoId = streetData.links[i].panoId;
                    nextYaw = streetData.links[i].yaw;
                    break;
               }
           }
        }
        lastPanoId = streetData.location.panoId;     // 今いた場所を覚えておく
        streetViewClient.getPanoramaById( nextPanoId,
                                          function(nextStreetData){
                                              nowLatLng = nextStreetData.location.latlng;
                                              // 目的地へGO！
                                              //streetPanorama.setLocationAndPOV( nowLatLng, {yaw:nextYaw, pitch:0, zoom:-1});
                                              streetPanorama.followLink(nextYaw);
                                              //streetPanorama.setPOV({yaw:nextYaw, pitch:0, zoom:-1});
                                              moveInterval = setInterval(toNextPanorama, 5000);
                                          }
                                         );
        // 目的地へGO！
        // streetPanorama.followLink(nextYaw);
   }
   );
}

