﻿var map;
var mapDivId;
var segments = [];
var mapPixelWidth = null;
var mapPixelHeight = null;
var routeStartPolygon = null;
var arrowColor = '#FF0000';
var arrowTransparency = 1.0;

function initMap() {
    if (GBrowserIsCompatible()) {
        if (mapPixelWidth && mapPixelHeight) {
            map = new GMap2(document.getElementById('MapDiv'), {size: new GSize(mapPixelWidth, mapPixelHeight)});
        } else {
            map = new GMap2(document.getElementById('MapDiv'));
        }
        map.addMapType(G_PHYSICAL_MAP);
        
		if (window.location.search)
		{
			var params = window.location.search.split('&');
			for (i = 0; i < params.length; i++)
			{
				var keyPair = params[i].split('=');
				if (keyPair[0] == 'type')
				{
					switch (keyPair[1])
					{
						case '1':
							map.setMapType(G_NORMAL_MAP);
							break;
						case '2':
							map.setMapType(G_SATELLITE_MAP);
							break;
						case '3':
							map.setMapType(G_HYBRID_MAP);
							break;
						case '4':
							map.setMapType(G_PHYSICAL_MAP);
							break;
					
					}
					map.addControl(new GMapTypeControl());
				}
			}
		}
		
		map.setCenter(new GLatLng(54.6484, -4.6582), 4);
        map.addControl(new GLargeMapControl());
		var pos = new GControlPosition(G_ANCHOR_TOP_LEFT, new GSize(8,350));
		map.addControl(new GScaleControl(), pos);
        var polyLine = dataBind();
        if (polyLine) {
            map.addOverlay(polyLine);
            var lineBounds = polyLine.getBounds();
            map.setZoom(map.getBoundsZoomLevel(lineBounds));
            map.setCenter(lineBounds.getCenter());
            renderArrow(map, polyLine.getVertex(0), polyLine.getVertex(1));
            GEvent.addListener(map, "zoomend", function() {
                renderArrow(map, polyLine.getVertex(0), polyLine.getVertex(1));
            });
        }
        //recreateSegments(map);
        
    }
}

function renderArrow(map, point1, point2) {
    if (routeStartPolygon) {
        map.removeOverlay(routeStartPolygon);
    }
    
    var point1DivLocation = map.fromLatLngToDivPixel(point1);
    var point2DivLocation = map.fromLatLngToDivPixel(point2);
    
    var deltaXSquared = (point2DivLocation.x - point1DivLocation.x) * (point2DivLocation.x - point1DivLocation.x);
    var deltaYSquared = (point2DivLocation.y - point1DivLocation.y) * (point2DivLocation.y - point1DivLocation.y);
   
    var lineLength = Math.min(10, Math.sqrt(deltaXSquared + deltaYSquared));
    
    var legLineSegment = new LineSegment({
        startPoint: point1DivLocation,
        endPoint: point2DivLocation
    });
    
    var leftLineSegment = new LineSegment({
        startPoint: point1DivLocation,
        angle: (legLineSegment.angle - 90) - 90,
        length: lineLength
    });
    
    var rightLineSegment = new LineSegment({
        startPoint: point1DivLocation,
        angle: (legLineSegment.angle - 90) + 90,
        length: lineLength
    });
    
    var finalLineSegment = new LineSegment({
        startPoint: point1DivLocation,
        angle: legLineSegment.angle - 90,
        length: lineLength * 2
    });
    
    var finalFinalLineSegment = new LineSegment({
        startPoint: point1DivLocation,
        angle: legLineSegment.angle - 90,
        length: lineLength / 2
    });
    
    routeStartPolygon = new GPolygon([
        map.fromDivPixelToLatLng(leftLineSegment.endPoint),
        map.fromDivPixelToLatLng(finalLineSegment.endPoint),
        map.fromDivPixelToLatLng(rightLineSegment.endPoint),
        map.fromDivPixelToLatLng(finalFinalLineSegment.endPoint),
    ], arrowColor, 0, arrowTransparency, arrowColor, arrowTransparency);
    
    map.addOverlay(routeStartPolygon);
    
}

function addSegment(start, end, description) {
    var marker = new GMarker(end);
    
    var localIcon = new GIcon(G_DEFAULT_ICON);
    
    var marker = new GMarker(end, {icon:localIcon});
    GEvent.addListener(marker, "click", function() {marker.openInfoWindowHtml(description);});
    map.addOverlay(marker);
    
    map.addOverlay(new GPolyline([
        start,
        end
    ], '#FF0000', 10));
    
    segments.push({startLatLng: start, endLatLng: end, polyLines: []});
}

function recreateSegments(map) {
    for (i = 0; i < segments.length; i++) {
        // add our tick
        
        if (segments[i].polyLines) {
            for (j = 0; j < segments[i].polyLines.length; j++) {
                map.removeOverlay(segments[i].polyLines[j]);
            }
        }
        
        var startDivPosition = map.fromLatLngToDivPixel(segments[i].startLatLng);
        var endPosition = map.fromLatLngToDivPixel(segments[i].endLatLng);
        
        // we want to add our tick half way across the leg, find our point halfway along the vector
        
        var deltax = endPosition.x - startDivPosition.x;
        var deltay = endPosition.y - startDivPosition.y;
        
        var halfWayPosition = new GPoint(startDivPosition.x + (deltax / 2), startDivPosition.y + (deltay / 2));
        
        var legLineSegment = new LineSegment({
            startPoint: startDivPosition, 
            endPoint: endPosition
        });
        var tickOneSegment = new LineSegment({
            startPoint: halfWayPosition, 
            angle: legLineSegment.angle + 90 + 30,
            length: 10
        });
        var tickTwoSegment = new LineSegment({
            startPoint: halfWayPosition, 
            angle: legLineSegment.angle + 90 - 30,
            length: 10
        });
        
        var tickOnePolyLine = tickOneSegment.createPolyLine('#000000', 10);
        map.addOverlay(tickOnePolyLine);
        segments[i].polyLines.push(tickOnePolyLine);
        
        var tickTowPolyLine = tickTwoSegment.createPolyLine('#000000', 10);
        map.addOverlay(tickTowPolyLine);
        segments[i].polyLines.push(tickTowPolyLine);
    }
}


// class line segment
// simply encapsulates some simple trig
function LineSegment(config) {
    this.startPoint = config.startPoint;
    if (config.endPoint) {
        this.endPoint = config.endPoint;
        this.angle = getLineAngle(this.startPoint, this.endPoint);
    } else {
        this.endPoint = new GPoint(
            this.startPoint.x + (config.length * Math.cos(degreesToRadians(config.angle))), 
            this.startPoint.y + (config.length * Math.sin(degreesToRadians(config.angle)))
        );
        this.angle = config.angle % 360;
    }
}

LineSegment.prototype.createPolyLine = function(color, transparency) {
    return new GPolyline([
        map.fromDivPixelToLatLng(this.startPoint),
        map.fromDivPixelToLatLng(this.endPoint)
    ], color, transparency);
}

function degreesToRadians(degrees) {
    return degrees * (Math.PI / 180);
}

function radiansToDegreees(radians) {
    return radians * (180 / Math.PI);
}

function getLineAngle(startPoint, endPoint) {
    var x = endPoint.x - startPoint.x;
    var y = startPoint.y - endPoint.y;
    if (Math.abs(y) > Math.abs(x)) {
        if (y > 0) {
            return radiansToDegreees(Math.atan(x / y));
        } else {
            return radiansToDegreees(Math.atan(x / y) + Math.PI);
        }
    } else {
        if (x > 0) {
            return radiansToDegreees(0.5 * Math.PI - Math.atan(y / x));
        } else {
            return radiansToDegreees(-0.5 * Math.PI - Math.atan(y / x));
        }
    }
}
