﻿function GetCameraBalloonContent(cameraDescription, cameraImageURL) {
    /// <summary>Returns the content of a camera balloon with the balloon div width and the camera image size adjusted, based on the size of the map, to not display any of the image "off the map"</summary>
    var ID = cameraImageURL.replace("http://", "");
    while (ID.indexOf("/") != -1) { ID = ID.replace("/", ""); }
    while (ID.indexOf(".") != -1) { ID = ID.replace(".", ""); }
    while (ID.indexOf(" ") != -1) { ID = ID.replace(" ", ""); }
    
    var balloonWidth = 300, imageWidth = 297, imageHeight = 225;
    var maxBalloonWidth = Math.floor(map.getWidth() / 2);
    var maxImageHeight = Math.floor(map.getHeight() / 2) - 43 - 30;  // 43 = dock height, 30 = balloon description area
    if (balloonWidth > maxBalloonWidth) {
        balloonWidth = maxBalloonWidth;
        imageWidth = balloonWidth - 3;
        imageHeight = Math.floor(imageWidth * 0.76);
    }
    if (imageHeight > maxImageHeight) {
        imageHeight = maxImageHeight;
        imageWidth = Math.floor(imageHeight * 1.32);
        balloonWidth = imageWidth + 3;
    }

    // DateTime.Now.ToString("yyyyMMddHHmmss");
    var now = new Date();
    var timestampID = now.getFullYear().toString() + now.getMonth().toString() + now.getDate().toString() + now.getHours().toString() + now.getMinutes().toString() + now.getSeconds().toString();

    var balloonContent = '<div class="mapBalloon" style="width:' + balloonWidth + 'px">' +
        '<strong>' + cameraDescription + '</strong><br />' + 
        '<div id="lc' + ID + '" style="display:block">Loading camera image...</div>' +
        '<img onload="HideCameraImageLoading(\'' + ID + '\');" class="cameraImage" width="' + imageWidth + 'px" height="' + imageHeight + 'px" src="' + cameraImageURL + '?timestamp=' + timestampID + '" />' +
        '</div>';
    return balloonContent;
}

function GetDeviceBalloonContent(deviceID, direction, postedSpeed, speed, description) {
    var content = '<div class="mapBalloon" style="width:180px">' +
            '<span style="font-weight:bold">Device ID:</span> ' + deviceID + '<br />' +
            '<span style="font-weight:bold">Direction:</span> ' + direction + '<br />' +
            '<span style="font-weight:bold">Posted Speed:</span> ' + postedSpeed + '<br />' +
            '<span style="font-weight:bold">Current Speed:</span> ' + speed + '<br />' +
            '<span style="font-weight:bold">Description:</span> ' + description + '<br />' +
            '</div>';
//    var content = '<div class="mapBalloon" style="width:300px">' +
//            '<span style="font-weight:bold">Device ID:</span> ' + deviceID + '<br />' +
//            '<span style="font-weight:bold">Road:</span> ' + roadName + ' ' + direction + '<br />' +
//            '<span style="font-weight:bold">Speed:</span> ' + speed + '<br />' +
//            '<span style="font-weight:bold">Last Updated:</span> ' + lastUpdate + ' (' + age + ' minutes ago)<br />' +
//            '</div>';
    return content;
}

function HideCameraImageLoading(ID) {
    $("#lc" + ID).hide();
}

// == Scaled Icons Functions ============================================================================================

// To disable scaled icons: set scaledIconsEnabled = false

var scaledIconsEnabled = false;
var currentCameraScaledIcon = "";
var currentZoomRange = -1;
var previousZoomRange = -1;

function GetCameraScaledIconURL() {
    if (scaledIconsEnabled) {
        if (currentCameraScaledIcon == "") {
            RefreshScaledIcons();
        }
        return currentCameraScaledIcon;
    }
    else return "/images/cctv.png";
}

function GetSpotSpeedScaledIconURL(iconURL) {
    if (scaledIconsEnabled) {
        if (currentZoomRange == -1) {
            RefreshScaledIcons();
        }
        return iconURL.replace("spotspeed", "scaledicons").replace(".png", "-0" + currentZoomRange.toString() + ".png");
    }
    else return iconURL;
}

function RefreshScaledIcons() {
    if (scaledIconsEnabled) {
        var iconWidthHeight = 0;
        var zoomIndex = map.getZoomIndex();

        switch (true) {
            case (zoomIndex >= 0 && zoomIndex <= 6):
                currentZoomRange = 1;
                iconWidthHeight = 12;
                break;
            case (zoomIndex >= 7 && zoomIndex <= 8):
                currentZoomRange = 2;
                iconWidthHeight = 16;
                break;
            case (zoomIndex >= 9 && zoomIndex <= 10):
                currentZoomRange = 3;
                iconWidthHeight = 20;
                break;
            case (zoomIndex >= 11 && zoomIndex <= 12):
                currentZoomRange = 4;
                iconWidthHeight = 24;
                break;
            case (zoomIndex >= 13 && zoomIndex <= 14):
                currentZoomRange = 5;
                iconWidthHeight = 28;
                break;
            case (zoomIndex >= 15 && zoomIndex <= 16):
                currentZoomRange = 6;
                iconWidthHeight = 32;
                break;
            case (zoomIndex >= 17 && zoomIndex <= 18):
                currentZoomRange = 7;
                iconWidthHeight = 36;
                break;
            case (zoomIndex == 19):
                currentZoomRange = 8;
                iconWidthHeight = 40;
                break;
            default:
                currentZoomRange = 4;
                iconWidthHeight = 24;
                break;
        }

        // If the new currentZoomRange does not match previousZoomRange, update/refresh layers as appropriate.
        if (currentZoomRange != previousZoomRange) {
            previousZoomRange = currentZoomRange;

            // Update cameras layer
            currentCameraScaledIcon = "/images/scaledicons/cctv-0" + currentZoomRange + ".png";
            MapLayers['camerasLayer'].reconfigure({ size: new Size(iconWidthHeight, iconWidthHeight) });

            // Update spot speed layer
            MapLayers['spotSpeedDevicesLayer'].reconfigure({ size: new Size(iconWidthHeight, iconWidthHeight) });
        }

        // Set this function to be called every time the map's zoom changes, if it isn't already
        if (!map['ScaledIconsListener']) {
            map.addListener({
                id: 'ScaledIconsListener',
                setMap: function(map) { },
                update: function(updateType) {
                    if (updateType & Map.UPDATE_ZOOM) {
                        RefreshScaledIcons();
                    }
                }
            });
        }
    }
}

// == Ajax Calls ========================================================================================================

function UpdateCameras() {
    if (MapLayers['camerasLayer'].isVisible()) {
        AjaxCallWithRetry(null, '/services/MapServiceProxy.asmx/GetFullCameraListXML', null, null, null,
            UpdateCamerasXML, UpdateCamerasXMLError, 3);
    }
}

function UpdateDevices() {
    if (MapLayers['spotSpeedDevicesLayer'].isVisible()) {
        AjaxCallWithRetry(null, '/services/MapServiceProxy.asmx/GetCurrentSpeedsXML', null, null, null,
            UpdateDevicesXML, UpdateDevicesXMLError, 3);
    }
}


// == Ajax Callbacks ====================================================================================================

var camerasLoaded = false;
function UpdateCamerasXML(result) {
    // Workaround for XSLTObjectLayer - only load cameras once, but only do
    // it when the camerasLayer is visible.
    // Once XSLTObjectLayer fixed, this function should only call .loadXML line.
    if (MapLayers["camerasLayer"].isVisible() && !camerasLoaded) {
        MapLayers['camerasLayer'].loadXML(result.d);
        camerasLoaded = true;
    }
}

function UpdateCamerasXMLError(xhr, textStatus, thrownError) {
    AjaxErrorHandler("services/MapServiceProxy.asmx/GetFullCameraListXML", xhr, textStatus, thrownError,
        "UpdateCamerasXML(result);",
        "UpdateCamerasXMLError(xhr, textStatus, thrownError);"
    );
}

function UpdateDevicesXML(devices) {
    if (MapLayers["spotSpeedDevicesLayer"].isVisible()) {
        MapLayers['spotSpeedDevicesLayer'].loadXML(devices.d);
    }
}

function UpdateDevicesXMLError(xhr, textStatus, thrownError) {
    AjaxErrorHandler("/services/MapServiceProxy.asmx/GetCurrentSpeedsXML", xhr, textStatus, thrownError,
        "UpdateDevicesCallback(result);", "UpdateDevicesErrorHandler(xhr, textStatus, thrownError);"
    );
}
