﻿//Copyright © 2008 by Sergio Tobon - http://www.pinmaps.net

var guyMarker;
var overlayInstance = null;
var client;
var lastMarkerLocation;
var panorama;

function StreetViewLayer(map) {
  var me = this;
  me.map = map;
  me.enabled = false;
  
  client = new GStreetviewClient();
  var center = map.getCenter();
  var latlng = new GLatLng(center.y, center.x);
  
  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.image = "http://maps.gstatic.com/mapfiles/cb/man_arrow-0.png";
  guyIcon.transparent = "http://maps.gstatic.com/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

  guyMarker = new GMarker(latlng, {icon: guyIcon, draggable:true, title: ["Drag me onto a blue outlined street"]});
  lastMarkerLocation = latlng;
  
  GEvent.addListener(guyMarker, "dragstart", function() {
     guyMarker.closeInfoWindow();
     document.getElementById("lblPano").innerHTML = '';
  });
  GEvent.addListener(guyMarker, "dragend", function() {
     checkData();
  });
  GEvent.addListener(guyMarker, "click", function() {
     checkData();
  });
  GEvent.addListener(map, "infowindowclose", function() {
     document.getElementById("lblPano").innerHTML = '';
  });
  
  function openPanoramaBubble() {
      var contentNode = document.createElement('div');
      contentNode.style.textAlign = 'center';
      contentNode.style.width = '650px';
      contentNode.style.height = '400px';
      contentNode.innerHTML = 'Loading panorama';
      //guyMarker.openInfoWindow("<input id='chkShowPath' type='checkbox' /><span class='spnShowMarkers'>draw my path on the map</span><br><div id='pano' style='width:350px;height:250px;'></div>", {maxContent: contentNode, maxTitle: "<span id='spnStreet'></span>&nbsp;&nbsp;&nbsp;<input id='chkShowPath' type='checkbox' /><span class='spnShowMarkers'>draw my path on the map</span>"});
      guyMarker.openInfoWindow("<input id='chkShowPath' type='checkbox' checked='true' /><span class='spnShowMarkers'>draw my path on the map</span>&nbsp;&nbsp;&nbsp;<span id='spnStreet'></span><br><div id='pano' style='width:650px;height:375px;'></div>");
      ShowPanoMsg();
      document.getElementById("lblPano").innerHTML = '&nbsp;<img src="Images/wand.png" style="vertical-align:-4px" alt="tip" /> <b>Tip:</b> once you have clicked inside the streetview you can then use your keyboard keys to navigate.&nbsp;';
 
      panorama = new GStreetviewPanorama(document.getElementById("pano"));
      var agt=navigator.userAgent.toLowerCase();
      if (agt.indexOf("msie") != -1){
          var panoflash;
          for (var i = 0; i < 50; i++) {
               panoflash = 'panoflash' +i;
               window[panoflash] = new Object();
               //GLog.write("Panoflash Value: " + panoflash); 
          }      
      }
      window.setTimeout('panorama.setLocationAndPOV(guyMarker.getLatLng())', 5);   // give time to load the pano div
      
      GEvent.addListener(panorama, "newpano", onNewLocation);
      GEvent.addListener(panorama, "yawchanged", onYawChange);
      GEvent.addListener(panorama,"initialized",function(loc) {
        
        guyMarker.setLatLng(loc.latlng);
        var offset = new GSize(0,-30); //infoWindowAnchor minus iconAnchor
        map.getInfoWindow().reset(guyMarker.getLatLng(), null, new GSize(650,394), offset, null);
        
        var pano_yaw = panorama.getPOV().yaw;
        panmeTo(pano_yaw);
        //GLog.write("getPOV().yaw: " + pano_yaw); 
        
        var chklay = document.getElementById('chkShowPath');
        if (chklay.checked == true){;
           var path = new GPolyline([lastMarkerLocation,loc.latlng]);
           path.color = "#ff0000";
           map.addOverlay(path);
        }
        //var road = "You are currently driving along " + loc.description;
        //document.getElementById("spnStreet").innerHTML = road.toString();
        lastMarkerLocation = loc.latlng;
      });
      //var iw = map.getInfoWindow();
      //GEvent.addListener(iw, "maximizeend", function() {
      //  panorama.setContainer(contentNode); 
      //  window.setTimeout("panorama.checkResize()", 5);
      //});
    }
    
    function panmeTo(yaw){
        
        var dx;  //Horizontal
        var dy;  //Vertical
        
        if ((yaw > 383)&&(yaw < 427)||(yaw > 23)&&(yaw < 67)) {  //NorthEast
            dx = -13;
            dy = 13;
            map.panBy(new GSize(dx, dy));
            //GLog.write("Move NorthEast");
            
        } else if ((yaw >= 337)&&(yaw <= 383)||(yaw >= 0)&&(yaw <= 23)||(yaw >= 697)&&(yaw <= 743)) {  //North
            dx = 0;
            dy = 5;
            map.panBy(new GSize(dx, dy));
            //GLog.write("Move North");
            
        } else if ((yaw > 293)&&(yaw < 337)||(yaw > 653)&&(yaw < 697)) {  //NorthWest
            dx = 13;
            dy = 13;
            map.panBy(new GSize(dx, dy));
            //GLog.write("Move NorthWest");
            
        } else if ((yaw >= 247)&&(yaw <= 293)||(yaw >= 607)&&(yaw <= 653)) {  //West
            dx = 13;
            dy = 0;
            map.panBy(new GSize(dx, dy));
            //GLog.write("Move West");
            
        } else if ((yaw > 203)&&(yaw < 247)||(yaw > 563)&&(yaw < 607)) {  //SouthWest
            dx = 13;
            dy = -13;
            map.panBy(new GSize(dx, dy));
            //GLog.write("Move SouthWest");
            
        } else if ((yaw >= 157)&&(yaw <= 203)||(yaw >= 517)&&(yaw <= 563)) {  //South
            dx = 0;
            dy = -13;
            map.panBy(new GSize(dx, dy));
            //GLog.write("Move South");
            
        } else if ((yaw > 473)&&(yaw < 517)||(yaw > 113)&&(yaw < 157)) {  //SouthEast
            dx = -13;
            dy = -13;
            map.panBy(new GSize(dx, dy));
            //GLog.write("Move SouthEast");
            
        } else if ((yaw >= 427)&&(yaw <= 473)||(yaw >= 67)&&(yaw <= 113)) {  //East
            dx = -13;
            dy = 0;
            map.panBy(new GSize(dx, dy)); 
            //GLog.write("Move East"); 
                   
        } else {  //No value then don't move                               
            dx = 0;
            dy = 0;
            map.panBy(new GSize(dx, dy));
            //GLog.write("Value not found");         
        }
    }
    
    // GStreetviewPanorama Camera Angle (yaw)
    //(383 - 405 - 427)(23 - 45 - 67)    NorthEast (44)  (dx dy) 0 13 Move to the NorthEast
    //(338 - 360 - 382)(338 - 0 - 22)    North     (44)  (dx dy) 0 13 Move to the North     
    //(293 - 315 - 337)(293 - 315 - 337) NorthWest (44)  (dx dy) 0 13 Move to the NorthWest
    //(248 - 270 - 292)(248 - 270 - 292) West      (44)  (dx dy) 13 0 Move to the West       
    //(203 - 225 - 247)(203 - 225 - 247) SouthWest (44)  (dx dy) 0 13 Move to the SouthWest
    //(518 - 180 - 202)(158 - 180 - 202) South     (44)  (dx dy) 0 -13 Move to the South    
    //(473 - 495 - 517)(113 - 135 - 157) SouthEast (44)  (dx dy) 0 13 Move to the SouthEast
    //(428 - 450 - 472)(68 - 90 - 112)   East      (44)  (dx dy) -13 0 Move to the East       
    
    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";
      guyMarker.setImage(guyImageUrl);
      //GLog.write("onYawChange(newYaw): " + newYaw); 
    }
    
    function onNewLocation(lat, lng) {
      var latlng = new GLatLng(lat, lng);
      marker.setLatLng(latlng);
    }
    
    function checkData() {
      var latlng = guyMarker.getLatLng();
      client.getNearestPanorama(latlng, onResponse);
    }
    
    function onResponse(response) {
      if (response.code != 200) {
        guyMarker.setLatLng(lastMarkerLocation);
        guyMarker.openInfoWindow("<div id='pano' style='width:300px;height:60px;'><h3>Street View</h3>No panorama image available for that location.<br>Drag me onto a blue outlined street.</div>");
      } else if (response.code == 200) {
        var latlng = new GLatLng(response.Location.lat, response.Location.lng);
        guyMarker.setLatLng(latlng);
        lastMarkerLocation = latlng;
        openPanoramaBubble();
      }
    }
  
    function toggleOverlay() {
      if (!overlayInstance) {
        overlayInstance = new GStreetviewOverlay();
        map.addOverlay(overlayInstance);
        map.addOverlay(guyMarker);
        //guyMarker.openInfoWindow("<div id='pano' style='width:350px;height:90px;'><span style='font-size:14px; font-weight:bold'>Street View</span><br><br><span class='spnShowMarkers'>The Stret View service is only available in some U.S. cities.</span><br><br>Make sure that I'm standing on a blue outlined street<br>otherwise click <a href='#'>here</a> to jump to a Street View location.</div>");
        guyMarker.openInfoWindow("<div id='pano' style='width:350px;height:90px;'><span style='font-size:14px; font-weight:bold'>Street View</span><br><br><span class='spnShowMarkers'>The Stret View service is only available in some U.S. cities.</span><br>Make sure that I'm standing on a blue outlined street.</div>");
      } else {
        map.removeOverlay(overlayInstance);
        map.removeOverlay(guyMarker);
        overlayInstance = null;
        document.getElementById("lblPano").innerHTML = '';
      }
    }

//    // We have to do this so that we can sense if traffic is in view
//    GEvent.addListener(overlayInstance, "changed", function(hasStreetviewData) {
//        if (hasStreetviewData) {
//            alert('Street Data Available');
//        } else {
//            alert('No Street Data Available');
//        }
//    });
    
    StreetViewLayer.prototype.enable = function() {
        this.enabled = true;
        toggleOverlay();
    }

    StreetViewLayer.prototype.disable = function() {
        this.enabled = false;
        toggleOverlay();
        HidePanoMsg();
    }

    StreetViewLayer.prototype.getEnabled = function() {
        return this.enabled;
    }
}


//    var map;
//    var geoXml;
//    var toggleState = 1;

//	function initialize() {
//  	  if (GBrowserIsCompatible()) {
//  	    geoXml = new GGeoXml("http://api.flickr.com/services/feeds/groups_pool.gne?id=322338@N20&format=rss_200&georss=1");
//        map = new GMap2(document.getElementById("map_canvas"));
//        map.setCenter(new GLatLng(49.496675,-102.65625), 3); 
//        map.addControl(new GLargeMapControl());
//        map.addControl(new GLargeMapControl());
//        map.addOverlay(geoXml);
//  	  }
//	} 

//	function toggleMyKml() {
//  	  if (toggleState == 1) {
//    	map.removeOverlay(geoXml);
//    	toggleState = 0;
//  	  } else {
//   		map.addOverlay(geoXml);
//    	toggleState = 1;
//  	  }
//	}

//        var currentLocation;
//        var startPoint = new GLatLng(40.765539, -73.975967);
//        currentLocation = createCarMarker(startPoint);
//        map.addOverlay(currentLocation);
//       
//        // Pan the map back to the original start location
//        map.panTo(startPoint, 15);
//        // Set the virtual car location back to the start location
//        currentLocation.setLatLng(startPoint);

//        var func_newLat = currentLocation.getLatLng().lat();
//        var func_newLng = currentLocation.getLatLng().lng();
//        
//        // move the current virtual car GMarker
//        currentLocation.setLatLng(new GLatLng(func_newLat, func_newLng));
//        
//        function checkBounds()
//        {
//         var polyBounds = polygon.getBounds();
//         if (!map.getBounds().containsBounds(polyBounds))
//         {
//            map.panTo(currentLocation.getLatLng());
//         }
//       }


//function start() {
//	var map = new GMap2(document.getElementById("mapContainer"));
//	map.addControl(new GLargeMapControl());
//	map.addControl(new GMapTypeControl());
//	map.addControl(new GScaleControl());
//	map.setCenter(new GLatLng(53.763325,-2.579041), 9);
//	new GKeyboardHandler(map);
//	map.enableDragging();    
//}
//function setKeys() {
//	var event = {srcElement: mapContainer, target: mapContainer, nodeType: 1}; 
//	GEvent.trigger(document, "click", event); 
//}
//function noKeys() {
//	var event = {srcElement: body, target: body, nodeType: 1}; 
//	GEvent.trigger(document, "click", event); 
//}

//        var pano_pitch = panorama.getPOV().pitch;
//        var pano_zoom = panorama.getPOV().zoom;
//        var pano_link = panorama.followLink(pano_yaw);
//        var point1 = map.fromContainerPixelToLatLng(guyLatLng);
//        var point2 = map.fromLatLngToContainerPixel(guyLatLng);
//        var point3 = map.fromLatLngToDivPixel(guyLatLng);
//        var point4 = map.fromDivPixelToLatLng(guyLatLng);
//        var bounds = map.getBounds();
//        var southWest = bounds.getSouthWest();
//        var northEast = bounds.getNorthEast();
//        var lngSpan = northEast.lng() - southWest.lng();
//        var latSpan = northEast.lat() - southWest.lat();
//		  GLog.write("fromContainerPixelToLatLng(pixel): " + point1);
//		  GLog.write("fromLatLngToContainerPixel(latlng): " + point2);
//        GLog.write("fromLatLngToDivPixel(latlng) :" + point3);
//        GLog.write("fromDivPixelToLatLng(pixel): " + point4);
//        GLog.write("guyMarker.getLatLng(): " + guyLatLng);
//        GLog.write("map.getCenter(): " + map.getCenter());
//        GLog.write("");
//        GLog.write("map.getBounds(): " + bounds);
//        GLog.write("bounds.getSouthWest(): " + southWest);
//        GLog.write("bounds.getNorthEast(): " + northEast);
//        GLog.write("northEast.lng() - southWest.lng(): " + lngSpan);
//        GLog.write("northEast.lat() - southWest.lat(): " + latSpan);
//        GLog.write("");
//        GLog.write("getPOV().pitch: " + pano_pitch);
//        GLog.write("getPOV().zoom: " + pano_zoom);
//        map.panTo(guyLatLng);

//        var polyline = new GPolyline([new GLatLng(53.4807, -2.2344),new GLatLng(51.5002, -0.1262)], "#ff0000", 3);
//        map.addOverlay(polyline);


//  function clickPanoWindow() {
//      guyMarker.openInfoWindow("<input id='chkShowPath' type='checkbox' /><span class='spnShowMarkers'>draw my path on the map</span>&nbsp;&nbsp;&nbsp;<span id='spnStreet'></span><br><div id='pano' style='width:650px;height:375px;'></div>");
//      document.getElementById("lblPano").innerHTML = '<img src="Images/wand.png" style="vertical-align:-4px" alt="tip" /> <b>Tip:</b> once you have clicked inside the streetview you can then use your keyboard keys to navigate.';
// 
//      pano = new GStreetviewPanorama(document.getElementById("pano"));
//      window.setTimeout("pano.setLocationAndPOV(guyMarker.getLatLng())", 5);   // give time to load the pano div
//      
//      GEvent.addListener(panorama, "newpano", onNewLocation);
//      GEvent.addListener(panorama, "yawchanged", onYawChange);
//      GEvent.addListener(panorama,"initialized",function(loc) {
//        guyMarker.setLatLng(loc.latlng);
//        var offset = new GSize(0,-30); //infoWindowAnchor minus iconAnchor
//        map.getInfoWindow().reset(guyMarker.getLatLng(), null, new GSize(650,394), offset, null);
//        var chklay = document.getElementById('chkShowPath');
//            if (chklay.checked == true){;
//               var path = new GPolyline([lastMarkerLocation,loc.latlng]);
//               path.color = "#ff0000";
//               map.addOverlay(path);
//            }
//        var road = "You are currently walking along " + loc.description;
//        document.getElementById("spnStreet").innerHTML = road.toString();
//        lastMarkerLocation = loc.latlng;
//      });
//    }

//  GEvent.addListener(map,"click", function(overlay,latlng) {
//    panorama.setLocationAndPOV(latlng);
//  });
//  GEvent.addListener(map,"click", function() {
//    clickPanoWindow();
//  });




