﻿function EGCSMap() { }

EGCSMap.MapDivId = 'map';
EGCSMap._map = null;
EGCSMap._points = [];
EGCSMap._shapes = [];

EGCSMap.LoadMap = function (latitude, longitude, onMapLoaded) {
    EGCSMap._map = new VEMap(EGCSMap.MapDivId);

    var options = new VEMapOptions();

    options.EnableBirdseye = false

    this._map.SetDashboardSize(VEDashboardSize.Small);

    if (onMapLoaded != null)
        EGCSMap._map.onLoadMap = onMapLoaded;

    if (latitude != null && longitude != null)
        var center = new VELatLong(latitude, longitude);

    EGCSMap._map.LoadMap(center, null, VEMapStyle.Hybrid, null, null, null, null, options);
}

EGCSMap.LoadPin = function (LL, name, description) {
    var shape = new VEShape(VEShapeType.Pushpin, LL);

    //Make a nice Pushpin shape with a title and description
    shape.SetTitle("<span class=\"pinTitle\"> " + escape(name) + "</span>");

    if (description !== undefined) {
        shape.SetDescription("<p class=\"pinDetails\">" + escape(description) + "</p>");
    }

    EGCSMap._map.AddShape(shape);
    EGCSMap._points.push(LL);
    EGCSMap._shapes.push(shape);
}

EGCSMap.FindAddressOnMap = function (where) {
    var numberOfResults = 1;
    var setBestMapView = true;
    var showResults = true;
    var defaultDisambiguation = true;

    EGCSMap._map.Find("", where, null, null, null,
                         numberOfResults, showResults, true, defaultDisambiguation,
                         setBestMapView, EGCSMap._callbackForLocation);
}

EGCSMap._callbackForLocation = function (layer, resultsArray, places, hasMore, VEErrorMessage) {

    if (places == null) {
        EGCSMap._map.ShowMessage(VEErrorMessage);
        return;
    }

    //Make a pushpin for each place we find
    jQuery.each(places, function (i, item) {
        var description = "";
        if (item.Description !== undefined) {
            description = item.Description;
        }
        var LL = new VELatLong(item.LatLong.Latitude,
                        item.LatLong.Longitude);

        EGCSMap.LoadPin(LL, item.Name, description);
    });

    //Make sure all pushpins are visible
    if (EGCSMap._points.length > 1) {
        EGCSMap._map.SetMapView(EGCSMap._points);
    }

    //If we've found exactly one place, that's our address.
    //lat/long precision was getting lost here with toLocaleString, changed to toString
    if (EGCSMap._points.length === 1) {
        jQuery("#Latitude").val(EGCSMap._points[0].Latitude.toString());
        jQuery("#Longitude").val(EGCSMap._points[0].Longitude.toString());
    }
}
