﻿// 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');
    var objMap = document.getElementById('GoogleMap_Div');
    var objDiv = document.getElementById('GoogleMap_Div_Container');
    if(objButton.value=='Full Screen')
    {
        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();
    }
}

var map;
var geocoder = null;
var trafficInfo = null;
var currentIcon;

//function fListeners()
//{
//    this.listeners = new Array();
//    this.getLength = function() { return this.listeners.length; };
//    this.pushValue = function(v) { this.listeners.push(v); }
//    this.getValue = function(i)  { return this.listeners[i]; }
//}
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; 
                                      }
}

if (GBrowserIsCompatible())
{
map = new GMap2(document.getElementById("GoogleMap_Div"));
geocoder = new GClientGeocoder();
map.setUIToDefault();

var markers = new fMarkers();
var polylines = new fPolylines();
var polygons = new fPolygons();
//var myEventListeners = new fListeners();

function CreateMarker(point, icon1, InfoHTML, bDraggable, sTitle, markerType)
{
    var index = 0;
    
    if (markerType == "StartTrip")
    {
        index = 1001;
    }
    else if (markerType == "EndTrip")
    {
        index = 1000;
    }
        
    function GetZIndex(marker, markerType)
    {
        return index;
//        return GOverlay.getZIndex(marker.getPoint().lat())+index*10000;
    }
    
    var marker = new GMarker(point,{icon:icon1,draggable:bDraggable,title: sTitle, zIndexProcess: GetZIndex});
    if(InfoHTML!='')
    {
        GEvent.addListener(marker, "click",
            function()
            {
                this.openInfoWindowHtml(InfoHTML);
            }
        );
    }
    
    GEvent.addListener(marker, "dragend",
        function()
        {
            GService.SetLatLon(this.value,this.getLatLng().y,this.getLatLng().x);RaiseEvent('PushpinMoved',this.value);
        }
    );
    
    if (markerType == "Regular")
    {
        GEvent.addListener(marker,'mouseover',
            function()
            {
                currentIcon = marker.getIcon();
                var iconOptions = {};
                iconOptions.width = 32;
                iconOptions.height = 32;
                iconOptions.primaryColor = "#00FF00FF";
                iconOptions.cornerColor = "#00FF00FF";
                iconOptions.strokeColor = "#000000FF";
                var myIcon_google = MapIconMaker.createMarkerIcon(iconOptions);
                marker.setImage(myIcon_google.image);
                //document.getElementById("sidebar").getElementsByTagName("span")[i].style.background ="yellow";
            }
        );
        
        GEvent.addListener(marker,'mouseout',
            function()
            {
                var myIcon_google = new GIcon(currentIcon);
                marker.setImage(myIcon_google.image);
                //if(marker[i].visited){
                //marker[i].setImage(markerImage[4]);
                //document.getElementById("sidebar").getElementsByTagName("span")[i].style.color ="gray";

                //}else{
                //marker[i].setImage(markerImage[0]);
                //document.getElementById("sidebar").getElementsByTagName("span")[i].style.color ="black";
                //}    
                //document.getElementById("sidebar").getElementsByTagName("span")[i].style.background ="white";
            }
        );
    }
    return marker;
}

function OpenInfoWindow(id,InfoHTML)
{
    var marker = markers.getValueById(id);
    if(marker!=null)
    {
        marker.openInfoWindowHtml(InfoHTML);
    }
}

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)
{
    return new GPolygon(points,strokecolor,strokeweight,strokeopacity,fillcolor,fillopacity);
}

function fGetGoogleObject(result, userContext)
{
    map.setCenter(new GLatLng(result.CenterPoint.Latitude, result.CenterPoint.Longitude), result.ZoomLevel);
    
    if(result.ShowMapTypesControl)
    {
        map.addControl(new GMapTypeControl());
    }

    if(result.ShowZoomControl)
    {
        map.addControl(new GLargeMapControl());
    }
    
    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();

    var startLabel;
    var endLabel;
    if (result.Language == "en") {
        startLabel = "S";
        endLabel = "E";
    }
    else if (result.Language == "fr") {
        startLabel = "D";
        endLabel = "A";
    }

    for (i=0; i<result.Points.length; i++)
    {   
        var myPoint = new GLatLng(result.Points[i].Latitude, result.Points[i].Longitude);
        var myIcon_google = null;
        var iconOptions = {};
        if (result.Points[i].MarkerType == "Regular")
        {
            iconOptions.width = 32;
            iconOptions.height = 32;
            iconOptions.primaryColor = result.Points[i].PrimaryColor + "FF";
            iconOptions.cornerColor = result.Points[i].CornerColor + "FF";
            myIcon_google = MapIconMaker.createMarkerIcon(iconOptions);
        }
        else if (result.Points[i].MarkerType == "StartTrip")
        {
            iconOptions.primaryColor = result.Points[i].PrimaryColor;
            iconOptions.label = startLabel;
            iconOptions.labelColor = "#FFFFFF";
            iconOptions.addStar = false;
            myIcon_google = MapIconMaker.createLabeledMarkerIcon(iconOptions);
        }
        else if (result.Points[i].MarkerType == "EndTrip")
        {
            iconOptions.primaryColor = result.Points[i].PrimaryColor;
            iconOptions.label = endLabel;
            iconOptions.labelColor = "#FFFFFF";
            iconOptions.addStar = false;
            myIcon_google = MapIconMaker.createLabeledMarkerIcon(iconOptions);
        }
//        var myIcon_google = MapIconMaker.createLabeledMarkerIcon(iconOptions);
        //var myIcon_google = MapIconMaker.createMarkerIcon({width: 32, height: 32, primaryColor: "#00ff00"}); 

        // NOTE: To Display a label use the following code.
//        var iconOptions = {};
//        iconOptions.width = 30;
//        iconOptions.height = 16;
//        iconOptions.primaryColor = "#00FF00";
//        iconOptions.label = "1000";
//        iconOptions.labelSize = 0;
//        iconOptions.labelColor = "#000000";
//        iconOptions.shape = "roundrect";
//        myIcon_google = MapIconMaker.createFlatIcon(iconOptions);

        if(result.Points[i].IconImage!='')
        {
            //myIcon_google = new GIcon(G_DEFAULT_ICON);
            markerOptions = { icon:myIcon_google };
            
            myIcon_google.iconSize = new GSize(result.Points[i].IconImageWidth,result.Points[i].IconImageHeight);
            myIcon_google.image = result.Points[i].IconImage;
            myIcon_google.shadow = result.Points[i].IconShadowImage;
            myIcon_google.shadowSize = new GSize(result.Points[i].IconShadowWidth, result.Points[i].IconShadowHeight);
            myIcon_google.iconAnchor =  new GPoint(result.Points[i].IconAnchor_posX, result.Points[i].IconAnchor_posY);
            myIcon_google.infoWindowAnchor = new GPoint(result.Points[i].InfoWindowAnchor_posX, result.Points[i].InfoWindowAnchor_posY);
        }
       
        var marker = CreateMarker(myPoint,myIcon_google,result.Points[i].InfoHTML,result.Points[i].Draggable,result.Points[i].ToolTip, result.Points[i].MarkerType);
        marker.value = result.Points[i].ID;
        markers.pushValue(marker);
        map.addOverlay(markers.getLastValue());
    }
    //Add polylines

    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());
    }

    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);
    }
    
    InitGeofence();
}

function DrawGoogleMap()
{
    if (GBrowserIsCompatible())
    {
        map = new GMap2(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();
    }
    
    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;
    var startLabel;
    var endLabel;
    if (result.Language == "en") {
        startLabel = "S";
        endLabel = "E";
    }
    else if (result.Language == "fr") {
        startLabel = "D";
        endLabel = "A";
    }

    for(i=0;i<result.Points.length;i++)
    {
        //Create icon
        var myPoint = new GLatLng(result.Points[i].Latitude, result.Points[i].Longitude);
                 
        var myIcon_google = null;
        var iconOptions = {};
        if (result.Points[i].MarkerType == "Regular")
        {
            iconOptions.width = 32;
            iconOptions.height = 32;
            iconOptions.primaryColor = result.Points[i].PrimaryColor + "FF";
            iconOptions.cornerColor = result.Points[i].CornerColor + "FF";
            myIcon_google = MapIconMaker.createMarkerIcon(iconOptions);
        }
        else if (result.Points[i].MarkerType == "StartTrip")
        {
            iconOptions.primaryColor = result.Points[i].PrimaryColor;
            iconOptions.label = startLabel;
            iconOptions.labelColor = "#FFFFFF";
            iconOptions.addStar = false;
            myIcon_google = MapIconMaker.createLabeledMarkerIcon(iconOptions);
        }
        else if (result.Points[i].MarkerType == "EndTrip")
        {
            iconOptions.primaryColor = result.Points[i].PrimaryColor;
            iconOptions.label = endLabel;
            iconOptions.labelColor = "#FFFFFF";
            iconOptions.addStar = false;
            myIcon_google = MapIconMaker.createLabeledMarkerIcon(iconOptions);
        }
//        iconOptions.width = 32;
//        iconOptions.height = 32;
//        iconOptions.primaryColor = result.Points[i].PrimaryColor;
//        iconOptions.cornerColor = result.Points[i].CornerColor;
//        iconOptions.strokeColor = "#000000FF";
//        var myIcon_google = MapIconMaker.createMarkerIcon(iconOptions);
//        
        // NOTE: To Display a label use the following code.
//        var iconOptions = {};
//        iconOptions.width = 100;
//        iconOptions.height = 32;
//        iconOptions.primaryColor = "#FFFF00";
//        iconOptions.label = "agssdgdg";
//        iconOptions.labelSize = 0;
//        iconOptions.labelColor = "#000000";
//        iconOptions.shape = "roundrect";
//        myIcon_google = MapIconMaker.createFlatIcon(iconOptions);

        if(result.Points[i].IconImage!='')
        {
            //myIcon_google = new GIcon(G_DEFAULT_ICON);
            markerOptions = { icon:myIcon_google };

            myIcon_google.iconSize = new GSize(result.Points[i].IconImageWidth,result.Points[i].IconImageHeight);
            myIcon_google.image = result.Points[i].IconImage;
            myIcon_google.shadow = result.Points[i].IconShadowImage;
            myIcon_google.shadowSize = new GSize(result.Points[i].IconShadowWidth, result.Points[i].IconShadowHeight);
            myIcon_google.iconAnchor =  new GPoint(result.Points[i].IconAnchor_posX, result.Points[i].IconAnchor_posY);
            myIcon_google.infoWindowAnchor = new GPoint(result.Points[i].InfoWindowAnchor_posX, result.Points[i].InfoWindowAnchor_posY);

        }
        //Existing marker, but changed.
        if(result.Points[i].PointStatus=='C')
        {
            var marker = markers.getValueById(result.Points[i].ID);
            if(marker!=null)
            {
                markers.removeValueById(result.Points[i].ID);
                map.removeOverlay(marker);
            }
            var marker = CreateMarker(myPoint,myIcon_google,result.Points[i].InfoHTML,result.Points[i].Draggable,result.Points[i].ToolTip, result.Points[i].MarkerType);
            marker.value = result.Points[i].ID;
            markers.pushValue(marker);
            map.addOverlay(markers.getLastValue());
        }
        //New Marker
        if(result.Points[i].PointStatus=='N')
        {
            var marker = CreateMarker(myPoint,myIcon_google,result.Points[i].InfoHTML,result.Points[i].Draggable,result.Points[i].ToolTip, result.Points[i].MarkerType);
            marker.value = result.Points[i].ID;
            markers.pushValue(marker);
            map.addOverlay(markers.getLastValue());
        }
        //Existing marker, but deleted.
        if(result.Points[i].PointStatus=='D')
        {
            var marker = markers.getValueById(result.Points[i].ID);
            if(marker!=null)
            {
                markers.removeValueById(result.Points[i].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(result.RecenterMapAndZoom, result);
    }
    
    InitGeofence();
}
}

//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(iZoomLevel>14)
        {
            iZoomLevel = 14;
        }
        
        if(cnt<=0)
        {
            point = new GLatLng(result.CenterPoint.Latitude,result.CenterPoint.Longitude);
            iZoomLevel = result.ZoomLevel;
        }

        map.setZoom(iZoomLevel);
        map.setCenter(point);
    }
}

function endRequestHandler(sender, args)
{
    GService.GetOptimizedGoogleObject(fGetGoogleObjectOptimized);
}

function pageLoad()
{
    if(!Sys.WebForms.PageRequestManager.getInstance().get_isInAsyncPostBack())
        Sys.WebForms.PageRequestManager.getInstance().add_endRequest(endRequestHandler);
}

function BringAllToFront()
{
    GService.GetOptimizedGoogleObject(BringAllPinsToFront);
}


function BringAllPinsToFront(result, userContext)
{
    RecenterAndZoom(true, result)
}

var opacity = 0.4;
var circle;
var centerMarker;
var circleRadius;
var zoom = 2;
var centerPoint = new GLatLng(40,-100);
var dragged = false;

function drawCircle()
{
    var center = map.getCenter();
    {
        GService.GetGeofenceCenter(OnGetGeofenceCenterComplete, OnError, OnTimeOut);
    }
    // It's the return false that prevents the postback, if you return true the postback will occur
	return true;
}

function OnComplete(result, arg)
{
    circleRadius = result;
    DrawGeofenceCircle();
    //doDrawCircle();
}

function OnGetGeofenceCenterComplete(result, arg)
{
    if (result != null)
    {
        if (!dragged)
        {
            map.setCenter(new GLatLng(result.Latitude, result.Longitude), result.ZoomLevel);
        }
        dragged = false;
        GService.GetGeofenceRadius(OnComplete, OnError, OnTimeOut);
    }
}

function OnTimeOut(arg)
{
    alert("timeOut has occured");
}
function OnError(arg)
{
    alert("error has occured: " + arg._message);
}

var geofenceBounds = null;

function doDrawCircle()
{
	if (circle)
	{
		map.removeOverlay(circle);
	}

	if (centerMarker)
	{
	    map.removeOverlay(centerMarker);
	}

	centerMarker = new GMarker(map.getCenter(), { draggable: true });
		GEvent.addListener(centerMarker,'dragend',
            function(overlay, point)
            {
                if (centerMarker)
                {
                    map.panTo(centerMarker.getLatLng());
                    map.setCenter(centerMarker.getLatLng());
                    dragged = true;
                    drawCircle();
                }
            }
		);
		map.addOverlay(centerMarker);

	var center = map.getCenter();

	geofenceBounds = new GLatLngBounds();
	var circlePoints = Array();

    ChangeCoords(center.lat(), center.lng());
    
	with (Math)
	{
        var d = circleRadius;
		var lat1 = (PI/180)* center.lat(); // radians
		var lng1 = (PI/180)* center.lng(); // radians

		for (var a = 0 ; a < 361 ; a++ )
		{
			var tc = (PI/180)*a;
			var y = asin(sin(lat1)*cos(d)+cos(lat1)*sin(d)*cos(tc));
			var dlng = atan2(sin(tc)*sin(d)*cos(lat1),cos(d)-sin(lat1)*sin(y));
			var x = ((lng1-dlng+PI) % (2*PI)) - PI ; // MOD function
			var point = new GLatLng(parseFloat(y*(180/PI)),parseFloat(x*(180/PI)));
			circlePoints.push(point);
			geofenceBounds.extend(point);
		}

		if (d < 1.5678565720686044) {
			circle = new GPolygon(circlePoints, '#000000', 2, 1, '#000000', 0.25);	
		}
		else
		{
		    circle = new GPolygon(circlePoints, '#000000', 2, 1);	
		}

        map.addOverlay(circle);
        //map.setZoom(map.getBoundsZoomLevel(geofenceBounds));
    }
}

function ShowGeofenceBounds() {
    if (geofenceBounds != null) {
        map.setZoom(map.getBoundsZoomLevel(geofenceBounds));
    }
}

function DrawGeofenceCircle() {
    doDrawCircle();
    ShowGeofenceBounds();
}
