﻿// VE Map VEMap.js #######################################################################
var map = null;
var le = 0;
var trackPinsLayer;
var trackPointsLayer;
var picLayer;
var poiLayer;


// ###############################################################################
// MAP FUNCTIONS
//      VEGetMap();
//      VEGetMapDelayed();
//      ReinitMap();
//      ClearAndReinit();
//      GetMapChangeSettings();
//      SaveCurrentView();
// ###############################################################################

function VEGetMap() {    
    
    if(oldFunction){ oldFunction(); }

    var head = document.getElementsByTagName("head")[0];
    var s = document.createElement('script');
    var localisationName = "en-US"
    if (typeof (Sys) != 'undefined') {
        if (Sys.CultureInfo.CurrentCulture.name.indexOf('de') > -1) localisationName = "de-DE";
    }
    s.id = 'VEScript';
    s.type = 'text/javascript';
    s.src = "http://dev.virtualearth.net/mapcontrol/mapcontrol.ashx?v=6.2&mkt=" + localisationName;
    head.appendChild(s);
    VEGetMapDelayed();
}
function VEGetMapDelayed() {
    try {
        // If map is enlarged, set these layers to null...
        // VEGetMapDelayed is also used as a "Reset" function
        CommentLayer = null;
        VEMapWikiLayer = null;
        VEMapWeatherLayer = null;
        VEMapMountainnamesLayer = null;

        ResizeMap();

        map = new VEMap(MapControlViewMapID);

        // Set the right MapStyle
        mapStyle = VEMapStyle.Road;
        switch (cMapType) {
            case 1:
                mapStyle = VEMapStyle.Hybrid;
                break;
            case 2:
                mapStyle = VEMapStyle.Aerial;
                break;
            case 3:
                mapStyle = VEMapStyle.BirdseyeHybrid;
                break;
            case 4:
                mapStyle = VEMapStyle.Birdseye;
                break;
        }
        // Load the map
        map.LoadMap(new VELatLong(MapCenterLocation.Lat, MapCenterLocation.Lon), MapZoomLevel, mapStyle);
        map.SetShapesAccuracy(VEShapeAccuracy.Pushpin);

        // Set the Measurement unit of the map
        if (MapMeasurementUnit == "Imperial")
            map.SetScaleBarDistanceUnit(VEDistanceUnit.Miles);
        else
            map.SetScaleBarDistanceUnit(VEDistanceUnit.Kilometers);
        
        // Activates the custom map menu
        ActivateCustomMapMenu("VEMap");
        
        // Activates the message box
        MapControlInitMessageBox("VEMap");
        
        map.AttachEvent("oninitmode", ClearAndReinit);

        document.getElementById(MapControlViewMapID).style.background = "";

        // Init the layers
        trackPinsLayer = new VEShapeLayer();
        trackPointsLayer = new VEShapeLayer();
        picLayer = new VEShapeLayer();
        poiLayer = new VEShapeLayer();
        map.AddShapeLayer(trackPointsLayer);
        map.AddShapeLayer(trackPinsLayer);
        map.AddShapeLayer(picLayer);
        map.AddShapeLayer(poiLayer);
        
        // Draw the data (common function)
        setTimeout("MapDrawData()", 500);
    }
    catch (error) {
        if (le < 30) {
            le++;
            setTimeout("VEGetMapDelayed()", 500);
        } else {
            alert('Server busy. Please wait a few seconds...');
        }
    }
}

function ReInitMap() {
    MapCenterLocation.Lat = map.GetCenter().Latitude;
    MapCenterLocation.Lon = map.GetCenter().Longitude;
    MapZoomLevel = map.GetZoomLevel();
    map.Resize();
}

function ClearAndReinit() {
    map.DeleteAllShapeLayers();
    MapDrawData();
}

// Get all informations of the map, which are important for the change to another MapType
function GetMapChangeSettings() {
    infos = new Object();
    // Map.GetCenter does not work for these two mapstyles!!!
    if (map.GetMapStyle() == VEMapStyle.Birdseye || map.GetMapStyle() == VEMapStyle.BirdseyeHybrid) {
        cZoom = MapZoomLevel;
        loc = new VELatLong(MapCenterLocation.Lat, MapCenterLocation.Lon);
    }
    else {
        cZoom = map.GetZoomLevel();
        loc = map.GetCenter();
    }
    // Localize
    if (Sys.CultureInfo.CurrentCulture.name.indexOf('de') == 0) {
        infos.CenterLat = loc.Latitude.toString().replace('.', ',');
        infos.CenterLon = loc.Longitude.toString().replace('.', ',');
    } else {
        infos.CenterLat = loc.Latitude.toString();
        infos.CenterLon = loc.Longitude.toString();
    }
    infos.ZoomLevel = cZoom;
    infos.MapType = "VEMap";
    if (map.GetMapStyle() == VEMapStyle.Aerial || map.GetMapStyle() == VEMapStyle.Hybrid || map.GetMapStyle() == VEMapStyle.Oblique || map.GetMapStyle() == VEMapStyle.Birdseye || map.GetMapStyle() == VEMapStyle.BirdseyeHybrid)
        infos.MapView = "Aerial";
    else
        infos.MapView = "Road";

    return infos;
}
function SaveCurrentView() {

    cMapTypeString = "BingMap_Road";
    switch (map.GetMapStyle()) {
        case VEMapStyle.Road:
            //alert("Road");
            cMapTypeString = "BingMap_Road";
            break;
        case VEMapStyle.Hybrid:
            //alert("Aerial");
            cMapTypeString = "BingMap_AerialWithLabels";
            break;
        case VEMapStyle.Aerial:
            cMapTypeString = "BingMap_AerialWithoutLabels";
            break;
        case VEMapStyle.BirdseyeHybrid:
            //alert("BirdWithLabels");
            cMapTypeString = "BingMap_BirdsEyeWithLabels";
            break;
        case VEMapStyle.Birdseye:
            //alert("BirdWithoutLabels");
            cMapTypeString = "BingMap_BirdsEyeWithoutLabels";
            break;
    }

    url = "/Controls/MapControlViewAsyncWorker.aspx";
    if (jsonMapDataRoutes != null) {
        routeID = jsonMapDataRoutes[0].ID;
        paramString = "Method=SaveCurrentViewRoute&RouteID=" + routeID + "&CurrentMapType=" + cMapTypeString;
    }
    if (jsonMapDataPOIs != null) {
        poiID = jsonMapDataPOIs[0].ID;
        paramString = "Method=SaveCurrentViewPOI&POIID=" + poiID + "&CurrentMapType=" + cMapTypeString;
    }
    SendAjaxRequest("GET", url, paramString, "OnSaveCurrentViewSuccess", "OnSaveCurrentViewFail");
}
function OnSaveCurrentViewSuccess(obj) {
    if (obj.Status == "FAIL")
        MapControlShowMessageBox(true, Resources_MapControlView.CustomMenuSaveMapTypeFailMessage, 3000);
    else
        MapControlShowMessageBox(true, Resources_MapControlView.CustomMenuSaveMapTypeSuccessMessage, 3000);
}
function OnSaveCurrentViewFail(obj) {
    MapControlShowMessageBox(true, Resources_MapControlView.CustomMenuSaveMapTypeFailMessage, 3000);
}

function AdjustMapBounds(NWPoint, SEPoint) {
    boundArray = new Array();
    boundArray.push(new VELatLong(NWPoint.Lat, NWPoint.Lon));
    boundArray.push(new VELatLong(SEPoint.Lat, SEPoint.Lon));
    map.SetMapView(boundArray);
}


// ###############################################################################
// DRAW DATA TO THE MAP
// ###############################################################################
function CWMapDrawPin(pinType, lat, lon, desc, poiTypeID) {
    switch (pinType) {
        case "startend":
        case "startendWithPicture":
            shape = new VEShape(VEShapeType.Pushpin, new VELatLong(lat, lon));
            shape.SetDescription(desc);
            if (map.GetMapMode() == VEMapMode.Mode3D)
                shape.SetCustomIcon(SetPinIcon("startend", "gr", "3D"));
            else
                shape.SetCustomIcon("<div style=\"position:relative;top:-41px;left:-10px;\"><img class=\"IE6Png\" src=\"/App_Themes/CWDefault/MapIcons/Pin_Loop.png\" style=\"border:0px;\"></div>");
            trackPinsLayer.AddShape(shape);
            break;
        case "start":
        case "startWithPicture":
            shape = new VEShape(VEShapeType.Pushpin, new VELatLong(lat, lon));
            shape.SetDescription(desc);
            if (map.GetMapMode() == VEMapMode.Mode3D)
                shape.SetCustomIcon(SetPinIcon("start", "gr", "3D"));
            else
                shape.SetCustomIcon("<div style=\"position:relative;top:-41px;left:-10px;\"><img class=\"IE6Png\" src=\"/App_Themes/CWDefault/MapIcons/Pin_Start.png\" style=\"border:0px;\"></div>");
            trackPinsLayer.AddShape(shape);
            break;
        case "end":
        case "endWithPicture":
            shape = new VEShape(VEShapeType.Pushpin, new VELatLong(lat, lon));
            shape.SetDescription(desc);
            if (map.GetMapMode() == VEMapMode.Mode3D)
                shape.SetCustomIcon(SetPinIcon("end", "gr", "3D"));
            else
                shape.SetCustomIcon("<div style=\"position:relative;top:-41px;left:-10px;\"><img class=\"IE6Png\" src=\"/App_Themes/CWDefault/MapIcons/Pin_End.png\" style=\"border:0px;\"></div>");
            trackPinsLayer.AddShape(shape);
            break;
        case "picture":
            shape = new VEShape(VEShapeType.Pushpin, new VELatLong(lat, lon));
            shape.SetDescription(desc);
            if (map.GetMapMode() == VEMapMode.Mode3D)
                shape.SetCustomIcon(SetPinIcon("picture", "gr", "3D"));
            else
                shape.SetCustomIcon("<div style=\"position:relative;top:-23px;left:-8px;\"><img class=\"IE6Png\" src=\"/App_Themes/CWDefault/MapIcons/Pin_Photo.png\" style=\"border:0px;\"></div>");
            picLayer.AddShape(shape);
            break;
        case "pictureComment":
            shape = new VEShape(VEShapeType.Pushpin, new VELatLong(lat, lon));
            shape.SetDescription(desc);
            if (map.GetMapMode() == VEMapMode.Mode3D)
                shape.SetCustomIcon(SetPinIcon("picture", "gr", "3D"));
            else
                shape.SetCustomIcon("<div style=\"position:relative;top:-23px;left:-8px;\"><img class=\"IE6Png\" src=\"/App_Themes/CWDefault/MapIcons/Pin_PhotoComment.png\" style=\"border:0px;\"></div>");
            picLayer.AddShape(shape);
            break;
        case "poi":
            shape = new VEShape(VEShapeType.Pushpin, new VELatLong(lat, lon));
            shape.SetDescription(desc);
            if (map.GetMapMode() == VEMapMode.Mode3D)
                shape.SetCustomIcon(SetPOIIcon(poiTypeID, "sm", "3D"));
            else
                shape.SetCustomIcon(String.format("<div style=\"position:relative;top:-27px;left:-5px;\"><img class=\"IE6Png\" src=\"/App_Themes/CWDefault/PoiIcons/POIPin-{0}_small.png\" style=\"border:0px;\"></div>", poiTypeID));
            poiLayer.AddShape(shape);
            break;
        case "comment":
            break;
    }
}
function CWMapDrawRoute(cRoute, lineColor, lineAlpha) {
    if (lineAlpha == null) {
        lineAlpha = 0.7;
    }

    if (lineColor == null) {
        if (cRoute.MainRouteTypeID == 19 || cRoute.MainRouteTypeID == 24 || cRoute.MainRouteTypeID == 27)
            lineColor = new VEColor(0, 0, 255, lineAlpha);
        else
            lineColor = new VEColor(255, 0, 0, lineAlpha);
    }
    else {
        rPart = parseInt(lineColor.substring(1, 3), 16).toString();
        gPart = parseInt(lineColor.substring(3, 5), 16).toString();
        bPart = parseInt(lineColor.substring(5, 7), 16).toString();
        lineColor = new VEColor(rPart, gPart, bPart, lineAlpha);
    }
    
    VETrackPoints = new Array();
    VETrackPointsShadow = new Array();
    alternate_index = 0;
    for (var t = 0; t < cRoute.TrackPoints.length; t++) {
        if (map.GetMapMode() == VEMapMode.Mode3D) {
            // If there is two subsequent points with the same elevation & lat & lon -> bing maps gets an error and doesnt draw the track
            if (t > 0 && (cRoute.TrackPoints[t-1].Ele == cRoute.TrackPoints[t].Ele)) {
                new_ele = cRoute.TrackPoints[t].Ele + Math.pow(-1, alternate_index) * 0.01;
                alternate_index++;
                VETrackPoints.push(new VELatLong(cRoute.TrackPoints[t].Lat, cRoute.TrackPoints[t].Lon, new_ele, VEAltitudeMode.Absolute));
            }
            else {
                VETrackPoints.push(new VELatLong(cRoute.TrackPoints[t].Lat, cRoute.TrackPoints[t].Lon, cRoute.TrackPoints[t].Ele, VEAltitudeMode.Absolute));
            }
            VETrackPointsShadow.push(new VELatLong(cRoute.TrackPoints[t].Lat, cRoute.TrackPoints[t].Lon));
        }
        else {
            VETrackPoints.push(new VELatLong(cRoute.TrackPoints[t].Lat, cRoute.TrackPoints[t].Lon));
        }
    }
    var shape = new VEShape(VEShapeType.Polyline, VETrackPoints);
    shape.SetLineWidth(3);
    shape.SetLineColor(lineColor);
    shape.HideIcon();
    trackPointsLayer.AddShape(shape);
    
    // For 3D Mode, also draw the shadow line on the ground
    if (map.GetMapMode() == VEMapMode.Mode3D) {
        var shadowShape = new VEShape(VEShapeType.Polyline, VETrackPointsShadow);
        shadowShape.SetLineWidth(3);
        shadowShape.SetLineColor(new VEColor(155, 155, 155, 1));
        shadowShape.HideIcon();
        trackPointsLayer.AddShape(shadowShape);
    }
}


// ###############################################################################
// ADD POIS AND COMMENTS TO THE MAP
// ###############################################################################
var AddLayer = null;
var marker = null;
var loc = null;
var moving = false;
var POIDescription;
function MapAddPOI(Description) {
    map.AttachEvent("onmousemove", mouseMoveHandler);
    map.AttachEvent("onmousedown", mouseDownHandler);
    map.AttachEvent("onmouseup", mouseUpPOIAddHandler);
    loc = map.GetCenter();
    AddLayer = new VEShapeLayer();
    map.AddShapeLayer(AddLayer);
    marker = new VEShape(VEShapeType.Pushpin, loc);
    marker.SetCustomIcon("<div style='position:relative;top:-13px;left:-9px;z-index:10;'><img src='/App_Themes/CWDefault/PoiIcons/POIPin-1_small.png'></div>");
    POIDescription = Description;
    marker.SetDescription(String.format(POIDescription, jsonMapDataRoutes[0].ID, loc.Latitude.toString().replace('.', ','), loc.Longitude.toString().replace('.', ',')));
    AddLayer.AddShape(marker);
    map.ShowInfoBox(marker);
}
function MapAddComment(Description) {
    // Map
    map.AttachEvent("onmousemove", mouseMoveHandler);
    map.AttachEvent("onmousedown", mouseDownHandler);
    map.AttachEvent("onmouseup", mouseUpCommentAddHandler);
    loc = map.GetCenter();
    AddLayer = new VEShapeLayer();
    map.AddShapeLayer(AddLayer);
    marker = new VEShape(VEShapeType.Pushpin, loc);
    marker.SetCustomIcon("<div style='position:relative; top:-29px; left:-12px; z-index:10;'><img src='/App_Themes/CWDefault/MapIcons/Pin_Comment.png'></div>");
    marker.SetDescription(Description);
    AddLayer.AddShape(marker);
    map.ShowInfoBox(marker);

    // Localize
    if (Sys.CultureInfo.CurrentCulture.name.indexOf('de') > 0) {
        document.getElementById(CCGeocodedCommentLatitude).value = loc.Latitude.toString().replace('.', ',');
        document.getElementById(CCGeocodedCommentLongitude).value = loc.Longitude.toString().replace('.', ',');
    } else {
        document.getElementById(CCGeocodedCommentLatitude).value = loc.Latitude.toString();
        document.getElementById(CCGeocodedCommentLongitude).value = loc.Longitude.toString();
    }
}
function MapCancelAddPOI() {
    map.DetachEvent("onmousemove", mouseMoveHandler);
    map.DetachEvent("onmousedown", mouseDownHandler);
    map.DetachEvent("onmouseup", mouseUpPOIAddHandler);
    map.HideInfoBox(marker);
    map.DeleteShapeLayer(AddLayer);
    AddLayer = null;
}
function MapCancelAddComment() {
    map.DetachEvent("onmousemove", mouseMoveHandler);
    map.DetachEvent("onmousedown", mouseDownHandler);
    map.DetachEvent("onmouseup", mouseUpCommentAddHandler);
    map.HideInfoBox(marker);
    map.DeleteShapeLayer(AddLayer);
    AddLayer = null;
}
//onmouseup handler for Action: Add POI
function mouseUpPOIAddHandler(e) {
    if (moving && e.leftMouseButton) {
        moving = false;
        map.vemapcontrol.EnableGeoCommunity(false);

        // Do the action
        marker.SetDescription(String.format(POIDescription, jsonMapDataRoutes[0].ID, loc.Latitude.toString().replace('.', ','), loc.Longitude.toString().replace('.', ',')));
        map.ShowInfoBox(marker);
    }
}
function mouseUpCommentAddHandler(e) {
    if (moving && e.leftMouseButton) {
        moving = false;
        map.vemapcontrol.EnableGeoCommunity(false);
        
        // Localize
        if (Sys.CultureInfo.CurrentCulture.name.indexOf('de') > 0) {
            document.getElementById(CCGeocodedCommentLatitude).value = loc.Latitude.toString().replace('.', ',');
            document.getElementById(CCGeocodedCommentLongitude).value = loc.Longitude.toString().replace('.', ',');
        } else {
            document.getElementById(CCGeocodedCommentLatitude).value = loc.Latitude.toString();
            document.getElementById(CCGeocodedCommentLongitude).value = loc.Longitude.toString();
        }
        // Show Add Comment Popup
        map.ShowInfoBox(marker);
    }
}
// general OnMouseDown handler
function mouseDownHandler(e) {
    if (e.leftMouseButton && e.elementID) {
        moving = true;
        map.vemapcontrol.EnableGeoCommunity(true);
    }
}
// general OnMouseMove handler
function mouseMoveHandler(e) {
    loc = map.PixelToLatLong(new VEPixel(e.mapX, e.mapY));
    if (moving) {
        map.HideInfoBox(marker);
        marker.SetPoints(loc);
    }
}


// ###############################################################################
// ADD COMMENTS TO MAP
//      External Function Support for (CommentList.ascx)
// ###############################################################################
var CommentLayer = null;
function AddCommentOnMap(comment, GeocodedHeaderText) {
    var description = CreateCommentPopup();
    description = String.format(description, ResGeocodedCommentHeader, unescape(comment.Text), comment.CreatedByUserAvatar.replace("_thumb25_", "_thumb50_"), comment.CreatedByUserLink, comment.CreatedByUserDisplayName, comment.PostedTime);
    commentShape = new VEShape(VEShapeType.Pushpin, new VELatLong(comment.Latitude, comment.Longitude));
    if (map.GetMapMode() == VEMapMode.Mode3D) {
        c_icon = new VECustomIconSpecification();
        c_icon.Image = "/App_Themes/CWDefault/MapIcons/Pin_Comment.png";
        c_icon.ImageOffset = new VEPixel(-5, -20);
        c_icon.TextContent = " ";
        commentShape.SetCustomIcon(c_icon);
    }
    else {
        commentShape.SetCustomIcon("<div style='position:relative; top:-29px; left:-12px; z-index:10;'><img src='/App_Themes/CWDefault/MapIcons/Pin_Comment.png'></div>");
    }
    commentShape.SetDescription(description);
    if (CommentLayer == null) {
        CommentLayer = new VEShapeLayer();
        map.AddShapeLayer(CommentLayer);
        CommentLayer.AddShape(commentShape);
    }
    else {
        CommentLayer.AddShape(commentShape);
    }
}
// External Function Support for (CommentList.ascx)
function DeleteAllCommentsOnMap() {
    if (CommentLayer != null)
        CommentLayer.DeleteAllShapes();
}




// ###############################################################################
// SEARCH THE MAP
// ###############################################################################
function SearchAndMoveMap(searchstring) {
    try {
        //document.getElementById('resultDiv').style.display = "none";
        //layer.DeleteAllShapes();
        results = map.Find(null,
              searchstring,
              null,
              null,
              0, // changed from index
              10,
              false,
              false,
              false,
              false,
              SearchCallback);
        //index = parseInt(index) + 19;
    }
    catch (e) {
        alert(e.message);
    }
}

function SearchCallback(a, b, c, d, e) {
    //var results = "";
    SearchLayer = new VEShapeLayer();

    if (c != null && c.length > 1) {
        results = "<div style=\"font-size:12px; background-color:#eeeeee; color:#666666; padding:3px;\">" + Resources_MapControlView.SearchMoreLocationsFoundInfo + "</div><br />";
        for (x = 0; x < c.length; x++) {
            results += "<a href=\"javascript:SearchFixChoice(" + c[x].LatLong + ");\">" + c[x].Name + "</a><br />";
        }
        map.SetCenter(c[0].LatLong);
        results += "<br /><a href=\"javascript:CloseSearch()\" style=\"color:#FFCC33;\">" + Resources_MapControlView.SearchCloseWindow + "</a>";
        document.getElementById("MapCustomMenuSearchResult").innerHTML = results;
        document.getElementById("MapCustomMenuSearchResult").style.display = "block";
    } else if (c != null && c.length == 1) {
        document.getElementById("MapCustomMenuSearchResult").style.display = "none";
        map.SetCenter(c[0].LatLong);
    } else {
    results = "<div style=\"font-size:12px; color:#666666; padding:3px;\">" + Resources_MapControlView.SearchNoLocationFoundInfo + "</div><br />";
        results += "<br /><a href=\"javascript:CloseSearch()\" style=\"color:#ffcc33;\">" + Resources_MapControlView.SearchCloseWindow + "</a>";
        document.getElementById("MapCustomMenuSearchResult").innerHTML = results;
        document.getElementById("MapCustomMenuSearchResult").style.display = "block";
    }
}
function SearchFixChoice(x, y) {
    loc = new VELatLong(x, y);
    map.SetCenter(loc);
    CloseSearch();
}
function CloseSearch() {
    document.getElementById("MapCustomMenuSearchResult").innerHTML = "";
    document.getElementById("MapCustomMenuSearchResult").style.display = "none";
}


// ###############################################################################
// ADDITIONAL MAP INFOS (wiki, weather, mountain names
// ###############################################################################
var VEMapWikiLayer = null;
var VEMapWeatherLayer = null;
var VEMapMountainnamesLayer = null;

function MapControlVEAddWikiEntries() {
    var NWLatLong = null;
    var y = 0;
    while (NWLatLong == null) {
        pixel = new VEPixel(0, y);
        try { NWLatLong = new VELatLong(map.PixelToLatLong(pixel).Latitude, map.PixelToLatLong(pixel).Longitude); }
        catch (error) { NWLatLong = null; }
        y = y + 10;
    }
    var mapBox = Sys.UI.DomElement.getBounds(document.getElementById(MapControlViewMapID));
    pixel = new VEPixel(mapBox.width, mapBox.height);
    var SELatLong = new VELatLong(map.PixelToLatLong(pixel).Latitude, map.PixelToLatLong(pixel).Longitude);
    MapControlShowMessageBox(true, "Please wait while retrieving wikipedia data...", 3000);
    LeaveYourTracks.com.WSAjax.AJAXSvc.GetWikiByBoundingBox(NWLatLong.Latitude, SELatLong.Latitude, SELatLong.Longitude, NWLatLong.Longitude, "de", MapControlVEAddWikiEntries_success, MapControlVEAddWikiEntries_Failed);
}
function MapControlVEAddWikiEntries_success(e) {
    var wikiData = Sys.Serialization.JavaScriptSerializer.deserialize(e);
    var entriesFound = 0;

    if (wikiData.geonames && wikiData.geonames.length > 0) {
        Array.forEach(wikiData.geonames, MapControlVEAddWikiPushpin);
        entriesFound = wikiData.geonames.length;
    }

    if (entriesFound > 0) {
        var message = String.format("{0} wikipedia entries found.", entriesFound);
        MapControlShowMessageBox(true, message, 2000);
    }
    else {
        MapControlShowMessageBox(true, "No Wikipedia entries found. Please try again.", 5000);
    }
}
function MapControlVEAddWikiEntries_Failed(e) {
    MapControlShowMessageBox(true, "Error while connecting to the remote web service. Please try again later.", 5000);
}
function MapControlVEAddWikiPushpin(entry) {
    var icon;
    var htmlImage = "<br/><b>Summary: </b> {1}<br/>" +
            "<br/><img src=\"{3}\" alt=\"Thumbnail\" /><br/><br/><b>Wikipedia-Link: </b><a href=\"http://{2}\" target=\"_new\" >{0}</a>";
    var htmlNoImage = "<br/><b>Summary: </b> {1}<br/>" +
            "<br/><br/><b>Wikipedia-Link: </b><a href=\"http://{2}\" target=\"_new\" >{0}</a>";
    var details = "";
    if (entry.thumbnailImg == undefined)
        details = String.format(htmlNoImage,
            entry.title, entry.summary, escape(entry.wikipediaUrl));
    else
        details = String.format(htmlImage,
            entry.title, entry.summary, escape(entry.wikipediaUrl),
            escape(entry.thumbnailImg));

    icon = String.format("/images/Wikipedia_Icon_kl.png", icon);
    
    // Add the pushpin
    if (VEMapWikiLayer == null) {
        VEMapWikiLayer = new VEShapeLayer();
        map.AddShapeLayer(VEMapWikiLayer);
    }

    shp = new VEShape(VEShapeType.Pushpin, new VELatLong(entry.lat, entry.lng));
    shp.SetTitle(entry.title);
    shp.SetDescription(details);
    if (icon) {
        shp.SetCustomIcon(icon);
    }
    VEMapWikiLayer.AddShape(shp);
}
// Weather --------------------------------
function MapControlVEAddWeatherInfos() {
    var centre = map.GetCenter();
    LeaveYourTracks.com.WSAjax.AJAXSvc.GetWeatherByLocation(centre.Latitude, centre.Longitude, MapControlVEAddWeatherInfos_success, MapControlVEAddWeatherInfos_Failed);
    MapControlShowMessageBox(true, "Please wait while retrieving weather data...");
}
function MapControlVEAddWeatherInfos_Failed(e) {
    MapControlShowMessageBox(true, "Error while connecting to the remote web service. Please try again later.", 5000);
}
function MapControlVEAddWeatherInfos_success(e) {
    var weatherData = Sys.Serialization.JavaScriptSerializer.deserialize(e);
    var stationsFound = 0;
    if (weatherData.weatherObservations && weatherData.weatherObservations.length > 0) {
        Array.forEach(weatherData.weatherObservations, MapControlVEAddWeatherPushpin);
        stationsFound = weatherData.weatherObservations.length;
    }
    if (stationsFound > 0) {
        var message = String.format("Data was retrieved for {0} weather stations.", stationsFound);
        MapControlShowMessageBox(true, message, 2000);
    }
    else {
        MapControlShowMessageBox(true, "No weather data was found. Please try again.", 5000);
    }
}
function MapControlVEAddWeatherPushpin(observation) {
    var icon;
    // The observation time is parsed in order to determine 
    // whether the observation was taken during the day or 
    // the night and choose an appropriate icon.
    // The format of the returned date is yyyy-MM-dd hh:mm:ss 
    var d = observation.datetime;
    var date = new Date(d.substr(0, 4), d.substr(5, 2), d.substr(8, 2),
                        d.substr(11, 2), d.substr(14, 2), d.substr(17, 2));

    var isDay = (date.getHours() > 6 && date.getHours() < 20);

    switch (observation.clouds) {
        case 'clear sky':
            if (isDay) icon = '32'; else icon = '31';
            break;
        case 'few clouds':
            if (isDay) icon = '30'; else icon = '29';
            break;
        case 'scattered clouds':
            if (isDay) icon = '28'; else icon = '27';
            break;
        case 'broken clouds':
            icon = '26';
            break;
        case 'overcast':
        case 'vertical visibility':
            icon = '23';
            break;
        default:
            icon = 'NA';
    }
    // The wind speed is converted from knots to m/s 
    var windSpeedMs = Math.round(observation.windSpeed * 0.5144444 * 100) / 100;

    var html = "<em>{0}</em><br/><b>Clouds:</b> {1}<br/><b>Weather condition:</b> {2}<br/>" +
            "<b>Temperature:</b> {3} °C<br/><b>Dew Point:</b> {4} °C<br/>" +
            "<b>Wind:</b> {5}kt ({6} m/s) from {7}°<br/><b>Altimeter:</b> {8} hPa";
    var details = String.format(html,
            observation.datetime, observation.clouds, observation.weatherCondition,
            observation.temperature, observation.dewPoint, observation.windSpeed,
            windSpeedMs, observation.windDirection, observation.hectoPascAltimeter);

    icon = String.format("/images/{0}.png", icon);
    icon = GetCorrectIcon(icon, 48, 48, -10, -12);
    
    //AddPushpin(observation.lat, observation.lng, observation.stationName, details, icon, 10);
    if (VEMapWeatherLayer == null) {
        VEMapWeatherLayer = new VEShapeLayer();
        map.AddShapeLayer(VEMapWeatherLayer);
    }
    shp = new VEShape(VEShapeType.Pushpin, new VELatLong(observation.lat, observation.lng));
    shp.SetTitle(observation.stationName);
    shp.SetDescription(details);
    if (icon) {
        shp.SetCustomIcon(icon);
    }
    VEMapWeatherLayer.AddShape(shp);
}
// Mountain names ---------------------
function MapControlVEAddMountainNames() {
    var centre = map.GetCenter();
    LeaveYourTracks.com.WSAjax.AJAXSvc.GetMountainNames(centre.Latitude, centre.Longitude, MapControlVEAddMountainNames_success, MapControlVEAddMountainNames_Failed);
    MapControlShowMessageBox(true, "Please wait while retrieving mountain data...", 3000);
}
function MapControlVEAddMountainNames_Failed(e) {
    MapControlShowMessageBox(true, "Error while connecting to the remote web service. Please try again later.", 5000);
}
function MapControlVEAddMountainNames_success(e) {
    var MountainNames;
    var entriesFound = 0;

    for (i = 0; i < e.length; i++) {
        var Mountain = e[i];
        MapControlVEAddMountainNamePushpin(Mountain);
    }

    if (e.length > 0) {
        var message = String.format("{0} mountains found.", e.length);
        MapControlShowMessageBox(true, message, 5000);
    }
    else {
        MapControlShowMessageBox(true, "No mountains found...", 5000);
    }
}
function MapControlVEAddMountainNamePushpin(Mountain) {
    icon = new VECustomIconSpecification();
    icon.Image = Mountain.PinURL;
    icon.TextContent = " ";
    point = new VELatLong(Mountain.Latitude, Mountain.Longitude);
    shp = new VEShape(VEShapeType.Pushpin, point);
    shp.SetAltitude(50.0, VEAltitudeMode.RelativeToGround);
    shp.SetTitle("");
    shp.SetDescription("");
    shp.SetCustomIcon(icon);
    if (VEMapMountainnamesLayer == null) {
        VEMapMountainnamesLayer = new VEShapeLayer();
        map.AddShapeLayer(VEMapMountainnamesLayer);
    }
    VEMapMountainnamesLayer.AddShape(shp);
}

// Clear all additional infos on the map! -------------------
function MapControlVEClearAdditionalInfosOnMap() {
    if (VEMapWikiLayer != null)
        VEMapWikiLayer.DeleteAllShapes();
    if (VEMapWeatherLayer != null)
        VEMapWeatherLayer.DeleteAllShapes();
    if (VEMapMountainnamesLayer != null)
        VEMapMountainnamesLayer.DeleteAllShapes();
}
