/*
this is defined by the xsl
var mapMarkers[][]
*/
var baseIcon;
var map;
var directions = null;
var startLocation = null;
var endLocation = null;

var mapMarkersCount = 0;
var routePlotted = false;
var allowDirections = false;

var mapMarkersAll = new Array();
var defaultLegendItems = new Array();
var defaultMarkers = new Array();
var defaultLegendStatuses = new Array();

var allowPlotting = false;

var initialLat;
var initialLng;
var initialZoom;

function plotRoute()
{
    allowPlotting = true;
    alert('You can now click on two map points to plot directions');
}

function InitialiseMap(filename, allowDirectionsIn, lat, lng, zoom)
{
    if (GBrowserIsCompatible())
    {
        InitialiseMapLite(allowDirectionsIn, lat, lng, zoom);
        PlotMarkersFromXmlFile(filename);
    }
}
function InitialiseMapLite(allowDirectionsIn, lat, lng, zoom)
{
    initialLat = lat;
    initialLng = lng;
    initialZoom = zoom;
    if (GBrowserIsCompatible())
    {
        map = new GMap2(document.getElementById("map_canvas"));
        map.setCenter(new GLatLng(initialLat, initialLng), initialZoom);
        SetupMapUI(map);
        allowDirections = allowDirectionsIn;
        if (allowDirections)
        {
            directions = new GDirections(map, document.getElementById("directions_canvas"));
            GEvent.addListener(directions, "addoverlay", hideDirectionMarkers);
        }
    }
}
function hideDirectionMarkers()
{
    var numMarkers = directions.getNumGeocodes()
    for (var i = 0; i < numMarkers; i++)
    {
        var marker = directions.getMarker(i);
        if (marker != null)
        {
            marker.hide();
        }
    }
}
function SetupMapUI(map)
{
    var customUI = map.getDefaultUI();
    customUI.maptypes.physical = false;
    customUI.maptypes.hybrid = false;
    customUI.controls.scalecontrol = true;
    map.setUI(customUI);

    baseIcon = new GIcon(G_DEFAULT_ICON);
    //baseIcon.shadow = rootPath + "images/mapicons/shadow.png";
    baseIcon.shadow = null;
    baseIcon.iconSize = new GSize(32, 37);
    //baseIcon.shadowSize = new GSize(37, 34);
    baseIcon.iconAnchor = new GPoint(9, 34);
    baseIcon.infoWindowAnchor = new GPoint(9, 2);
}
function PlotMarkersFromXmlFile(fileName)
{
    $.ajax({
        type: "GET",
        url: rootPath + fileName,
        dataType: "xml",
        success: function(xml)
        {
            var theXml = $(xml);
            theXml.find('legend').find('item').each(parseLegendItem);
            theXml.find('marker').each(parseMarkerItem);
        }
    });
}
function parseLegendItem()
{
    var legendItem = $(this);
    var legendStatus = legendItem.attr('default');
    var legendKey = legendItem.attr('key');

    defaultLegendStatuses[legendKey] = legendStatus;

    if (legendStatus == 'show' || legendStatus == 'notavailable')
    {
        defaultLegendItems[defaultLegendItems.length] = legendKey;
    }
}
function parseMarkerItem()
{
    var markerItem = $(this);
    var legendKey = markerItem.find('key').text();
    var pointLat = markerItem.find('lat').text();
    var pointLng = markerItem.find('lng').text();
    var iconFile = markerItem.find('icon').text() + '.png';
    var iconToUse = new GIcon(baseIcon);       
    
    var point = new GLatLng(parseFloat(pointLat), parseFloat(pointLng));
    iconToUse.image = rootPath + "images/mapicons/" + iconFile;
    markerOptions = { icon: iconToUse, draggable: false };
    var Marker = new GMarker(point, markerOptions);

    var ubound = mapMarkers[legendKey].length;
    mapMarkers[legendKey][ubound] = Marker;
    mapMarkersAll[mapMarkersCount] = Marker;
    mapMarkersCount++;
    map.addOverlay(Marker);
    Marker.bindInfoWindowHtml(buildMarkerDIV(markerItem));
    if (allowDirections)
    {
        GEvent.addListener(Marker, "click", mapPointClick);
    }

    if (defaultLegendStatuses[legendKey] == 'hide')
    {
        Marker.hide();
    }
    
    return Marker;
}
function buildMarkerDIV(markerItem)
{
    var HTML = '<div style="' + 'width: 300px;">' + '<b><u>' + markerItem.find('title').text() + '</u></b>';

    var depth = markerItem.find("depth");
    var information = markerItem.find("information");
    var link = markerItem.find("link");
    var rellink = markerItem.find("rellink");
    var rellinktext = markerItem.find("rellink-text");
    
    
    if (depth != null)
    {
        if (depth.text().length > 0)
        {
            HTML += "<br/><br/><b>Depth:</b> " + depth.text();
        }
    }
    if (information != null)
    {
        if (information.text().length > 0)
        {
            HTML += "<br/><br/><b>Information:</b> " + information.text();
        }
    }
    if (link != null)
    {
        if (link.text().length > 0)
        {
            HTML += '<br/><br/>Click <a target="_blank" href="' + link.text() + '">here</a> for more information';
        }
    }
    if (rellink != null)
    {
        if (rellink.text().length > 0)
        {
            HTML += '<br/><br/><a target="_blank" href="' + rootPath + rellink.text() + '">' + rellinktext.text() + '</a>';
        }
    }

    HTML += '</div>';

    return HTML;
}
function changeMarkerVisibility(checkbox)
{
    if (!checkbox.checked)
    {
        for (var i = 0; i < mapMarkers[checkbox.value].length; i++)
        {
            hideMarker(mapMarkers[checkbox.value][i]);
        }
    }
    if (checkbox.checked)
    {
        if (mapMarkers[checkbox.value].length > 0)
        {
            for (var i = 0; i < mapMarkers[checkbox.value].length; i++)
            {
                var Marker = mapMarkers[checkbox.value][i];
                if (Marker != null)
                {
                    Marker.show();
                }
            }
        }
    }
}
function hideMarker(Marker)
{
    if (Marker != null)
    {
        if (
            (startLocation == null || (startLocation.lat() != Marker.getLatLng().lat() && startLocation.lat() != Marker.getLatLng().lat()))
            &&
            (endLocation == null || (endLocation.lat() != Marker.getLatLng().lat() && endLocation.lat() != Marker.getLatLng().lat()))
       )
        {
            Marker.hide();
        }
    }
}
function checkByParent(aId, aChecked)
{
    var collection = document.getElementById(aId).getElementsByTagName('INPUT');
    for (var x = 0; x < collection.length; x++)
    {
        if (collection[x].type.toUpperCase() == 'CHECKBOX')
        {
            collection[x].checked = aChecked;
        }
    }
}
function clearDirections()
{
    if (routePlotted)
    {
        allowPlotting = false;
        directions.clear();
        startLocation = null;
        endLocation = null;
        routePlotted = false;

        var collection = document.getElementById("map_legend").getElementsByTagName('INPUT');
        for (var i = 0; i < defaultLegendItems.length; i++)
        {
            var legendKey = defaultLegendItems[i];
            for (var l = 0; l < collection.length; l++)
            {
                var checkbox = collection[l];
                if (checkbox.value == legendKey)
                {
                    checkbox.checked = true;
                    changeMarkerVisibility(checkbox);
                }
            }
        }
        for (var i = 0; i < defaultMarkers.length; i++)
        {
            defaultMarkers[i].show();
        }
        map.setCenter(new GLatLng(initialLat, initialLng), initialZoom);
    }
}
function mapPointClick(point)
{
    if (allowPlotting)
    {
        if (startLocation == null)
        {
            startLocation = point;
        }
        else if (endLocation == null)
        {
            endLocation = point;
        }

        if (startLocation != null && endLocation != null && !routePlotted)
        {
            directions.loadFromWaypoints([startLocation, endLocation], { getPolyline: true });
            routePlotted = true;
            for (var i = 0; i < mapMarkersAll.length; i++)
            {
                hideMarker(mapMarkersAll[i]);
            }
            checkByParent("map_legend", false);
        }
    }
}