﻿// JScript File
function IgnoreZeroLatLongs(bIgnore)
{
    //Check if there is any visible pushpin on map.
    var cnt = 0;
    bounds = new GLatLngBounds();
    for (var i = 0; i < markers.getLength(); i++)
    {
        var ignoremarker = false;
        var point1 = markers.markers[i].getPoint();
        if (bIgnore)
        {
            if ((point1.x == 0) && (point1.y == 0))
            {
                ignoremarker = true;
            }
        }
        if (!ignoremarker)
        {
            if (!markers.markers[i].isHidden())
            {
                bounds.extend(markers.markers[i].getPoint());
                //Increment visible pushpin count
                cnt++;
            }
        }

    }
    var iZoomLevel = map.getBoundsZoomLevel(bounds);
    var point = bounds.getCenter();

    map.setZoom(iZoomLevel);
    map.setCenter(point);

}

function ShowFullScreenMap()
{

    var objButton = document.getElementById('btnFullScreen');
    if (objButton.value == 'Full Screen')
    {
        var objMap = document.getElementById('GoogleMap_Div');
        var objDiv = document.getElementById('GoogleMap_Div_Container');
        objMap.style.width = '100%';
        objMap.style.height = '100%';

        objDiv.style.position = 'absolute';
        objDiv.style.left = '0px';
        objDiv.style.top = '0px';
        objDiv.style.width = '99%';
        objDiv.style.height = '95%';
        objDiv.style.backgroundColor = 'LightGrey';

        objButton.value = 'Close Fullscreen';
        DrawGoogleMap();
    }
    else
    {
        var objMap = document.getElementById('GoogleMap_Div');
        var objDiv = document.getElementById('GoogleMap_Div_Container');
        objMap.style.width = '<%=GoogleMapObject.Width %>';
        objMap.style.height = '<%=GoogleMapObject.Height %>';

        objDiv.style.position = '';
        objDiv.style.left = '';
        objDiv.style.top = '';
        objDiv.style.width = '';
        objDiv.style.height = '';

        objButton.value = 'Full Screen';
        //DrawGoogleMap();
    }
}


function fMarkers()
{
    this.markers = new Array();
    this.getLength = function() { return this.markers.length; };
    this.pushValue = function(v) { this.markers.push(v); }
    this.getValue = function(i) { return this.markers[i]; }
    this.getLastValue = function() { return this.markers[this.markers.length - 1]; }
    this.getValueById = function(ID)
    {
        var i;
        for (i = 0; i < this.markers.length; i++)
        {
            if (this.markers[i].value == ID)
            {
                // alert('marker found : '+this.markers[i].value);
                return this.markers[i];
            }
        }
        return null;
    }
    this.removeValueById = function(ID)
    {
        var i;
        for (i = 0; i < this.markers.length; i++)
        {
            if (this.markers[i].value == ID)
            {
                // alert('marker found : '+this.markers[i].value);
                this.markers.splice(i, 1);
                //alert('changed marker removed');

            }
        }
        return null;
    }
}

function fPolylines()
{
    this.polylines = new Array();
    this.polylinesID = new Array();
    this.getLength = function() { return this.polylines.length; };
    this.pushValue = function(v, ID) { this.polylines.push(v); this.polylinesID.push(ID); }
    this.getValue = function(i) { return this.polylines[i]; }
    this.getLastValue = function() { return this.polylines[this.polylines.length - 1]; }
    this.getValueById = function(ID)
    {
        var i;
        for (i = 0; i < this.polylinesID.length; i++)
        {
            if (this.polylinesID[i] == ID)
            {
                // alert('polyline found : '+this.polylines[i].value);
                return this.polylines[i];
            }
        }
        return null;
    }
    this.removeValueById = function(ID)
    {
        var i;
        for (i = 0; i < this.polylinesID.length; i++)
        {
            if (this.polylinesID[i] == ID)
            {
                this.polylines.splice(i, 1);
                this.polylinesID.splice(i, 1);
            }
        }
        return null;
    }
}

function fPolygons()
{
    this.polygons = new Array();
    this.polygonsID = new Array();
    this.getLength = function() { return this.polygons.length; };
    this.pushValue = function(v, ID) { this.polygons.push(v); this.polygonsID.push(ID); }
    this.getValue = function(i) { return this.polygons[i]; }
    this.getLastValue = function() { return this.polygons[this.polygons.length - 1]; }
    this.getValueById = function(ID)
    {
        var i;
        for (i = 0; i < this.polygonsID.length; i++)
        {
            if (this.polygonsID[i] == ID)
            {
                return this.polygons[i];
            }
        }
        return null;
    }
    this.removeValueById = function(ID)
    {
        var i;
        for (i = 0; i < this.polygonsID.length; i++)
        {
            if (this.polygonsID[i] == ID)
            {
                this.polygons.splice(i, 1);
                this.polygonsID.splice(i, 1);
            }
        }
        return null;
    }
}


var map;
var trafficInfo = null;
var markers = new fMarkers();
var polylines = new fPolylines();
var polygons = new fPolygons();


function CreateMarker(point, icon1, InfoHTML, infoTabs, bDraggable, sTitle, additionalClickEventFunction)
{
    var marker;
    marker = new GMarker(point, { icon: icon1, draggable: bDraggable, title: sTitle });
    marker.isInfoWindowOpen = false;
    if (InfoHTML != '')
    {
        // Add 3 events to each marker. One for clicking it, one if the info window opens and one for closing the window.
        // Reason is that in the iScope live page, if a user clicks a marker, the info window should get reopend after a refresh...unless he closed the window or selected another one
        GEvent.addListener(marker, "click", function() { marker.openInfoWindowHtml(InfoHTML); marker.isInfoWindowOpen = true; eval(additionalClickEventFunction) });
        GEvent.addListener(marker,"infowindowclose",function() {marker.isInfoWindowOpen = false; });
        GEvent.addListener(marker, "infowindowopen", function() { marker.isInfoWindowOpen = true; });
       
    }
    else if (infoTabs != null && infoTabs.length > 0)
    {
        var gInfoTabs = new Array();
        for (i = 0; i < infoTabs.length; i++)
        { 
            tab = infoTabs[i];
            gInfoTabs.push(new GInfoWindowTab(tab.Title, tab.ContentHtml));
        }

        GEvent.addListener(marker, "click", function() { marker.openInfoWindowTabsHtml(gInfoTabs); marker.isInfoWindowOpen = true; eval(additionalClickEventFunction) });
        GEvent.addListener(marker,"infowindowclose",function() {marker.isInfoWindowOpen = false; });
        GEvent.addListener(marker, "infowindowopen", function() { marker.isInfoWindowOpen = true; });
       
    }
    
    GEvent.addListener(marker, "dragend", function() { GService.SetLatLon(this.value, this.getLatLng().y, this.getLatLng().x); RaiseEvent('PushpinMoved', this.value); });
    
    return marker;
}

//Remove the events to prevent memory increase
function RemoveEventListeners( marker )
{
   GEvent.clearListeners(marker,"click");
   GEvent.clearListeners(marker,"infowindowclose");
   GEvent.clearListeners(marker,"infowindowopen");
   GEvent.clearListeners(marker,"dragend");
}

function OpenInfoWindow(id, selectInList) 
{
    var marker = markers.getValueById(id);
    if (marker != null) 
    {
        //marker.openInfoWindowHtml(InfoHTML);
        // Open the marker's info window by triggering its click event.

        GEvent.trigger(marker, "click");
        if (selectInList != null)
            toggleStation(id, selectInList);
    }
}




function CreatePolyline(points, color, width, isgeodesic)
{
    var polyline;
    if (!isgeodesic)
    {
        polyline = new GPolyline(points, color, width);
    }
    else
    {
        var polyOptions = { geodesic: true };
        polyline = new GPolyline(points, color, width, 1, polyOptions);
    }
    return polyline;
}

function CreatePolygon(points, strokecolor, strokeweight, strokeopacity, fillcolor, fillopacity)
{
    var polygon;

    var polygon = new GPolygon(points, strokecolor, strokeweight, strokeopacity, fillcolor, fillopacity);
    return polygon;
}

function fGetGoogleObject(result, userContext)
{
    map.setCenter(new GLatLng(result.CenterPoint.Latitude, result.CenterPoint.Longitude), result.ZoomLevel);

    if (result.UseUIDefaults)
    {
        // Use the default Google Maps UI as seen on maps.google.com.
        // Adds the following controls:
        // - MapTypeControl
        // - LargeMapControl3D
        // - ScaleControl
        // Also enables the following functionality:
        // - Scrollwheel zooming
        // - Double-click zooming
        // - Keyboard handling
        map.setUIToDefault();

        // Prevent the browser window from scrolling when the mouse wheel is used for zooming.
        google.maps.Event.addDomListener(map.getContainer(), "DOMMouseScroll", WheelEvent);
        map.getContainer().onmousewheel = WheelEvent;
    }
    else
    {
        if (result.ShowMapTypesControl)
        {
            map.addControl(new GMapTypeControl());
        }

        if (result.ShowZoomControl)
        {
            map.addControl(new GLargeMapControl());
        }
    }

    // Enable "soft" zooming.
    map.enableContinuousZoom();

    map.setMapType(eval(result.MapType));

    var i;
    if (markers != null)
    {
        for (i = 0; i < markers.getLength(); i++)
        {
            var cmark = markers.getValue(i);
            if (cmark != null)
            {
                map.removeOverlay(cmark);
            }
        }
    }
    //    if(myEventListeners!=null)
    //    {
    //        for(i=0;i<myEventListeners.getLength();i++)
    //        {
    //            var lisnr = myEventListeners.getValue(i);
    //            if(lisnr!=null)
    //            {
    //                GEvent.removeListener(lisnr);
    //            }
    //        }
    //    }  
    markers = new fMarkers();
    //    myEventListeners = new fListeners();

    for (i = 0; i < result.Points.length; i++)
    {
        var point = result.Points[i];
        var icon = point.Icon;

        var myIcon_google;

        var myPoint = new GLatLng(point.Latitude, point.Longitude);

        myIcon_google = null;
        if (icon.IconUrl != '')
        {
            myIcon_google = new GIcon(G_DEFAULT_ICON);
            markerOptions = { icon: myIcon_google };

            myIcon_google.iconSize = new GSize(icon.IconWidth, icon.IconHeight);
            myIcon_google.image = icon.IconUrl;
            myIcon_google.shadow = icon.ShadowUrl;
            myIcon_google.shadowSize = new GSize(icon.ShadowWidth, icon.ShadowHeight);
            myIcon_google.iconAnchor = new GPoint(icon.AnchorPosX, icon.AnchorPosY);
            myIcon_google.infoWindowAnchor = new GPoint(icon.InfoWindowAnchorPosX, icon.InfoWindowAnchorPosY);
        }

        var marker = CreateMarker(myPoint, myIcon_google, point.InfoHTML, point.InfoTabs, point.Draggable, point.ToolTip, point.AdditionalClickEventFunction);
        marker.value = point.ID;
        markers.pushValue(marker);
        map.addOverlay(markers.getLastValue());
    }
    //Add polylines
    // alert('adding polyline');

    polylines = new fPolylines();
    for (i = 0; i < result.Polylines.length; i++)
    {
        var polypoints = new Array();
        var j;
        for (j = 0; j < result.Polylines[i].Points.length; j++)
        {
            polypoints.push(new GLatLng(result.Polylines[i].Points[j].Latitude, result.Polylines[i].Points[j].Longitude));
        }
        var polyline = CreatePolyline(polypoints, result.Polylines[i].ColorCode, result.Polylines[i].Width, result.Polylines[i].Geodesic);
        polylines.pushValue(polyline, result.Polylines[i].ID);
        map.addOverlay(polylines.getLastValue());
    }
    // var polypoints = new Array();
    // polypoints.push(new GLatLng(43.65669, -79.44268));
    // polypoints.push(new GLatLng(43.66619, -79.44268));
    // var poly = CreatePolyline(polypoints,"#66FF00",10,true);
    // map.addOverlay(poly);

    // var polypoints = new Array();
    // polypoints.push(new GLatLng(43.65669, -79.44268));
    // polypoints.push(new GLatLng(43.66619, -79.44268));
    // polypoints.push(new GLatLng(43.67619, -79.44268));
    // var directions = new GDirections(map,document.getElementById("directions_canvas")); 
    //Clear the mapa nd directions of any old information
    //directions.clear();

    //Load the map and directions from the specified waypoints
    //directions.loadFromWaypoints(polypoints);


    polygons = new fPolygons();
    for (i = 0; i < result.Polygons.length; i++)
    {
        var polypoints = new Array();
        var j;
        for (j = 0; j < result.Polygons[i].Points.length; j++)
        {
            polypoints.push(new GLatLng(result.Polygons[i].Points[j].Latitude, result.Polygons[i].Points[j].Longitude));
        }
        var polygon = CreatePolygon(polypoints, result.Polygons[i].StrokeColor, result.Polygons[i].StrokeWeight, result.Polygons[i].StrokeOpacity, result.Polygons[i].FillColor, result.Polygons[i].FillOpacity);
        polygons.pushValue(polygon, result.Polygons[i].ID);
        map.addOverlay(polygons.getLastValue());
    }


    if (result.ShowTraffic)
    {
        trafficInfo = new GTrafficOverlay();
        map.addOverlay(trafficInfo);
    }
    if (result.AutomaticBoundaryAndZoom)
    {
        RecenterAndZoom(true, result);
    }

}


// Prevent the browser window from scrolling when the mouse wheel is used for zooming.
// Function copied from http://esa.ilmari.googlepages.com/scrollzoom.htm.
function WheelEvent(evt)
{
    if (!evt)
        evt = window.event;

    if (evt.preventDefault)
        evt.preventDefault();

    evt.returnValue = false;
}


function DrawGoogleMap()
{
    if (!google.maps.BrowserIsCompatible())
    {
        alert("Your browser isn't compatible with Google Maps, sorry!");
        return;
    }

    map = new google.maps.Map2(document.getElementById("GoogleMap_Div"));
    geocoder = new GClientGeocoder();
    
    GService.GetGoogleObject(fGetGoogleObject);
}


function fGetGoogleObjectOptimized(result, userContext)
{
    if (result.RecenterMap)
    {
        map.setCenter(new GLatLng(result.CenterPoint.Latitude, result.CenterPoint.Longitude), result.ZoomLevel);
        GService.RecenterMapComplete();
    }

    // Don't set the map type here because once it is initialized, it would be reset on every map refresh.
    //map.setMapType(eval(result.MapType));

    if (result.ShowTraffic)
    {
        trafficInfo = new GTrafficOverlay();
        map.addOverlay(trafficInfo);
    }
    else
    {
        if (trafficInfo != null)
        {
            map.removeOverlay(trafficInfo);
            trafficInfo = null;
        }
    }

    var i;
    for (i = 0; i < result.Points.length; i++)
    {
        //Create icon
        var point = result.Points[i];
        
        var icon = point.Icon;

        var myIcon_google;

        var myPoint = new GLatLng(point.Latitude, point.Longitude);
        
        var reopenInfoWindow = false;
        
        var infoWndTabIdx = 0;
        
        var infoTabs;
        
        var infowindow = map.getInfoWindow();

        myIcon_google = null;
        if (icon.IconUrl != '')
        {
            myIcon_google = new GIcon(G_DEFAULT_ICON);
            markerOptions = { icon: myIcon_google };

            myIcon_google.iconSize = new GSize(icon.IconWidth, icon.IconHeight);
            myIcon_google.image = icon.IconUrl;
            myIcon_google.shadow = icon.ShadowUrl;
            myIcon_google.shadowSize = new GSize(icon.ShadowWidth, icon.ShadowHeight);
            myIcon_google.iconAnchor = new GPoint(icon.AnchorPosX, icon.AnchorPosY);
            myIcon_google.infoWindowAnchor = new GPoint(icon.InfoWindowAnchorPosX, icon.InfoWindowAnchorPosY);
        }

        //Existing marker, but changed.
        if (point.PointStatus == 'C')
        {
            var marker = markers.getValueById(point.ID);
            
            reopenInfoWindow = marker.isInfoWindowOpen;
            if ( reopenInfoWindow)
            {
                infoWndTabIdx = infowindow.getSelectedTab();
                infoTabs = point.InfoTabs;
            }
            if (marker != null)
            {
                markers.removeValueById(point.ID);
                marker.closeInfoWindow();
                RemoveEventListeners(marker);
                map.removeOverlay(marker);
                
                
            }
            var marker = CreateMarker(myPoint, myIcon_google, point.InfoHTML, point.InfoTabs, point.Draggable, point.ToolTip, point.AdditionalClickEventFunction);
            
            marker.value = point.ID;
            markers.pushValue(marker);
            map.addOverlay(markers.getLastValue());
            if (reopenInfoWindow)
            {
              marker.isInfoWindowOpen = true;
              var tabs = [new GInfoWindowTab(infoTabs[0].Title,infoTabs[0].ContentHtml),new GInfoWindowTab(infoTabs[1].Title,infoTabs[1].ContentHtml)];
              //marker.openInfoWindow(myPoint,tabs);
              marker.openInfoWindowTabs(tabs,{selectedTab:infoWndTabIdx });


            }
            else
              marker.isInfoWindowOpen = false;
            
        }
        //New Marker
        if (point.PointStatus == 'N')
        {
            var marker = CreateMarker(myPoint, myIcon_google, point.InfoHTML, point.InfoTabs, point.Draggable, point.ToolTip, point.AdditionalClickEventFunction);
            marker.value = point.ID;
            markers.pushValue(marker);
            map.addOverlay(markers.getLastValue());
        }
        //Existing marker, but deleted.
        if (point.PointStatus == 'D')
        {
            var marker = markers.getValueById(point.ID);
            if (marker != null)
            {
                markers.removeValueById(point.ID);
                map.removeOverlay(marker);
            }
        }
    }

    //Get Polylines
    for (i = 0; i < result.Polylines.length; i++)
    {
        //Existing marker, but changed.

        if (result.Polylines[i].LineStatus == 'C')
        {

            var polyline = polylines.getValueById(result.Polylines[i].ID);
            if (polyline != null)
            {
                polylines.removeValueById(result.Polylines[i].ID);
                map.removeOverlay(polyline);
            }
            var polypoints = new Array();
            var j;
            for (j = 0; j < result.Polylines[i].Points.length; j++)
            {
                polypoints.push(new GLatLng(result.Polylines[i].Points[j].Latitude, result.Polylines[i].Points[j].Longitude));
            }
            var polyline = CreatePolyline(polypoints, result.Polylines[i].ColorCode, result.Polylines[i].Width, result.Polylines[i].Geodesic);
            polylines.pushValue(polyline, result.Polylines[i].ID);
            map.addOverlay(polylines.getLastValue());
        }
        //New Marker

        if (result.Polylines[i].LineStatus == 'N')
        {
            var polypoints = new Array();
            var j;
            for (j = 0; j < result.Polylines[i].Points.length; j++)
            {
                polypoints.push(new GLatLng(result.Polylines[i].Points[j].Latitude, result.Polylines[i].Points[j].Longitude));
            }
            var polyline = CreatePolyline(polypoints, result.Polylines[i].ColorCode, result.Polylines[i].Width, result.Polylines[i].Geodesic);
            polylines.pushValue(polyline, result.Polylines[i].ID);
            map.addOverlay(polylines.getLastValue());
        }
        //Existing marker, but deleted.
        if (result.Polylines[i].LineStatus == 'D')
        {
            var polyline = polylines.getValueById(result.Polylines[i].ID);
            if (polyline != null)
            {
                polylines.removeValueById(result.Polylines[i].ID);
                map.removeOverlay(polyline);
            }
        }
    }

    //Get Polygons
    for (i = 0; i < result.Polygons.length; i++)
    {
        //Existing marker, but changed.

        if (result.Polygons[i].Status == 'C')
        {

            var polygon = polygons.getValueById(result.Polygons[i].ID);
            if (polygon != null)
            {
                polygons.removeValueById(result.Polygons[i].ID);
                map.removeOverlay(polygon);
            }
            var polypoints = new Array();
            var j;
            for (j = 0; j < result.Polygons[i].Points.length; j++)
            {
                polypoints.push(new GLatLng(result.Polygons[i].Points[j].Latitude, result.Polygons[i].Points[j].Longitude));
            }
            var polygon = CreatePolygon(polypoints, result.Polygons[i].StrokeColor, result.Polygons[i].StrokeWeight, result.Polygons[i].StrokeOpacity, result.Polygons[i].FillColor, result.Polygons[i].FillOpacity);
            polygons.pushValue(polygon, result.Polygons[i].ID);
            map.addOverlay(polygons.getLastValue());
        }
        //New Marker

        if (result.Polygons[i].Status == 'N')
        {
            var polypoints = new Array();
            var j;
            for (j = 0; j < result.Polygons[i].Points.length; j++)
            {
                polypoints.push(new GLatLng(result.Polygons[i].Points[j].Latitude, result.Polygons[i].Points[j].Longitude));
            }
            var polygon = CreatePolygon(polypoints, result.Polygons[i].StrokeColor, result.Polygons[i].StrokeWeight, result.Polygons[i].StrokeOpacity, result.Polygons[i].FillColor, result.Polygons[i].FillOpacity);
            polygons.pushValue(polygon, result.Polygons[i].ID);
            map.addOverlay(polygons.getLastValue());
        }
        //Existing marker, but deleted.
        if (result.Polygons[i].Status == 'D')
        {
            var polygon = polygons.getValueById(result.Polygons[i].ID);
            if (polygon != null)
            {
                polygons.removeValueById(result.Polygons[i].ID);
                map.removeOverlay(polygon);
            }
        }
    }
    if (result.AutomaticBoundaryAndZoom)
    {
        RecenterAndZoom(true, result);
    }
}


//This function causes Recentering of map. It finds all visible markers on map and decides center point and zoom level based on these markers.
function RecenterAndZoom(bRecenter, result)
{
    if (bRecenter)
    {
        //Check if there is any visible pushpin on map.
        var cnt = 0;
        bounds = new GLatLngBounds();
        var objIgnore = document.getElementById('chkIgnoreZero');
        var bIgnore = false;
        if (objIgnore != null)
        {
            bIgnore = objIgnore.checked;
        }
        bIgnore = result.IgnoreZeroLatLngs;
        for (var i = 0; i < markers.getLength(); i++)
        {
            var ignoremarker = false;
            if (bIgnore)
            {
                var point1 = markers.markers[i].getPoint();
                if ((point1.x == 0) && (point1.y == 0))
                {
                    ignoremarker = true;
                }
            }
            if (!ignoremarker)
            {
                if (!markers.markers[i].isHidden())
                {
                    bounds.extend(markers.markers[i].getPoint());
                    //Increment visible pushpin count
                    cnt++;
                }
            }

        }
        var iZoomLevel = map.getBoundsZoomLevel(bounds);
        var point = bounds.getCenter();

        if (cnt <= 0)
        {
            point = new GLatLng(result.CenterPoint.Latitude, result.CenterPoint.Longitude);
            iZoomLevel = result.ZoomLevel;
        }
        map.setZoom(iZoomLevel);
        map.setCenter(point);

        // Check if the current zoom level can still be displayed without error tiles
        // (see comment below). Done with a small delay because loading of map tiles is done
        // in another thread.
        // Note that the mapType.getMaximumResolution() function doesn't help in this case.
        window.setTimeout("CheckMaxZoomLevel()", 1500);
    }
}


// Checks the number of <p> elements in the map, revealing how many "Sorry, we don't have images
// at this zoom level" messages you get. If these exceed a certain threshold, the map is
// zoomed out.
function CheckMaxZoomLevel()
{
    // Copied from http://esa.ilmari.googlepages.com/sorry.htm.
    paragraphs = map.getContainer().getElementsByTagName('p').length;
    if (paragraphs > 4)
    {
        map.zoomOut(false, true);
        // Call the same function again, as zooming out just one level is possibly not sufficient.
        // We have to delay the call as the error message only appears after the tiles have
        // (not) been loaded in a different thread.
        window.setTimeout("CheckMaxZoomLevel()", 1000);
    }
    else
        map.savePosition();
}


function endRequestHandler(sender, args)
{
    GService.GetOptimizedGoogleObject(fGetGoogleObjectOptimized);
}

function pageLoad()
{
    if (!Sys.WebForms.PageRequestManager.getInstance().get_isInAsyncPostBack())
        Sys.WebForms.PageRequestManager.getInstance().add_endRequest(endRequestHandler);
}