﻿
var map;
var point;
var x;
var y;
var mapType;
var mapZoom;

var marker;

var mapTypes = [ G_NORMAL_MAP, G_SATELLITE_MAP, G_HYBRID_MAP ];


var streetPoint = null;
var streetHeading = 0;
var streetPitch = 0;
var streetZoom = 0;

var streetviewOn = false;
var streetOverlay  = null;
var streetviewClient = null;
var streetMarker = null;

var streetTitle = "";
var panorama = null;
var panInitialized = false;


function eid(id) 
{
    return document.getElementById(id); 
}

function loadPage()
{
    if (!eid("ctl00_CH1_XTextBox"))
    {
        return;
    }
    
    // get settings from page
    x = parseFloat(eid("ctl00_CH1_XTextBox").value);
    y = parseFloat(eid("ctl00_CH1_YTextBox").value);
    mapType = 2;
    
    mapZoom = parseInt(eid("ctl00_CH1_ZTextBox").value);
    
    var mapOptions = { googleBarOptions : { showOnLoad : true } };
    var mapDiv = eid("mapDiv");
    point = new GLatLng(y,x);
    
    map = new GMap2(mapDiv, mapOptions);
    map.addControl(new GMenuMapTypeControl());
    map.addControl(new GLargeMapControl());
    map.addControl(new GScaleControl());
    
    map.setCenter(point, mapZoom);
    map.setMapType(mapTypes[mapType]);
    
    map.enableDoubleClickZoom();
    map.enableContinuousZoom();   
    map.enableScrollWheelZoom();
    
    // map.enableGoogleBar();
     
    
    // Create the place marker
    marker = new GMarker(point, {"draggable":true});
    map.addOverlay(marker);
    
    GEvent.addListener(marker, "dragend", function()
   {            
        point = marker.getPoint();
        
        eid("ctl00_CH1_XTextBox").value = point.lng();
        eid("ctl00_CH1_YTextBox").value = point.lat();
        
        // change streetview heading
        streetHeading = getBearing(streetPoint, point);
        panorama.setLocationAndPOV(streetPoint, {"yaw":streetHeading,"pitch":streetPitch,"zoom":streetZoom});
        
        map.setCenter(point);
   });         

   GEvent.addListener(map, "zoomend", function()
   {            
        mapZoom = map.getZoom();
        
        eid("ctl00_CH1_ZTextBox").value = mapZoom;
   }); 
   
   GEvent.addListener(map, "moveend", function()
   {            
        var bounds = map.getBounds();
        if (!bounds.contains(point))
        {
            point = bounds.getCenter();

            marker.setLatLng(point);
            
            eid("ctl00_CH1_XTextBox").value = point.lng();
            eid("ctl00_CH1_YTextBox").value = point.lat();
        
        }
   }); 
   
   // create an empty panorama
    initPanStats();
    createPanorama(eid("panDiv"));
    initStreetViewClient();
    
    if (streetPoint != null)
    {
        initPanorama(streetPoint);
    }
    else
    {
        setTimeout("streetAutoFind();", 1);
    }
        
}



function geoFind()
{
    var address = eid("ctl00_CH1_FindAddressTextBox").value;
    
    var geoError = [];

    geoError[G_GEO_SUCCESS]            = "Success";
    geoError[G_GEO_MISSING_ADDRESS]    = "Missing Address: The address was either missing or had no value.";
    geoError[G_GEO_UNKNOWN_ADDRESS]    = "Unknown Address:  No corresponding geographic location could be found for the specified address.";
    geoError[G_GEO_UNAVAILABLE_ADDRESS]= "Unavailable Address:  The geocode for the given address cannot be returned due to legal or contractual reasons.";
    geoError[G_GEO_BAD_KEY]            = "Bad Key: The API key is either invalid or does not match the domain for which it was given";
    geoError[G_GEO_TOO_MANY_QUERIES]   = "Too Many Queries: The daily geocoding quota for this site has been exceeded.";
    geoError[G_GEO_SERVER_ERROR]       = "Server error: The geocoding request could not be successfully processed.";
    
    // Geocode the address
    var geocoder = new GClientGeocoder(new GGeocodeCache()); 

    geocoder.getLatLng(address, function(point)
    { 
        if (point)
        {
            map.setCenter(point);
            marker.setPoint(point);
            
            eid("ctl00_CH1_XTextBox").value = point.lng();
            eid("ctl00_CH1_YTextBox").value = point.lat();            
        }
        else
        {
            // Error - Display error text
            var result = geocoder.getCache().get(address);
            var reason = "";
            if (result)
            {
                var reason = "Error " + result.Status.code + " : ";
                if (geoError[result.Status.code])
                {
                    reason += geoError[result.Status.code];
                }
    
                // display geocoder error
                alert(reason);
            }
            
        }
    });

}





function initStreetViewClient()
{
    streetviewClient = new GStreetviewClient();
    streetOverlay = new GStreetviewOverlay();
    
    streetviewOn = true;
    eid("svBox").checked = true;

    // main overlay
    map.addOverlay(streetOverlay);              
    
      GEvent.addListener(this.map, "click", function(overlay,point)
      {
            if (streetviewOn)
            {
                initPanorama(point);
            }
       });
}

function clickSvBox(a)
{
    streetviewOn = a;
    if (streetviewOn)
    {
        if (!streetviewClient)
        {
            streetviewClient = new GStreetviewClient();
            streetOverlay = new GStreetviewOverlay();

            // main overlay
            map.addOverlay(streetOverlay);              
            
              GEvent.addListener(this.map, "click", function(overlay,point)
              {
                    if (streetviewOn)
                    {
                        initPanorama(point);
                    }
               });              
            
        }
        else
        {
            map.addOverlay(streetOverlay);
        }
    }
    else
    {
        map.removeOverlay(streetOverlay);
    }
}


// Create the main panorama
function createPanorama(container)
{
    if (panorama == null)
    {
        // create the panorama
        panorama = new GStreetviewPanorama(container);
        panorama.setLocationAndPOV(streetPoint, {"yaw":streetHeading,"pitch":streetPitch,"zoom":streetZoom});
        
        // listen for changes in bearing and latlng, then update marker accordingly
        GEvent.addListener(panorama,"yawchanged",function(a)
             {
                streetHeading = parseFloat(a);
                updateStreetMarker();
                updatePanStats();                
             });

        GEvent.addListener(panorama,"pitchchanged",function(a)
             {
                streetPitch = parseFloat(a);
                updatePanStats();                

             });

        GEvent.addListener(panorama,"zoomchanged",function(a)
             {
                streetZoom = parseInt(a);
                updatePanStats();                
             });

        GEvent.addListener(panorama,"initialized",function(a)
             {
                streetPoint= a.latlng;
                streetTitle = a.description;
                
                updateStreetMarker();
                updatePanStats();
             }); 
    }
}


// find nearest panorama      
function initPanorama(point)
{
    if (!panInitialized)
    {
        panInitialized = true;
    }

    // change current point (note, if a nearby street view is found then the latlng will be updated to the latlng of the streetview)
    streetviewClient.getNearestPanorama(point, initPanorama2);
}

// callback function for initPanorama() - change panorama view to specified latlong
function initPanorama2(param)
{
    if (param)
    {    
        var location = param.location;
        streetPoint = location.latlng;
        streetTitle = location.description; 
        
        // calculate new street heading
        streetHeading = getBearing(streetPoint, point);
                       
        panorama.setLocationAndPOV(streetPoint, {"yaw":streetHeading,"pitch":streetPitch,"zoom":streetZoom});
        
        updateStreetMarker();
        updatePanStats();
    }
            
}

function initPanStats()
{
    var x = parseFloat(eid("ctl00_CH1_SVXTextBox").value);
    var y = parseFloat(eid("ctl00_CH1_SVYTextBox").value);
    
    if (x != 0 || y != 0)
    {
        streetPoint = new GLatLng(y,x);
    }
    
    streetHeading = parseInt(eid("ctl00_CH1_SVBTextBox").value);
    streetPitch = parseInt(eid("ctl00_CH1_SVPTextBox").value);
    streetZoom = parseInt(eid("ctl00_CH1_SVZTextBox").value);
}

function updatePanStats()
{
    eid("ctl00_CH1_SVXTextBox").value = streetPoint.lng();
    eid("ctl00_CH1_SVYTextBox").value = streetPoint.lat();
    
    eid("ctl00_CH1_SVBTextBox").value =  parseInt(streetHeading);
    eid("ctl00_CH1_SVPTextBox").value =  parseInt(streetPitch);
    eid("ctl00_CH1_SVZTextBox").value =  parseInt(streetZoom);
}

function updateStreetMarker()
{
    // add marker to indicate street view position
    if (!streetMarker)
    {
        // Create Street View Dude Marker
        var l_icon = new GIcon();

        var l_imageNum = Math.round(streetHeading/22.5) % 16;
        var l_imageUrl = "img/streetview/panda-" + l_imageNum + ".png";
        
        l_icon.image = l_imageUrl;
        l_icon.iconSize = new GSize(49,52);

        l_icon.printImage = l_icon.image;
        l_icon.mozPrintImage = l_icon.image;
        l_icon.iconAnchor =  new GPoint(25,36);
        l_icon.infoWindowAnchor = new GPoint(25,6);        
        
        streetMarker = new GMarker(streetPoint, {"icon":l_icon, "draggable":true});
         
        // draggable listener for gmap marker
        GEvent.addListener(streetMarker, "dragend", function()
        {            
            streetPoint = streetMarker.getPoint();
            initPanorama(streetPoint);                
        });              
        
        map.addOverlay(streetMarker);
    }
    else
    {
        // Update Street View Title

        // update image and location of marker
        var l_imageNum = Math.round(streetHeading/22.5) % 16;
        var l_imageUrl = "img/streetview/panda-" + l_imageNum + ".png";
        
        streetMarker.setImage(l_imageUrl);
        streetMarker.setPoint(streetPoint);
    }


}



function getBearing(p1, p2)
{
    var angle = null;
    if (p1 != null && p2 != null && !p1.equals(p2))
    {
        var y1 = p1.latRadians();
        var x1 = p1.lngRadians();
        var y2 = p2.latRadians();
        var x2 = p2.lngRadians();
        
        var a = Math.sin(x1-x2) * Math.cos(y2);
        var b = Math.cos(y1)*Math.sin(y2) - Math.sin(y1)*Math.cos(y2)*Math.cos(x1-x2);
        
        angle = -(Math.atan2(a,b));
        if (angle < 0.0)
        {
            angle += Math.PI*2.0;
        }        
    }
    return parseInt(angle * 180.0 / Math.PI);
}

// reset streetview settings to 0 so street view will not be displayed for venue
function streetReset()
{
    eid("ctl00_CH1_SVXTextBox").value = 0;
    eid("ctl00_CH1_SVYTextBox").value = 0;
    
    eid("ctl00_CH1_SVBTextBox").value = 0;
    eid("ctl00_CH1_SVPTextBox").value = 0;
    eid("ctl00_CH1_SVZTextBox").value = 0;
}

function streetAutoFind()
{
    x = parseFloat(eid("ctl00_CH1_XTextBox").value);
    y = parseFloat(eid("ctl00_CH1_YTextBox").value);

    point = new GLatLng(y,x);
    
    streetReset();
    
    initPanorama(point)
}


