﻿var MARKERS_PER_GRID_SQUARE = 3;
var MARKER_RADIUS = 5;

var _mapPoints = new Array();
var _coordZoomGrids = {};
var _zoomLevels = [0, 7, 9, 11, 13];

// Called from the flash map
function onMapReady() {
    // Show the map key and checkboxes
    $("extranewsbox").style.display = "block";
    $("extranewsboxtitle").innerHTML = "Map Data Layers";
    $("extranewsboxbody").innerHTML = "<div id='mapInfo'>&nbsp;</div><div style='margin-top:20px;' id='mapHoverInfo'>Loading map data...</div>";
    $("extranewsboxbody").style.height = "500px";

    var divMapInfo = document.getElementById("mapInfo");
    var mapInfoHtml = "<table>";

    for (var objectType in _objectTypes) {
        if (!isObjectTypeAreaMarker(objectType))
            mapInfoHtml += getObjectTypeSelectHtml(objectType, _objectTypes[objectType].index);
    }
    mapInfoHtml += "<tr><td colspan='3'>&nbsp;</td></tr>";
    for (var objectType in _objectTypes) {
        if (isObjectTypeAreaMarker(objectType))
            mapInfoHtml += getObjectTypeSelectHtml(objectType, _objectTypes[objectType].index);
    }
    
    mapInfoHtml += "</table>";
    divMapInfo.innerHTML = mapInfoHtml;
    translateLayerLabels();

    document.getElementById("mapHoverInfo").innerHTML = '';
    var map = getMovie("flashMap");
    map.initArrays(_objectTypeCount + 1);
}

function isObjectTypeAreaMarker(objectType) {
    return objectType == "UKCS" || objectType == "ICES Areas";
}

function loadMapData(offset) {
    var mapPointCount = _mapPoints.length;
    // Load the lines and points into the map
    var map = getMovie("flashMap");
    for (var i = offset; i < mapPointCount; i++) {
        var mapPoint = _mapPoints[i];
        var objectTypeName = mapPoint[MAP_POINTS_OBJECT_TYPE];
        if (mapPoint[MAP_POINTS_DATA_TYPE] == "L") {
            var points = mapPoint[MAP_POINTS_POINTS][MAP_POINTS_LINE_POINTS];
            var levels = mapPoint[MAP_POINTS_POINTS][MAP_POINTS_LINE_LEVELS];
            map.addPolyline(_objectTypes[objectTypeName].index, i, points, levels, getOverlayColour(objectTypeName));
        } else if (mapPoint[MAP_POINTS_DATA_TYPE] == "P") {
            var pointCount = mapPoint[MAP_POINTS_POINTS].length;
            var drawCircle = objectTypeName == "SAFETY";
            for (var j = 0; j < pointCount; j++) {
                var lat = mapPoint[MAP_POINTS_POINTS][j][MAP_POINTS_POINT_LAT];
                var lon = mapPoint[MAP_POINTS_POINTS][j][MAP_POINTS_POINT_LON];
                if (_coordZoomGrids[objectTypeName] == null)
                    _coordZoomGrids[objectTypeName] = {};
                var zoomLevel = getZoomLevel(_coordZoomGrids[objectTypeName], lat, lon, 0);
                map.addMarker(_objectTypes[objectTypeName].index, i, j, lat, lon, zoomLevel, MARKER_RADIUS, getOverlayColour(objectTypeName), drawCircle);
            }
        }
    }
}

// This checks that only n markers are shown per zoom level per sector in the grid
function getZoomLevel(coordZoomGrid, lat, lon, zoomIndex) {
    if (zoomIndex >= _zoomLevels.length)
        return _zoomLevels[_zoomLevels.length - 1];
    var key = Math.floor(lat) + ":" + Math.floor(lon);
    if (coordZoomGrid[key] == null)
        coordZoomGrid[key] = MARKERS_PER_GRID_SQUARE;
    if (coordZoomGrid[key] > 0) {
        // offset used to smooth zooms out a bit
        var offset = MARKERS_PER_GRID_SQUARE - coordZoomGrid[key];
        coordZoomGrid[key]--;
        return _zoomLevels[zoomIndex] + offset;
    }
    else // We have allocated enough markers for this grid square. Split the grid square into a sub grid and start again
        return getZoomLevel(coordZoomGrid, lat * 10, lon * 10, zoomIndex + 1);
}

// Called from the flash map for debugging
function writeError(err) {
    var divMapInfo = document.getElementById("mapInfo");
    divMapInfo.innerHTML += "<p>" + err + "</p>"
}

// Called from the flash map
function showLineInfo(mapPointIndex) {
    var divMapHoverInfo = document.getElementById("mapHoverInfo");
    var mapPoint = _mapPoints[mapPointIndex];
    divMapHoverInfo.innerHTML = "<b>" + mapPoint[MAP_POINTS_TEXT] + "</b>";
}

// Called from the flash map
function showMarkerInfo(mapPointIndex, coordIndex) {
    var divMapHoverInfo = document.getElementById("mapHoverInfo");
    var mapPoint = _mapPoints[mapPointIndex];
    var coords = mapPoint[MAP_POINTS_POINTS][coordIndex]
    var html = "<b>" + mapPoint[MAP_POINTS_TEXT] + " - " + coords[MAP_POINTS_POINT_TEXT] + "</b>";
    if (mapPoint[MAP_POINTS_OBJECT_TYPE] == "SPANS")
        html += "<div style='margin-top:20px;'><img alt='SPAN' src='/archive/MapImages/sp.png'/></div>";
    else if (mapPoint[MAP_POINTS_OBJECT_TYPE] != "SAFETY")
        html += "<div style='margin-top:20px;'><img alt='" + coords[MAP_POINTS_POINT_CODE] + "' src='/archive/MapImages/" + coords[MAP_POINTS_POINT_CODE] + ".png'/></div>";
    divMapHoverInfo.innerHTML = html;
}

// Called from the flash map
function clearInfo() {
    document.getElementById("mapHoverInfo").innerHTML = "";
}

// Called from the flash map
function showCoords(lat, lng) {
    if (lat != null && lng != null) {
        var latDir = lat < 0 ? "S" : "N"
        var lngDir = lng < 0 ? "W" : "E"
        $("mapCoords").innerHTML = "Cursor position: " + formatCoord(lat) + " " + latDir + " " + formatCoord(lng) + " " + lngDir;
    }
    else {
        $("mapCoords").innerHTML = "&nbsp;";
    }
}

function formatCoord(coord) {
    var degs = Math.floor(Math.abs(coord));
    var mins = (Math.abs(coord) - degs) * 60;
    mins = Math.round(mins * 1000) / 1000;
    return degs + "°" + mins + "'";
}

function getOverlayColour(objectType) {
    var overlayColour;
    switch (objectType.toUpperCase()) {
        case "PIPELINE":
            overlayColour = 0xff0000;
            break;
        case "SAFETY":
            overlayColour = 0xee00ff;
            break;
        case "SPANS":
            overlayColour = 0x008dff;
            break;
        case "SUBSURFACE":
            overlayColour = 0xdddddd;
            break;
        case "SURFACE":
            overlayColour = 0x00ff00;
            break;
        case "BOUNDARY":
            overlayColour = 0x00f0f0;
            break;
        case "SUSPENDED WELLS":
            overlayColour = 0xf0f000;
            break;
        case "SUSPENDED_WELLS":
            overlayColour = 0xf0f000;
            break;
        case "UKCS":
            overlayColour = 0x4554dd;
            break;
        case "POWER":
            overlayColour = 0xff6600;
            break;
        default:
            overlayColour = 0x000000;
    }
    return overlayColour;
}

function getOverlayColourHexString(objectType) {
    var overlayColourHexString = getOverlayColour(objectType).toString(16);
    while (overlayColourHexString.length < 6)
        overlayColourHexString = "0" + overlayColourHexString;
    return "#" + overlayColourHexString;
}

function toggleMapObjectType(objectTypeIndex) {
    var map = getMovie("flashMap");
    var objectType;
    for (objectType in _objectTypes) {
        if (objectTypeIndex == _objectTypes[objectType].index) {
            break;
        }
    }

    if (_objectTypes[objectType].visible) {
        map.hideOverlays(objectTypeIndex);
    }
    else {
        if (_objectTypes[objectType].isLoaded) {
            map.showOverlays(objectTypeIndex);
        } else {
            var url = "/scripts/" + _objectTypes[objectType].jsonFile;
            $("mapHoverInfo").innerHTML = "Loading " + objectType + " data...";
            new Ajax.Request(url, {
                method: 'get',
                onSuccess: function(transport) {
                    // *** NOTE: need to set .json MIME type in IIS to application/json for this to work ***
                    var offset = _mapPoints.length;
                    _mapPoints = _mapPoints.concat(transport.responseJSON);
                    loadMapData(offset);
                    map.showOverlays(objectTypeIndex);
                    $("mapHoverInfo").innerHTML = '';
                }
            });
            _objectTypes[objectType].isLoaded = true;
        }
    }
    _objectTypes[objectType].visible = !_objectTypes[objectType].visible;
}

function getObjectTypeSelectHtml(objectType, objectTypeIndex) {
    // the label will be translated after the table is rendered by translateLayerLabels(). tempName is from pre-translation days
    var tempName = objectType.substring(0, 1) + objectType.substr(1, objectType.length - 1).toLowerCase();
    if (tempName == "Safety")
        tempName += " Zones";

    var lblId = "lblLayer_" + objectType.toLowerCase().replace(" ", "_");

    var html = "<tr>"
            + "<td><span id='" + lblId + "'>" + tempName + "</span>&nbsp;</td>"
            + "<td><div style='width:30px;height:13px;margin-top:1px;background-color:" + getOverlayColourHexString(objectType) + ";'>&nbsp;</div></td>"
            + "<td><input type='checkbox' onclick='toggleMapObjectType(" + objectTypeIndex + ")' /></td>"
            + "</tr>";
    return html;
}

function translateLayerLabels() {
    try {
        var lang = document.URL.split("/")[3];
        var url = "/archive/Translations/HazardMap/Layers." + lang + ".txt";
        new Ajax.Request(url, {
            method: 'get',
            onSuccess: function(transport) {
                var pairs = transport.responseText.split("\n");
                for (var i = 0; i < pairs.length; i++) {
                    var pair = pairs[i].split("=");
                    var lblId = "lblLayer_" + pair[0].toLowerCase().replace(" ", "_");
                    $(lblId).innerHTML = pair[1];
                }
            }
        });
    }
    catch (err) { }
}

function getMovie(movieName) {
    var movie = null;
    if (navigator.appName.indexOf("Microsoft") != -1)
        movie = window[movieName];

    // window[movieName] does not always work in IE...
    if (movie == null)
        movie = document[movieName];

    return movie;
}
