﻿// default defined behaviour.
var xmldoc = null;
var xml = null;
var image = "http://labs.google.com/ridefinder/images/mm_20_red.png";
var shadow = "http://labs.google.com/ridefinder/images/mm_20_shadow.png";
var zoomlevel = 9;
var enableDragging = true;
var mapType = "G_NORMAL_MAP";
var map;
var radiusSize;
var keyhole;
var radiusColour;
var radiusLineColour;
var radiusLineOpacity;
var radiusOpacity;
var radiusLineWidth;
var radiusQuality;

// NOTES - Long term the icon parameters should be dropped from here, as these will be
// rolled into the GoogleMarker class, somehow.
function LoadData(mapId, latitude, logitude, zoomlevel, xmldoc, usecontrolset, showMapType, showMapNavigator,
                  showMapScale, enableDragging, mapType, enableReset, rKeyhole, rSize, rColour, rOpacity, rLineColour, rLineOpacity, rLineWidth, rQuality) {

    keyhole = rKeyhole;
    radiusSize = rSize;
    radiusColour = rColour;
    radiusOpacity = rOpacity;
    radiusLineColour = rLineColour;
    radiusLineOpacity = rLineOpacity;
    radiusLineWidth = rLineWidth;
    radiusQuality = rQuality;

    if (GBrowserIsCompatible()) {
        map = new GMap2(document.getElementById(mapId));

        // Configure boolean display parameters and control sets.
        if (showMapType) {
            map.addControl(new GMapTypeControl());
        }
        if (showMapNavigator) {
            map.addControl(new GOverviewMapControl());
        }
        if (showMapScale) {
            map.addControl(new GScaleControl());
        }

        switch (usecontrolset) {
            case 'GLargeMapControl':
                map.addControl(new GLargeMapControl);
                break;
            case 'GSmallMapControl':
                map.addControl(new GSmallMapControl);
                break;
            case 'GSmallZoomControl':
                map.addControl(new GSmallZoomControl);
                break;
            default:
                break;
        }

        try {
            if (enableDragging) {
                map.enableDragging();
            }
            else {
                map.disableDragging();
            }
        }
        catch (e)
		{ }

        var bounds;

        // Process the markers collection.
        if (xmldoc != null && xmldoc != "") {
            xml = GXml.parse(xmldoc);
            var markers = xml.documentElement.getElementsByTagName("marker");
            for (var i = 0; i < markers.length; i++) {
                var point = new GLatLng(parseFloat(markers[i].getAttribute("lat")),
					parseFloat(markers[i].getAttribute("lng")));
                if (!bounds) {
                    bounds = new GLatLngBounds(point);
                }
                else {
                    bounds.extend(point);
                }
                var infoTabs;

                if (markers[i].getAttribute("tab1description") != null && markers[i].getAttribute("tab1description") != '') {
                    if (markers[i].getAttribute("tab2description") != null && markers[i].getAttribute("tab2description") != '') {
                        infoTabs = [new GInfoWindowTab(markers[i].getAttribute("tab1name"), markers[i].getAttribute("tab1description")),
							new GInfoWindowTab(markers[i].getAttribute("tab2name"), markers[i].getAttribute("tab2description"))];
                    }
                    else {
                        infoTabs = [new GInfoWindowTab(markers[i].getAttribute("tab1name"), markers[i].getAttribute("tab1description"))];
                    }

                    map.addOverlay(createMarker(markers[i].getAttribute("iconimage"), point, infoTabs));
                }
                else {
                    map.addOverlay(createMarker(markers[i].getAttribute("iconimage"), point, null));
                }
            }
        }
        else {
            xml = '';
        }

        // Center the map.
        var usedZoomLevel = map.getBoundsZoomLevel(bounds);

        if (usedZoomLevel > zoomlevel)
            usedZoomLevel = zoomlevel;

        map.setCenter(new GLatLng(latitude, logitude), usedZoomLevel);

        map.setMapType(mapType);

        if (radiusSize > 0) {
            DoRadius(radiusSize, keyhole);
        }

        if (enableReset) {
            var resetControl = new ResetMap(map.getCenter(), map.getZoom());

            var zoom_end = function() { addResetControl(); }
            var drag_end = function() { addResetControl(); }
            var move_end = function() { addResetControl(); }

            var addResetControl = function() { map.addControl(resetControl); }

            GEvent.addListener(map, "dragend", drag_end);
            GEvent.addListener(map, "zoomend", zoom_end);
            GEvent.addListener(map, "moveend", move_end);
        }

    }
}


function createMarker(iconimage, point, info) {
    // Create our "tiny" marker icon
    if (iconimage != null && iconimage != '') {
        var icon = new GIcon();
        icon.image = iconimage;
        icon.shadow = shadow;
        icon.iconSize = new GSize(12, 20);
        icon.shadowSize = new GSize(22, 20);
        icon.iconAnchor = new GPoint(6, 20);
        icon.infoWindowAnchor = new GPoint(5, 1);
        var marker = new GMarker(point, icon);
    }
    else {
        var marker = new GMarker(point);
    }
    if (info != null) {
        GEvent.addListener(marker, "click", function() {
            marker.openInfoWindowTabsHtml(info);
        }
		);
    }
    return marker;
}

////pan and zoom to fit  
var bounds = new GLatLngBounds();

//calling circle drawing function
function DoRadius(givenRad) {

    bounds = new GLatLngBounds();

    var centre = map.getCenter()

    //calculating km/degree  
    var latConv = centre.distanceFrom(new GLatLng(centre.lat() + 0.1, centre.lng())) / 100;
    var lngConv = centre.distanceFrom(new GLatLng(centre.lat(), centre.lng() + 0.1)) / 100;

    //Loop to make points on the circle
    var points = [];
    var step = parseInt(360 / radiusQuality) || 10;

    for (var i = 0; i <= 360; i += step) {
        var pint = new GLatLng(centre.lat() + (givenRad / latConv * Math.cos(i * Math.PI / 180)),
                               centre.lng() + (givenRad / lngConv * Math.sin(i * Math.PI / 180)));
        points.push(pint);
        bounds.extend(pint);
    }

    var poly;
    if (!keyhole) {
        poly = new GPolygon(points, radiusLineColour, radiusLineWidth, radiusLineOpacity, radiusColour, radiusOpacity);
    }
    else {
        var polylineEncoder = new PolylineEncoder();

        var radiusEncoded = polylineEncoder.dpEncode(points).encodedPoints;
        
        // we have to encode different strips of the map individually due to google maps being crazy.
        poly = new GPolygon.fromEncoded({
            polylines: [{     // Portion over uk
                points: "_qxeO__hgN~brl_@??~~po]_crl_@??__qo]",
                levels: "1"
            },
            { // Portion to the Right
                points: "_qxeO__hgN?_gjaR~brl_@??~fjaR_crl_@?",
                levels: "1"
            },
            { // Portion to the Left
                points: "_qxeO~~ggN?~fjaR~brl_@??_gjaR_crl_@?",
                levels: "1"
            },
            {   // Circle
                points: radiusEncoded,
                levels: "1"
            }],
            fill: true,
            color: radiusColour,
            opacity: radiusOpacity
        });
    }

    map.addOverlay(poly);

    map.panTo(bounds.getCenter());
    map.setZoom(map.getBoundsZoomLevel(bounds));
}

//------------------ GControls Section -------------------------------------------------------//


// ---------- ResetMap -------------- //
// Allows the map to be reset to its original position and zoom level
function ResetMap(pos, zoom) {
    this.position = pos;
    this.zoomLevel = zoom;
}

ResetMap.prototype = new GControl();

ResetMap.prototype.initialize = function(map) {
    var pos = this.position;
    var zoom = this.zoomLevel;
    var container = document.createElement("div");
    var zoomOutDiv = document.createElement("div");
    var control = this;
    this.setButtonStyle_(zoomOutDiv);
    container.appendChild(zoomOutDiv);
    zoomOutDiv.appendChild(document.createTextNode("Reset Map"));
    GEvent.addDomListener(zoomOutDiv, "click", function() { map.setCenter(pos, zoom); map.removeControl(control) });
    map.getContainer().appendChild(container);
    return container;
}

ResetMap.prototype.getDefaultPosition = function() {
    return new GControlPosition(G_ANCHOR_BOTTOM_RIGHT, new GSize(7, 14));
}

ResetMap.prototype.setButtonStyle_ = function(button) {
    button.style.color = "#000";
    button.style.backgroundColor = "#fff";
    button.style.font = "small Arial";
    button.style.border = "1px solid black";
    button.style.padding = "2px";
    button.style.marginBottom = "3px";
    button.style.textAlign = "center";
    button.style.width = "6em";
    button.style.cursor = "pointer";
}
if(typeof(Sys)!=='undefined')Sys.Application.notifyScriptLoaded();