﻿var cacheKey;
var map;
var trafficInfo = null;

// Builds the marker array
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) {
                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) {
                this.markers.splice(i, 1);
            }
        }
        return null;
    }
}

//If browser is compatible for google maps, draw the map.
if (GBrowserIsCompatible())
{
    var m = document.getElementById("GoogleMap_Div");   

    map = new GMap2(m);

    //Creates and returns google compatible icons
    function CreateIcons(point) {
    
        var gIcon = new GIcon(G_DEFAULT_ICON);
        gIcon.iconSize = new GSize(point.IconImageWidth, point.IconImageHeight);
        gIcon.image = point.IconImage;
        gIcon.shadow = point.IconShadowImage;
        gIcon.shadowSize = new GSize(point.IconShadowWidth, point.IconShadowHeight);
        gIcon.iconAnchor = new GPoint(point.IconAnchor_posX, point.IconAnchor_posY);
        gIcon.infoWindowAnchor = new GPoint(point.InfoWindowAnchor_posX, point.InfoWindowAnchor_posY);
        return gIcon;
    }
    
    var markers = new fMarkers();
    
    //Creates markers to display on the map.
    function CreateMarker(point, icon1, InfoHTML, bDraggable, sTitle, cacheKey) {
        var marker;        
        marker = new GMarker(point, { icon: icon1, draggable: bDraggable, title: sTitle });
        
            //Add event for clicking on the marker and  and display the summary window
        if (InfoHTML != '') {
            GEvent.addListener(marker, "click", function() {
                //                var locChosen = marker.value;
                //                var locResult = "#ServiceID_" + locChosen;
                //                $(locChosen).scrollTo($(locResult), 800);
                //                $(locResult).effect("highlight", {}, 3500);
                //                $(locResult + " input").attr("checked", "checked");
               
                this.openInfoWindowHtml(InfoHTML);

                GoogleMapPinClicked('PushpinClicked', marker.value);

            });

//            GEvent.addListener(marker, "click keyup", function() {
//                this.openInfoWindowHtml(InfoHTML);
//            });
//            
//            $("#local-results-map img").bind("click keyup", function(e) {
//                $("#TaiTest").effect("highlight", {}, 3500);
//                //var locChosen = $(this).attr("id");
//                //var locResult = "#location_" + locChosen.substring(10);
//                //$(locResult).effect("highlight", {}, 3500);
//                //$(locResult + " input").attr("checked", "checked");
//       
//            });
            } 
        
        return marker;
    }

    // Open info info window for the marker
    function OpenInfoWindow(id, InfoHTML) {
        var marker = markers.getValueById(id);
        if (marker != null) {
            marker.openInfoWindowHtml(InfoHTML);            
        }
    }

    // Success Callback function for GetGoogleObject method of mapping service.
    // Used if Map object is found    
    function fGetGoogleObject(result, userContext) {
        var cpoint = new GLatLng(result.CenterPoint.Latitude, result.CenterPoint.Longitude);
        // Sets a default center point for the map
        map.setCenter(cpoint, result.ZoomLevel);
        //If the center point has an icon, Display it.
        var centermarker;

        
            if (result.CenterPoint.IconImage != '') {

                
                var centerIcon = CreateIcons(result.CenterPoint);
                markerOptions = { icon: centerIcon };

                centermarker = CreateMarker(cpoint, centerIcon, result.CenterPoint.InfoHTML, result.CenterPoint.Draggable, result.CenterPoint.ToolTip, cacheKey);
                centermarker.value = result.CenterPoint.ID;
                map.addOverlay(centermarker);
            
        }
        // Shows the following Buttons on the top right corner of the map.
        // Map
        // Satellite -> show lables
        // Terrain        
        if (result.ShowMapTypesControl) {
            map.addControl(new GHierarchicalMapTypeControl());
        }

        // Shows the zoom controle on the top left of the map.
        if (result.ShowZoomControl) {
            map.addControl(new GLargeMapControl3D());
        }

        // Type of map to display
        // G_NORMAL_MAP | G_SATELLITE_MAP | G_HYBRID_MAP | G_PHYSICAL_MAP
        map.addMapType(eval(result.MapType));
        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);
                }
            }
        }

        markers = new fMarkers();
        markers.pushValue(centermarker);
        //If the map has more points and icons to display other than the center point
        if (result.Points != null && result.Points.length > 0) {
            var myIcon_google;
            for (i = 0; i < result.Points.length; i++) {
                if (!result.Points[i].HidePoint) {
                    var myPoint = new GLatLng(result.Points[i].Latitude, result.Points[i].Longitude);
                    myIcon_google = null;
                    if (result.Points[i].IconImage != '') {
                        myIcon_google = CreateIcons(result.Points[i]);
                        markerOptions = { icon: myIcon_google };
                    }
                    var marker = CreateMarker(myPoint, myIcon_google, result.Points[i].InfoHTML, result.Points[i].Draggable, result.Points[i].ToolTip, cacheKey);
                    marker.value = result.Points[i].ID;
                    markers.pushValue(marker);
                    map.addOverlay(markers.getLastValue());
                }
            }
        }
        
        if (result.AutomaticBoundaryAndZoom) {
        RecenterAndZoom(true, result);
        }

    }

    // Called in the c# code to begin Draw
    function DrawGoogleMap(key) {
        if (GBrowserIsCompatible()) {
            map = new GMap2(document.getElementById("GoogleMap_Div"));
            geocoder = new GClientGeocoder();
            cacheKey = key;
            //Get the google Map object from the service.
            corporate.cpwj.mapping.imappingservice.GetGoogleObject(cacheKey, fGetGoogleObject, fGetGoogleObjectFailed, 'GetGoogleObject');
        }
    }

    // Fail Callback function for GetGoogleObject method of mapping service.
    // Used if Map object is not found or an exception occures 
    function fGetGoogleObjectFailed(exception, userContext, methodName) {
        alert("The Google service is not available at this time. Please try again later");
    }    
}

//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)-1;
        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) {
    corporate.cpwj.mapping.imappingservice.GetGoogleObject(cacheKey, fGetGoogleObject, fGetGoogleObjectFailed, 'GetGoogleObject');
}

function pageLoad() {
    if (!Sys.WebForms.PageRequestManager.getInstance().get_isInAsyncPostBack()) {
        Sys.WebForms.PageRequestManager.getInstance().add_endRequest(endRequestHandler);
    }   
}