
map = null;
id = null;
name = null;
description = [];
type = null;
hq = null
start = null;
finish = null;
waypoints = [];
xmlDoc = null;
directions = null;
startMarker = null;
finishMarker = null;
hqMarker = null;
waypointMarker = [];
courseSteps = [];
elevationSteps = [];

function setup() {
    map = new GMap2(document.getElementById("map_canvas"));
    map.setCenter(new GLatLng(53.82, -0.40), 11);
    map.addControl(new GLargeMapControl3D);
    map.addControl(new GScaleControl);
    map.addControl(new GMenuMapTypeControl);    
    xmlDoc = loadXMLDoc("Courses.xml")
    directions = new GDirections();
    GEvent.addListener(directions, "load", onDirectionsLoad);
    GEvent.addListener(directions, "error", onDirectionsError);
}

function tearDown() {
    GUnload()
}

function selectCourse(courseID) {
    if (loadFromXML(courseID)) {
        directions.clear();
        directions.loadFromWaypoints(getPoints(), {
            getPolyline:true
        });
    }
}

function centreMap() {
    var bounds = directions.getBounds();
    var zoom = map.getBoundsZoomLevel(bounds);

    map.setCenter(bounds.getCenter(), zoom);
}

function onDirectionsLoad() {
    map.clearOverlays();
    centreMap();
    generateMarkers();
    displayOverlays();

}

function onDirectionsError() {
    alert("Error loading course.")
}

function displayOverlays() {
    map.addOverlay(directions.getPolyline());
    map.addOverlay(startMarker);
    map.addOverlay(finishMarker);
    for (marker in waypointMarker) {
        map.addOverlay(waypointMarker[marker]);
    }
    var description = getDescriptionAsHTML();
    if (description == null) {
        description = "";
    }
    document.getElementById("description").innerHTML = description;
}

function generateMarkers() {

    startMarker = null;
    finishMarker = null;
    hqMarker = null;
    waypointMarker = [];

    var startIcon = initialiseIcon("Resources/start.png", 32, 37);
    startMarker = new GMarker(start, {
        icon:startIcon
    });

    var finishIcon = initialiseIcon("Resources/finish.png", 32, 37);
    finishMarker = new GMarker(finish, {
        icon:finishIcon
    });

    var hqIcon = initialiseIcon("Resources/hq.png", 32, 37);
    hqMarker = new GMarker(hq, {
        icon:hqIcon
    });

    var wpIcons = [];
    for (i = 0; i < waypoints.length; i++) {
        var path = "Resources/red" + (i + 1) + ".png"
        wpIcons[i] = initialiseIcon(path, 27, 27)
        waypointMarker[i] = new GMarker(waypoints[i], {
            icon:wpIcons[i]
        });
    }
}

function stepsToString() {
    var result = "";
    for (step in courseSteps) {
        result += courseSteps[step].lat + "<br />"
    }
    return result;
}

function initialiseIcon(image, width, height) {

    icon = new GIcon();
    icon.image = image;
    icon.iconSize = new GSize(width, height);
    icon.iconAnchor = new GPoint(width / 2, height);
    icon.infoWindowAnchor = new GPoint(width / 2, 1);

    return icon;
}

function loadFromXML(courseID) {
    
    id = null;
    name = null;
    description = [];
    type = null;
    hq = null
    start = null;
    finish = null;
    waypoints = [];

    x = xmlDoc.getElementsByTagName("course");
    // check the file to see if it contains the required course.
    for (i = 0; i < x.length; i++) {
        var xmlcourse = x[i]
        if (xmlcourse.getAttribute("id") == courseID) {
            //retrieve the course ID
            id = xmlcourse.getAttribute("id");

            for (var i = 0; i < xmlcourse.childNodes.length; i++) {
                element = xmlcourse.childNodes[i];
                switch (element.nodeName) {
                    case "name":
                        name = element.childNodes[0].nodeValue;
                        break;
                    case "description":
                        var descCounter = 0;
                        for (j = 0; j < element.childNodes.length; j++) {
                            if (element.childNodes[j].nodeName == "paragraph") {
                                description[descCounter] = element.childNodes[j].childNodes[0].nodeValue;
                                descCounter++;
                            }
                        }
                        break;
                    case "type":
                        type = element.childNodes[0].nodeValue;
                        break;
                    case "headquarters":
                        var lat, lng
                        lat = 0;
                        lng = 0;
                        for (j = 0; j < element.childNodes.length; j++) {
                            if (element.childNodes[j].nodeName == "lat") {
                                lat = element.childNodes[j].childNodes[0].nodeValue;
                            } else if (element.childNodes[j].nodeName == "long") {
                                lng = element.childNodes[j].childNodes[0].nodeValue;
                            }
                        }
                        hq = new GLatLng(lat, lng);
                        break;
                    case "start":
                        lat = 0;
                        lng = 0;
                        for (j = 0; j < element.childNodes.length; j++) {
                            if (element.childNodes[j].nodeName == "lat") {
                                lat = element.childNodes[j].childNodes[0].nodeValue;
                            } else if (element.childNodes[j].nodeName == "long") {
                                lng = element.childNodes[j].childNodes[0].nodeValue;
                            }
                        }
                        start = new GLatLng(lat, lng);
                        break;
                    case "finish":
                        lat = 0;
                        lng = 0;
                        for (j = 0; j < element.childNodes.length; j++) {
                            if (element.childNodes[j].nodeName == "lat") {
                                lat = element.childNodes[j].childNodes[0].nodeValue;
                            } else if (element.childNodes[j].nodeName == "long") {
                                lng = element.childNodes[j].childNodes[0].nodeValue;
                            }
                        }
                        finish = new GLatLng(lat, lng);
                        break;
                    case "points":
                        var wpCounter = 0;
                        for (j = 0; j < element.childNodes.length; j++) {
                            if (element.childNodes[j].nodeName == "point") {
                                pointElement = element.childNodes[j];
                                lat = 0;
                                lng = 0;
                                for (k = 0; k < pointElement.childNodes.length; k++) {
                                    if (pointElement.childNodes[k].nodeName == "lat") {
                                        lat = pointElement.childNodes[k].childNodes[0].nodeValue;
                                    } else if (pointElement.childNodes[k].nodeName == "long") {
                                        lng = pointElement.childNodes[k].childNodes[0].nodeValue;
                                    }
                                }
                                waypoints[wpCounter] = new GLatLng(lat, lng);
                                wpCounter++;
                            }
                        }
                        break;
                    default:
                        if (element.nodeType == 1) {
                            alert("Error parsing XML: unexpected element.\n\nNode Type: " + element.nodeType + ";\nNode Name: " + element.nodeName + ";\nNode Value: " + element.childNodes[0].nodeValue + "." )
                        }
                        break;
                }
            }
            return true;
        }
    }
    return false
}

function getPoints() {
    var tempPoints = [];
    var index = 1;
    tempPoints[0] = start.lat() + ", " + start.lng();
    for (point in waypoints) {
        var aPoint = waypoints[point];
        tempPoints[index] = aPoint.lat() + ", " + aPoint.lng();
        index++
    }
    if (type == "Circuit") {
        tempPoints[index] = start.lat() + ", " + start.lng();
    } else {
        tempPoints[index] = finish.lat() + ", " + finish.lng();
    }
    return tempPoints;
}

function getDescriptionAsHTML() {
    var tempDesc = "";
    for (i = 0; i < description.length; i++) {
        tempDesc += "<p>" + description[i] + "</p>";
    }
    return tempDesc;
}

function toString() {
    return id;
}



function loadXMLDoc(docName)
{
    var xhttp;
    //    if (window.XMLHttpRequest)
    //    {
    //        xmlDoc = new window.XMLHttpRequest();
    //        xmlDoc.open("GET", docName, false);
    //        xmlDoc.send("");
    //        return xmlDoc.responseXML;
    //    }
    //    // IE 5 and IE 6
    //    else if (ActiveXObject("Microsoft.XMLHTTP"))
    //    {
    //        xmlDoc = new ActiveXObject("Microsoft.XMLHTTP");
    //        xmlDoc.async=false;
    //        xmlDoc.load(dname);
    //        return xmlDoc;
    //    }
    //
    if (window.XMLHttpRequest)
    {
        xhttp=new XMLHttpRequest();
    }
    else // Internet Explorer 5/6
    {
        xhttp=new ActiveXObject("Microsoft.XMLHTTP");
    }
    xhttp.open("GET",docName,false);
    xhttp.send("");
    var xmlDoc=xhttp.responseXML;
    return xmlDoc;

//    alert("Error loading document");
//    return null;
}