﻿// MapControl.GeoBase.js v1.2

function CalculateBalloonHAlign(lat, lon) {
    var markerPoint = map.getXY(new Telogis.GeoBase.LatLon(parseFloat(lat), parseFloat(lon)));
    return (map.getWidth() - markerPoint.x > markerPoint.x) ? Balloon.ALIGN_RIGHT : Balloon.ALIGN_LEFT;
}

function CalculateBalloonVAlign(lat, lon) {
    var markerPoint = map.getXY(new Telogis.GeoBase.LatLon(parseFloat(lat), parseFloat(lon)));
    return (map.getHeight() - markerPoint.y > markerPoint.y) ? Balloon.ALIGN_BOTTOM : Balloon.ALIGN_TOP;
}

function ClearRegistry(registryToClear) {
    for (var i = 0; i < registryToClear.length; i++) {
        if (registryToClear[i] != null) {
            if (registryToClear[i].getBalloon() != null) {
                registryToClear[i].getBalloon().destroy();
            }
            registryToClear[i].destroy();
            delete registryToClear[i];
            registryToClear[i] = null;
        }
    }
}

function CreateImageObject(id, layer, latLon, imageSrc, balloonContent, adjustBalloonOnUpdate, balloonLayer, balloonBehavior) {
    /// <summary>Creates a new Telogis.GeoBase.MapLayers.ImageObject</summary>
    /// <param name='id' type='String'>Name for the ImageObject</param>
    /// <param name='layer' type='Telogis.GeoBase.MapLayers.AbstractLayer'>Layer object to which the ImageObject should be added</param>
    /// <param name='latLon' type='Telogis.GeoBase.LatLon'>Latitude/longitude coordinates of the ImageObject</param>
    /// <param name='imageSrc' type='String'>URL of the image that should represent the ImageObject on the map</param>
    /// <param name='balloonContent' type='String'>HTML to be displayed in the ImageObject's balloon, or string representation of a Javascript function (starting with &quot;function (&quot; to be called each time the balloon is opened.</param>
    /// <param name='adjustBalloonOnUpdate' type='Boolean'>DEPRECATED. True if the alignment of the ImageObject's balloon should be adjusted each time the map zooms, finishes a pan, or is resized</param>
    /// <param name='balloonLayer' type='Telogis.GeoBase.MapLayers.AbstractLayer'>Layer object on which this object's balloon should appear (set to this layer by default if this parameter is omitted)</param>
    /// <param name='balloonBehavior' type='String'>Any meaningful combination of the MapLayers.Balloon object's static behavior flags.  Default: Balloon.HOVER_ACTIVE | Balloon.REALIGN_TO_VIEWPORT</param>
    /// <returns type='Telogis.GeoBase.MapLayers.ImageObject'>A new Telogis.GeoBase.MapLayers.ImageObject</returns>

    var createJS = "imgObj = new Telogis.GeoBase.MapLayers.ImageObject({"
        + "layer: layer, "
        + "location: latLon, "
        + "src: imageSrc, ";
    if (balloonContent != null && balloonContent != "") {
        if (balloonBehavior == null) {
            balloonBehavior = "Balloon.HOVER_ACTIVE | Balloon.REALIGN_TO_VIEWPORT";
        }
        createJS += "balloonConfig : { behavior: " + balloonBehavior + ", ";

        if (balloonLayer != null) {
            createJS += "layer: balloonLayer, ";
        }

        if (balloonContent.toString().toLowerCase().substr(0, "function (".length) == "function ("
            || balloonContent.toString().toLowerCase().substr(0, "function(".length) == "function(") {
            createJS += "contentFunc: " + balloonContent + "}, ";
        }
        else {
            createJS += "content: balloonContent }, ";
        }
    }
    createJS += "id: id });";

    var imgObj;
    eval(createJS);
    return imgObj;
}

function GetMapLowerRight() {
    return map.getLatLon(new Telogis.GeoBase.Point(map.getWidth(), map.getHeight()));
}

function GetMapUpperLeft() {
    return map.getLatLon(new Telogis.GeoBase.Point(0, 0));
}

function PanAndZoom(lat, lon, zoom) {
    if (lat != null && lon != null) {
        map.pan(new Telogis.GeoBase.LatLon(parseFloat(lat), parseFloat(lon)));
    }
    if (zoom != null) {
        map.setZoomIndex(zoom);
    }
}

function PositionScaleDefault() {
    if (typeof mapScale == 'object') {
        mapScale.setPosition(new Telogis.GeoBase.Point(0, map.getHeight() - 80));
    }
}

/* 511NJ uses a custom ToggleLayer
function ToggleLayer(layerName) {
    MapLayers[layerName].toggleVisibility();
    if (MapLayers[layerName].isVisible() && typeof mapLayerRefresh == 'object' && mapLayerRefresh[layerName] != null) {
        eval(mapLayerRefresh[layerName]);
    }

    // Update visible layers in cookie map "remember position" callback is active
    if (map["setMapCookieCallback"]) { SetMapCookie(); }
}
*/

// == Functions that can be refactored further =====================================================================

function ZoomToIncident(lat, lon) {
    // This one should be replaced by calls to PanAndZoom
    PanAndZoom(lat, lon, 15);
}

function ZoomMap(sender, args) {
    // This one should be moved to the page that calls it and then it should call PanAndZoom
    PanAndZoom(null, null, sender.get_value());
}

// == Cookie Functions =============================================================================================

function LoadCookieSettings() {
    if (map['setMapCookieCallback']) { map.removeListener({ id: 'setMapCookieCallback' }); }

    var cookieData = GetMapCookie();
    for (i = 0; i < cookieData.length; i++) {
        if (cookieData[i].Name == GetCurrentPageName()) {
            if (cookieData[i].Lat != null && cookieData[i].Lon != null) {
                map.pan(new Telogis.GeoBase.LatLon(parseFloat(cookieData[i].Lat), parseFloat(cookieData[i].Lon)));
            }
            if (cookieData[i].Zoom != null) {
                map.setZoomIndex(parseInt(cookieData[i].Zoom));
            }
            if (cookieData[i].Layers != null) {
                for (var j = 0; j < cookieData[i].Layers.length; j++) {
                    layerItems = cookieData[i].Layers[j].split(".");
                    var desiredLayerState = (layerItems[1] == "1") ? true : false;
                    if ($("#layerckb" + layerItems[0]).length != 0) {
                        // Found the checkbox for this layer
                        if ($("#layerckb" + layerItems[0]).attr('checked') != desiredLayerState) {
                            $("#layerckb" + layerItems[0]).click();
                        }
                    }
                }
            }
            break;
        }
    }

    map.addListener({
        id: 'setMapCookieCallback',
        setMap: function(map) { },
        update: function(updateType) {
            if (updateType == Map.UPDATE_END_PAN || updateType == Map.UPDATE_REDRAW) {
                SetMapCookie();
            }
        }
    });
}

function SetMapCookie() {
    if (map && typeof $.cookie == 'function') {
        var cookieData = GetMapCookie();
        var cookieValue = "";

        // Write current cookie contents into string format.  Skip current page.
        for (i = 0; i < cookieData.length; i++) {
            if (cookieData[i].Name != GetCurrentPageName()) {
                if (cookieValue != "") { cookieValue += "|"; }
                cookieValue += cookieData[i].Name + "|lat=" + cookieData[i].Lat + "&lon=" + cookieData[i].Lon + "&zoom=" + cookieData[i].Zoom;
                var layersValue = "";
                for (var j = 0; j < cookieData[i].Layers.length; j++) {
                    if (layersValue != "") { layersValue += ","; }
                    layersValue += cookieData[i].Layers[j];
                }
                cookieValue += layersValue;
            }
        }

        // Add current page to cookieValue and set cookie
        if (cookieValue != "") { cookieValue += "|"; }
        cookieValue += GetCurrentPageName() + "|lat=" + map.getCenter().lat + "&lon=" + map.getCenter().lon + "&zoom=" + map.getZoomIndex();
        cookieValue += "&layers=";
        var layersValue = "";
        $(".MapLegendCheckbox").each(function() {
            var layerName = this.id.replace("layerckb", "");
            var layerVis = $(this).attr('checked') ? "1" : "0";
            if (layersValue.length > 0) { layersValue += ","; }
            layersValue += layerName + "." + layerVis;
        });
        cookieValue += layersValue;
        $.cookie(mapCookieName, cookieValue, { expires: 7 });
    }
}

// == Display/Position Loading and Error Bar Functions ==========================================================

function DisplayMapLoading() {
    var loadingBarTop = $(mapContainerID).position().top + $(mapContainerID).height() - 63;
    $("#LoadingBar").css("top", "" + loadingBarTop + "px");
    $("#LoadingBar").css("left", $(mapContainerID).position().left);
    $("#LoadingBar").show("fast");
}

function DisplayMapError(errorMessage) {
    if ($("#MapErrorBar").html().indexOf(errorMessage) == -1) {
        if ($("#MapErrorBar").html() != "") {
            $("#MapErrorBar").html($("#MapErrorBar").html() + "<br />" + errorMessage);
        }
        else {
            $("#MapErrorBar").html(errorMessage);
        }

        var mapErrorBarWidth = $(mapContainerID).width() - 10;
        $("#MapErrorBar").css("top", $(mapContainerID).position().top);
        $("#MapErrorBar").css("left", $(mapContainerID).position().left);
        $("#MapErrorBar").width(mapErrorBarWidth);
        $("#MapErrorBar").show("normal");

        if (hideMapErrorBarTimeout != null) {
            clearTimeout(hideMapErrorBarTimeout);
        }
        hideMapErrorBarTimeout = setTimeout("HideMapError();", 7 * 1000);
    }
}
