# -*- coding: iso-8859-1 -*-
"""
    MoinMoin - GetStreetView Macro
    Tool to get lat, lng, yaw, pitch and zoom for GoogleStreetView macro.
    ver 1.2
    by JasonMcArthur <jason@denied.to>
    1.4 - removed some nasty, added reverse geo and update on zoom.
    1.2 - no timeOut() on stats output so user can select it.

"""

def execute(macro,text):
    gkey = 'ABQIAAAA7rwZfsyEYZknlS0QWmZI4RQb5vo-4Bph0C_4e_e9IEgkaF03hxSX2F6kxStG0StGHPlKCc7vTMZJQQ'
    gkey2 = 'ABQIAAAA7rwZfsyEYZknlS0QWmZI4RQb5vo-4Bph0C_4e_e9IEgkaF03hxSX2F6kxStG0StGHPlKCc7vTMZJQQ'
    math = '%'
    html = '''
<script type="text/javascript">
    // set proper key for www. and wiki. subdomains.
    if( (window.location.href).indexOf("www.") == -1 ) {
        writeScript("%s");  
    } else { 
        writeScript("%s");}                                                    
function writeScript(key) {var ret='<'+'script src="http://maps.google.com/maps?file=api&v=2.x&key='+key+'"'+'type="text/javascript"><'+'/script>';document.write(ret);}  
</script> 
    <script type="text/javascript"> 
    var map;
    var myPano;   
    var panoClient;
    var nextPanoId;
    var center = new GLatLng(45.52310,-122.67133);

    function initMap() {
      panoClient = new GStreetviewClient();      
      // setup and configure map
      map = new GMap2(document.getElementById("mapDiv"));
      map.setMapType(G_HYBRID_MAP);
      map.addControl(new GScaleControl());
      map.addControl(new GMapTypeControl());
      map.addControl(new GSmallMapControl());
      map.setCenter(center, 15);
      map.enableContinuousZoom();      
      map.enableScrollWheelZoom();
      
      // setup draggable and rotating guy icon
      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(center, {icon: guyIcon, draggable: true});
      map.addOverlay(marker);
      lastMarkerLocation = center;
      GEvent.addListener(marker, "dragend", onDragEnd);
      GEvent.addListener(marker, "click", showPanoData);

      // update streetview client when location is selected on map
      GEvent.addListener(map, "click", function(overlay,latlng) {
        panoClient.getNearestPanorama(latlng, showPanoData);
        marker.setLatLng(latlng);
      });

      // setup and configure streetview client
      var POV = {yaw:0,pitch:-5};
      panoClient = new GStreetviewClient(); 
      myPano = new GStreetviewPanorama(document.getElementById("pano"));
      myPano.setLocationAndPOV(center, POV);
      GEvent.addListener(myPano, "error", handleNoFlash);  
      panoClient.getNearestPanorama(center, showPanoData);
      GEvent.addListener(myPano, "yawchanged", showStats);
      GEvent.addListener(myPano, "yawchanged", onYawChange);
      GEvent.addListener(myPano, "zoomchanged", showStats);
      // update map as user moves locations in the streetview client
      GEvent.addListener(myPano, "initialized", function(call) {
      var center = call.latlng;
      map.setCenter(center);
      marker.setLatLng(center);
      panoClient.getNearestPanorama(center, showPanoData);
      });
      showStats();
    }
    
    function showPanoData(panoData) {
      // get and fill out infowindow
      if (panoData.code != 200) {
        GLog.write('showPanoData: Server rejected with code: ' + panoData.code);
        return;
      }
      myPano.setLocationAndPOV(panoData.location.latlng);
      GEvent.addListener(myPano, "newpano", onNewLocation);
      showStats();
    }

    function showStats() {
      // return POV and coords    
      var geocoder = null;
      geocoder = new GClientGeocoder();
      var stats = "";            
      var pov = myPano.getPOV();
      estats = "&lt;&lt;GoogleStreetView" + marker.getLatLng() + "," + pov.yaw + "," + pov.pitch + "," + pov.zoom;
      stats = estats.replace(/( |\))/g, "");
      document.getElementById("statDiv").innerHTML = stats + ")&gt;&gt;";
      point = marker.getLatLng();      
      // Reverse Geocoder
      geocoder.getLocations(point, function(addresses) {
        if(addresses.Status.code != 200) {
          document.getElementById("statDesc").innerHTML = "<br />No address found";
        } else {
          address = addresses.Placemark[0];
          var myHtml = address.address;
          document.getElementById("statDesc").innerHTML = "<br />" + myHtml;
        }
      });
    }

    function next() {
      // Get the next panoId
      panoClient.getPanoramaById(nextPanoId, showPanoData, showStats);
    }
    
    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) %s GUY_NUM_ICONS;
      guyImageUrl = "http://maps.google.com/intl/en_us/mapfiles/cb/man_arrow-" + guyImageNum + ".png";
      //guyImageUrl = "http://maps.google.com/intl/en_us/mapfiles/cb/man_arrow-16,14.png";
      marker.setImage(guyImageUrl);
    }

    function onNewLocation(lat, lng) {
      var center = new GLatLng(lat, lng);
      marker.setLatLng(center);
      showStats();
    }
 
    function onDragEnd() {
      var center = marker.getLatLng();
      if (myPano) {
        panoClient.getNearestPanorama(center, onResponse);
        showStats();
      }
    }

    function onResponse(response) {
      if (response.code != 200) {
        marker.setLatLng(lastMarkerLocation);
      } else {
        var center = new GLatLng(response.Location.lat, response.Location.lng);
        marker.setLatLng(center);
        lastMarkerLocation = center;
        panoClient.getNearestPanorama(center, showPanoData);
        myPano.setLocationAndPOV(marker.getLatLng(), null)
        showStats();
      }
    }

    function handleNoFlash(errorCode) {
      if (errorCode == FLASH_UNAVAILABLE) {
        alert("Error: Flash doesn't appear to be supported by your browser");
        return;
      }
    }  
    </script>
    <script type="text/javascript">
        window.onload = initMap
        window.onunload=GUnload
    </script>
<span id="statDiv" style=""></span>
<span id="statDesc" style=""></span>
<span id="statLink"></span>
<div id="pano" style="width:350px;height:350px;border:1px solid #000;float:left;"></div>
<div id="mapDiv" style="width350px;height:350px;border:1px solid #000;margin-left:355px;"></div>
    ''' % (gkey, gkey2, math)
    return html
