/* extra functionality added to specify different markers */

var IdahoGoogleMap = {};

IdahoGoogleMap.Base = {

    // Properties
    base: this,
    markers: [],
    map: null,
    currentlySelected: 0,
    ddlDistance: 25,

    // Get all hidden field values
    userLat: null,
    userLng: null,
    mapXmlSource: null,
    mapZoomLevel: null,
    markerType: null,
    groupID: null,
    isProfilePage: null,
    isMidPointPage: null,

    // Collect highest LAT/LNG and lowest LAT/LNG
    highLat: null,
    highLng: null,
    lowLat: null,
    lowLng: null,

    goAhead: true,

    // Methods

    // -----------------------------------------------------------------------------------------------------------------------------------------------------

    EndMap: function() {
        GUnload();
    },

    // -----------------------------------------------------------------------------------------------------------------------------------------------------

    Marker: function(id, title, organisation, lat, lng, userType, facilitator, membership, personcategory, author, iconPath, ltc, qr, summary) {

        this.id = id;
        this.title = title;
        this.organisation = organisation;
        this.lat = parseFloat(lat);
        this.lng = parseFloat(lng);
        this.userType = parseInt(userType);
        this.facilitator = parseInt(facilitator);
        this.membership = parseInt(membership);
        this.personcategory = personcategory;
        this.author = author;
        this.iconPath = iconPath;
        this.ltc = ltc;
        this.qr = qr;
        this.summary = summary;
    },

    // -----------------------------------------------------------------------------------------------------------------------------------------------------

    getMarkers: function(src) {

        var bounds = this.map.getBounds();
        var southWest = bounds.getSouthWest();
        var northEast = bounds.getNorthEast();

        var dataRequest = GXmlHttp.create();
        dataRequest.open("GET", src, true);

        // WARNING - 'this' keyword takes on another meaning - refers to dataRequest object
        dataRequest.onreadystatechange = function() {
            if (dataRequest.readyState == 4) {
                IdahoGoogleMap.Results.Run(dataRequest.responseXML);
            }
        };

        dataRequest.send(null);

    },

    // -----------------------------------------------------------------------------------------------------------------------------------------------------

    InitMap: function() {
        if (GBrowserIsCompatible()) {
            // Ok this browser supports google maps

            // Grab all hidden field values

            this.userLat = parseFloat(document.getElementById("userLat").value);
            this.userLng = parseFloat(document.getElementById("userLng").value);

            this.mapXmlSource = document.getElementById("mapXmlSource").value;
            this.mapZoomLevel = parseInt(document.getElementById("mapZoomLevel").value);
            this.markerType = document.getElementById("markerType").value;
            this.groupID = document.getElementById("groupID").value;
            this.isProfilePage = document.getElementById("isProfilePage").value;
            this.isMidPointPage = document.getElementById("isMidPointPage").value;
            // Now the google map specifics
            this.map = new GMap2(document.getElementById("map"));
            //alert('Test');
            this.map.setCenter(new GLatLng(this.userLat, this.userLng), this.mapZoomLevel);
            this.map.addControl(new GMapTypeControl);
            this.map.addControl(new GLargeMapControl);
            this.map.setMapType(G_NORMAL_MAP); // sets the map type

            this.getMarkers(this.mapXmlSource);

            this.ddlDistance = document.getElementById("ddlDistance"); // =TODO



        }
    }

};

IdahoGoogleMap.Results = {

    Run: function(xmlDoc) {
        var markers = IdahoGoogleMap.Base.markers;

        var m = xmlDoc.documentElement.getElementsByTagName("marker");

        if (m) {
            for (var i = 0; i < m.length; i++) {

                var v = new IdahoGoogleMap.Base.Marker(
					this.childNodeById(m[i].childNodes, "id", 0, false),
					this.childNodeById(m[i].childNodes, "title", "Not Found", false),
					this.childNodeById(m[i].childNodes, "organisation", "", false),
					this.childNodeById(m[i].childNodes, "lat", 0, false),
					this.childNodeById(m[i].childNodes, "lng", 0, false),
					this.childNodeById(m[i].childNodes, "userType", 0, false),
					this.childNodeById(m[i].childNodes, "facilitator", 0, false),
					this.childNodeById(m[i].childNodes, "membership", 0, false),
				    this.childNodeById(m[i].childNodes, "personcategory", "", false),
				    this.childNodeById(m[i].childNodes, "author", "", false),
				    this.childNodeById(m[i].childNodes, "icon", "", false),
				    this.childNodeById(m[i].childNodes, "ltc", "", false),
				    this.childNodeById(m[i].childNodes, "qr", "", false),
				    this.childNodeById(m[i].childNodes, "summary", "", false)
				);

                markers.push(v);
            }
        }

        if (markers.length) {
            //divert to custom rendering for profile map	
            if (IdahoGoogleMap.Base.isProfilePage == 'True') {
                this.renderProfileMarkers(markers);
            }
            else if (IdahoGoogleMap.Base.isMidPointPage == 'True') {
                this.renderMidPointMarkers(markers);
            }
            else {
                this.renderMarkers(markers);
            }
        }
    },

    // -----------------------------------------------------------------------------------------------------------------------------------------------------

    childNodeById: function(nodeList, ID, defaultValue, returnXML) {
        for (j = 0; j < nodeList.length; j++) {
            if (nodeList[j].nodeType == 1 && nodeList[j].nodeName == ID) {
                if (returnXML) {
                    // alert ( nodeList[ j ].firstChild.nodeValue );
                }
                else {
                    if (nodeList[j].firstChild) {
                        return nodeList[j].firstChild.nodeValue;
                    }
                    else {
                        return defaultValue;
                    }
                }
            }
        }
        return defaultValue;
    },

    // -----------------------------------------------------------------------------------------------------------------------------------------------------

    renderMarkers: function(markersCollection) {
        // markersCollection, is our markers array made up of marker objects
        var userLatLng = new GLatLng(IdahoGoogleMap.Base.userLat, IdahoGoogleMap.Base.userLng); // =TODO, is this used alot if so create this in init

        // Always handy to call this, not really needed on this google map but will leave in anyways
        //IdahoGoogleMap.Base.map.clearOverlays();



        for (var i = 0; i < markersCollection.length; i++) {
            // At this point we can start collecting/examing the high/low lat/lng's. We do this so we can show all markers and find the correct zoomLevel

            // These four only happen once and are set to the first markers lat/lngs. 
            if (!IdahoGoogleMap.Base.highLat) { IdahoGoogleMap.Base.highLat = markersCollection[i].lat; }
            if (!IdahoGoogleMap.Base.lowLat) { IdahoGoogleMap.Base.lowLat = markersCollection[i].lat; }
            if (!IdahoGoogleMap.Base.highLng) { IdahoGoogleMap.Base.highLng = markersCollection[i].lng; }
            if (!IdahoGoogleMap.Base.lowLng) { IdahoGoogleMap.Base.lowLng = markersCollection[i].lng; }
            // - 

            // We now check current marker lat/lng's against our stored values
            if (markersCollection[i].lat > IdahoGoogleMap.Base.highLat) {
                IdahoGoogleMap.Base.highLat = markersCollection[i].lat;
            }

            if (markersCollection[i].lat < IdahoGoogleMap.Base.lowLat) {
                IdahoGoogleMap.Base.lowLat = markersCollection[i].lat;
            }

            if (markersCollection[i].lng > IdahoGoogleMap.Base.highLng) {
                IdahoGoogleMap.Base.highLng = markersCollection[i].lng;
            }

            if (markersCollection[i].lng < IdahoGoogleMap.Base.lowLng) {
                IdahoGoogleMap.Base.lowLng = markersCollection[i].lng;
            }
            // -

            var markerLatLng = new GLatLng(markersCollection[i].lat, markersCollection[i].lng);

            markersCollection[i].distanceFrom = Math.round((userLatLng.distanceFrom(markerLatLng) / 1609.347) * 100) / 100;

            var marker = this.createMarker(i, markerLatLng);
            markersCollection[i].gMarker = marker;
            IdahoGoogleMap.Base.map.addOverlay(marker);

        }

        //alert("WHAT WE HAVE \n HIGH LAT: " + highLat + "\n LOW LAT: " + lowLat + "\n HIGH LNG: " + highLng + "\n LOW LNG: "+ lowLng);

        // Now we need to attach events onto the divs in the results
        this.attachResultClickEvents(IdahoGoogleMap.Base.markers);

        // Now we have all our results we need to make sure they are all displayed in the visible area of the map.

        // 1st, grab the current bounds of the map
        var ne = new GLatLng(IdahoGoogleMap.Base.highLat, IdahoGoogleMap.Base.highLng);
        var sw = new GLatLng(IdahoGoogleMap.Base.lowLat, IdahoGoogleMap.Base.lowLng);

        // 2nd, load this into a google object GLatLngBounds
        var bounds = new GLatLngBounds(sw, ne);

        // 3rd, use the	map.getBoundsZoomLevel to return an integer value to set the zoomLevel for the map
        var zoomLevel = IdahoGoogleMap.Base.map.getBoundsZoomLevel(bounds);

        // 4th, check to make sure we aren't going too close. We need to do this because with 1 result it zooms in ridiculously close.
        if (zoomLevel > 16) {
            zoomLevel = 16;
        }

        // Finally set the map in position
        IdahoGoogleMap.Base.map.setCenter(bounds.getCenter(), zoomLevel);
    },

    // -----------------------------------------------------------------------------------------------------------------------------------------------------

    renderMidPointMarkers: function(markersCollection) {
        // markersCollection, is our markers array made up of marker objects
        var userLatLng = new GLatLng(IdahoGoogleMap.Base.userLat, IdahoGoogleMap.Base.userLng); // =TODO, is this used alot if so create this in init

        // Always handy to call this, not really needed on this google map but will leave in anyways
        //IdahoGoogleMap.Base.map.clearOverlays();



        for (var i = 0; i < markersCollection.length; i++) {
            // At this point we can start collecting/examing the high/low lat/lng's. We do this so we can show all markers and find the correct zoomLevel

            // These four only happen once and are set to the first markers lat/lngs. 
            if (!IdahoGoogleMap.Base.highLat) { IdahoGoogleMap.Base.highLat = markersCollection[i].lat; }
            if (!IdahoGoogleMap.Base.lowLat) { IdahoGoogleMap.Base.lowLat = markersCollection[i].lat; }
            if (!IdahoGoogleMap.Base.highLng) { IdahoGoogleMap.Base.highLng = markersCollection[i].lng; }
            if (!IdahoGoogleMap.Base.lowLng) { IdahoGoogleMap.Base.lowLng = markersCollection[i].lng; }
            // - 

            // We now check current marker lat/lng's against our stored values
            if (markersCollection[i].lat > IdahoGoogleMap.Base.highLat) {
                IdahoGoogleMap.Base.highLat = markersCollection[i].lat;
            }

            if (markersCollection[i].lat < IdahoGoogleMap.Base.lowLat) {
                IdahoGoogleMap.Base.lowLat = markersCollection[i].lat;
            }

            if (markersCollection[i].lng > IdahoGoogleMap.Base.highLng) {
                IdahoGoogleMap.Base.highLng = markersCollection[i].lng;
            }

            if (markersCollection[i].lng < IdahoGoogleMap.Base.lowLng) {
                IdahoGoogleMap.Base.lowLng = markersCollection[i].lng;
            }
            // -

            var markerLatLng = new GLatLng(markersCollection[i].lat, markersCollection[i].lng);

            markersCollection[i].distanceFrom = Math.round((userLatLng.distanceFrom(markerLatLng) / 1609.347) * 100) / 100;

            var marker = this.createMidPointMarker(i, markerLatLng);
            markersCollection[i].gMarker = marker;
            IdahoGoogleMap.Base.map.addOverlay(marker);

        }

        //alert("WHAT WE HAVE \n HIGH LAT: " + highLat + "\n LOW LAT: " + lowLat + "\n HIGH LNG: " + highLng + "\n LOW LNG: "+ lowLng);

        // Now we need to attach events onto the divs in the results
        this.attachResultClickEvents(IdahoGoogleMap.Base.markers);

        // Now we have all our results we need to make sure they are all displayed in the visible area of the map.

        // 1st, grab the current bounds of the map
        var ne = new GLatLng(IdahoGoogleMap.Base.highLat, IdahoGoogleMap.Base.highLng);
        var sw = new GLatLng(IdahoGoogleMap.Base.lowLat, IdahoGoogleMap.Base.lowLng);

        // 2nd, load this into a google object GLatLngBounds
        var bounds = new GLatLngBounds(sw, ne);

        // 3rd, use the	map.getBoundsZoomLevel to return an integer value to set the zoomLevel for the map
        var zoomLevel = IdahoGoogleMap.Base.map.getBoundsZoomLevel(bounds);

        // 4th, check to make sure we aren't going too close. We need to do this because with 1 result it zooms in ridiculously close.
        if (zoomLevel > 16) {
            zoomLevel = 16;
        }

        // Finally set the map in position
        IdahoGoogleMap.Base.map.setCenter(bounds.getCenter(), zoomLevel);
    },

    // -----------------------------------------------------------------------------------------------------------------------------------------------------

    renderProfileMarkers: function(markersCollection) {
        // markersCollection, is our markers array made up of marker objects
        var userLatLng = new GLatLng(IdahoGoogleMap.Base.userLat, IdahoGoogleMap.Base.userLng); // =TODO, is this used alot if so create this in init

        // Always handy to call this, not really needed on this google map but will leave in anyways
        //IdahoGoogleMap.Base.map.clearOverlays();



        for (var i = 0; i < markersCollection.length; i++) {
            // At this point we can start collecting/examing the high/low lat/lng's. We do this so we can show all markers and find the correct zoomLevel

            // These four only happen once and are set to the first markers lat/lngs. 
            if (!IdahoGoogleMap.Base.highLat) { IdahoGoogleMap.Base.highLat = markersCollection[i].lat; }
            if (!IdahoGoogleMap.Base.lowLat) { IdahoGoogleMap.Base.lowLat = markersCollection[i].lat; }
            if (!IdahoGoogleMap.Base.highLng) { IdahoGoogleMap.Base.highLng = markersCollection[i].lng; }
            if (!IdahoGoogleMap.Base.lowLng) { IdahoGoogleMap.Base.lowLng = markersCollection[i].lng; }
            // - 

            // We now check current marker lat/lng's against our stored values
            if (markersCollection[i].lat > IdahoGoogleMap.Base.highLat) {
                IdahoGoogleMap.Base.highLat = markersCollection[i].lat;
            }

            if (markersCollection[i].lat < IdahoGoogleMap.Base.lowLat) {
                IdahoGoogleMap.Base.lowLat = markersCollection[i].lat;
            }

            if (markersCollection[i].lng > IdahoGoogleMap.Base.highLng) {
                IdahoGoogleMap.Base.highLng = markersCollection[i].lng;
            }

            if (markersCollection[i].lng < IdahoGoogleMap.Base.lowLng) {
                IdahoGoogleMap.Base.lowLng = markersCollection[i].lng;
            }
            // -

            var markerLatLng = new GLatLng(markersCollection[i].lat, markersCollection[i].lng);

            markersCollection[i].distanceFrom = Math.round((userLatLng.distanceFrom(markerLatLng) / 1609.347) * 100) / 100;

            var marker = this.createProfileMarker(i, markerLatLng);
            markersCollection[i].gMarker = marker;
            IdahoGoogleMap.Base.map.addOverlay(marker);

        }

        //alert("WHAT WE HAVE \n HIGH LAT: " + highLat + "\n LOW LAT: " + lowLat + "\n HIGH LNG: " + highLng + "\n LOW LNG: "+ lowLng);

        // Now we need to attach events onto the divs in the results
        //this.attachResultClickEvents ( IdahoGoogleMap.Base.markers );

        // Now we have all our results we need to make sure they are all displayed in the visible area of the map.

        // 1st, grab the current bounds of the map
        var ne = new GLatLng(IdahoGoogleMap.Base.highLat, IdahoGoogleMap.Base.highLng);
        var sw = new GLatLng(IdahoGoogleMap.Base.lowLat, IdahoGoogleMap.Base.lowLng);

        // 2nd, load this into a google object GLatLngBounds
        var bounds = new GLatLngBounds(sw, ne);

        // 3rd, use the	map.getBoundsZoomLevel to return an integer value to set the zoomLevel for the map
        var zoomLevel = IdahoGoogleMap.Base.map.getBoundsZoomLevel(bounds);

        // 4th, check to make sure we aren't going too close. We need to do this because with 1 result it zooms in ridiculously close.
        if (zoomLevel > 16) {
            zoomLevel = 16;
        }

        // Finally set the map in position
        IdahoGoogleMap.Base.map.setCenter(bounds.getCenter(), zoomLevel);
    },

    // -----------------------------------------------------------------------------------------------------------------------------------------------------
    createMarker: function(index, latlng) {
        var icon = new GIcon();

        switch (index) {
            case 0: icon.image = "/images/mapfiles/iconA.png"; break;
            case 1: icon.image = "/images/mapfiles/iconB.png"; break;
            case 2: icon.image = "/images/mapfiles/iconC.png"; break;
            case 3: icon.image = "/images/mapfiles/iconD.png"; break;
            case 4: icon.image = "/images/mapfiles/iconE.png"; break;
            case 5: icon.image = "/images/mapfiles/iconF.png"; break;
            case 6: icon.image = "/images/mapfiles/iconG.png"; break;
            case 7: icon.image = "/images/mapfiles/iconH.png"; break;
            case 8: icon.image = "/images/mapfiles/iconI.png"; break;
            case 9: icon.image = "/images/mapfiles/iconJ.png"; break;
        }

        //icon.shadow = "http://labs.google.com/ridefinder/images/mm_20_shadow.png";
        icon.iconSize = new GSize(20, 34);
        //icon.shadowSize = new GSize( 22, 20 );
        icon.iconAnchor = new GPoint(6, 20); // =TODO Find out more about these two (below)
        icon.infoWindowAnchor = new GPoint(5, 1);

        var m = new GMarker(latlng, icon);

        var options = {

            onCloseFn: function() {
                // if window is open currentlySelected exists - clear colour and 'unselect'
                if (IdahoGoogleMap.Base.goAhead) {
                    IdahoGoogleMap.Base.currentlySelected.style.backgroundColor = "";
                    IdahoGoogleMap.Results.changeLetterImageOff(IdahoGoogleMap.Base.currentlySelected);
                    IdahoGoogleMap.Base.currentlySelected = null;
                }
                else {
                    IdahoGoogleMap.Base.goAhead = true;
                }
            }

        };

        GEvent.addListener(m, "click", function() {
            IdahoGoogleMap.Base.map.openInfoWindowHtml(latlng,
															IdahoGoogleMap.Results.renderMarker(index, latlng.lat(), latlng.lng()),
															options
														);

            IdahoGoogleMap.Results.selectedItem("result" + index);
        });

        return m;
    },

    // -----------------------------------------------------------------------------------------------------------------------------------------------------

    createMidPointMarker: function(index, latlng) {
        var icon = new GIcon();

        switch (index) {
            case 0: icon.image = "/images/mapfiles/iconA.png"; break;
            case 1: icon.image = "/images/mapfiles/iconB.png"; break;
            case 2: icon.image = "/images/mapfiles/iconC.png"; break;
            case 3: icon.image = "/images/mapfiles/iconD.png"; break;
            case 4: icon.image = "/images/mapfiles/iconE.png"; break;
            case 5: icon.image = "/images/mapfiles/iconF.png"; break;
            case 6: icon.image = "/images/mapfiles/iconG.png"; break;
            case 7: icon.image = "/images/mapfiles/iconH.png"; break;
            case 8: icon.image = "/images/mapfiles/iconI.png"; break;
            case 9: icon.image = "/images/mapfiles/iconJ.png"; break;
        }

        //icon.shadow = "http://labs.google.com/ridefinder/images/mm_20_shadow.png";
        icon.iconSize = new GSize(20, 34);
        //icon.shadowSize = new GSize( 22, 20 );
        icon.iconAnchor = new GPoint(6, 20); // =TODO Find out more about these two (below)
        icon.infoWindowAnchor = new GPoint(5, 1);

        var m = new GMarker(latlng, icon);

        var options = {

            onCloseFn: function() {
                // if window is open currentlySelected exists - clear colour and 'unselect'
                if (IdahoGoogleMap.Base.goAhead) {
                    IdahoGoogleMap.Base.currentlySelected.style.backgroundColor = "";
                    IdahoGoogleMap.Results.changeLetterImageOff(IdahoGoogleMap.Base.currentlySelected);
                    IdahoGoogleMap.Base.currentlySelected = null;
                }
                else {
                    IdahoGoogleMap.Base.goAhead = true;
                }
            }

        };

        GEvent.addListener(m, "click", function() {
            IdahoGoogleMap.Base.map.openInfoWindowHtml(latlng,
															IdahoGoogleMap.Results.renderMidPointMarker(index, latlng.lat(), latlng.lng()),
															options
														);

            IdahoGoogleMap.Results.selectedItem("result" + index);
        });

        return m;
    },

    // -----------------------------------------------------------------------------------------------------------------------------------------------------

    createProfileMarker: function(index, latlng) {
        var icon = new GIcon();

        switch (index) {
            case 0: icon.image = "/images/mapfiles/icon_red.png"; break;
            case 1: icon.image = "/images/mapfiles/icon_blue.png"; break;
        }

        //icon.shadow = "http://labs.google.com/ridefinder/images/mm_20_shadow.png";
        icon.iconSize = new GSize(20, 34);
        //icon.shadowSize = new GSize( 22, 20 );
        icon.iconAnchor = new GPoint(6, 20); // =TODO Find out more about these two (below)
        icon.infoWindowAnchor = new GPoint(5, 1);

        var m = new GMarker(latlng, icon);

        GEvent.addListener(m, "click", function() {
            IdahoGoogleMap.Base.map.openInfoWindowHtml(latlng,
															IdahoGoogleMap.Results.renderProfileMarker(index, latlng.lat(), latlng.lng())
														);

            //IdahoGoogleMap.Results.selectedItem("result" + index);
        });

        return m;
    },

    // -----------------------------------------------------------------------------------------------------------------------------------------------------

    renderMarker: function(index, lat, lng) {
        var marker, isGroup, type, isFacilitator, isTrainee, groupID, membershipStatus

        //set the marker type, group id and membership status
        type = IdahoGoogleMap.Base.markerType;
        groupID = IdahoGoogleMap.Base.groupID;
        membershipStatus = IdahoGoogleMap.Base.markers[index].membership;
        isTrainee = false;

        //create marker
        marker = "<h4 class=\"markerTitle\">" + IdahoGoogleMap.Base.markers[index].title + "</h4>";

        //if the marker is type 'group' or 'member' then the users organisation is displayed
        if (type == "group" && type == "member") {
            marker += "<p class=\"markerOrg\">" + IdahoGoogleMap.Base.markers[index].organisation + "</p>";
        }

        if (IdahoGoogleMap.Base.markers[index].personcategory != "") {
            marker += "<p class=\"markerCategory\">" + IdahoGoogleMap.Base.markers[index].personcategory + "</p>";
        }

        marker += "<p class=\"markerMiles\">" + IdahoGoogleMap.Base.markers[index].distanceFrom + " miles from your location</p>";

        // add items in on a marker by marker basis
        switch (type) {
            case "group":

                if (membershipStatus != 1 && membershipStatus != 2) {
                    marker += "<p class=\"markerContact\"><a href=\"group.asp?action=join&amp;id=" + IdahoGoogleMap.Base.markers[index].id + "\">Request to Join Group</a></p>";
                }
                // status 2 = pening membership
                if (membershipStatus == 2) {
                    marker += "<p class=\"markerOrg\"><strong>Pending membership request</strong></p>";
                }

                break


            case "invitations":
                marker += "<p class=\"markerContact\"><a href=\"invitations.asp?action=invite&id=" + IdahoGoogleMap.Base.markers[index].id + "\">Invite to Group</a></p>";
                break

            case "member":

                if (IdahoGoogleMap.Base.markers[index].facilitator == 1) {
                    marker += "<p class=\"markerRemoveGroup\"><a href=\"group.asp?action=removeuser&id=" + IdahoGoogleMap.Base.markers[index].id + "\">Remove from group</a></p>";

                    if (IdahoGoogleMap.Base.markers[index].userType == 2) { // is trainee
                        marker += "<p class=\"markerRemoveFac\"><a href=\"group.asp?action=removerights&id=" + IdahoGoogleMap.Base.markers[index].id + "\">Remove facilitator rights</a></p>";
                    }
                    if (IdahoGoogleMap.Base.markers[index].userType == 0) { // is normal user
                        marker += "<p class=\"markerAddFac\"><a href=\"group.asp?action=grantrights&id=" + IdahoGoogleMap.Base.markers[index].id + "\">Grant facilitator rights</a></p>";
                    }

                }
                marker += "<p class=\"markerContact\"><a href=\"contact.asp?id=" + IdahoGoogleMap.Base.markers[index].id + "\">Contact</a></p>";
                break
            default: //users
                marker += "<p class=\"markerContact\"><a href=\"contact.asp?id=" + IdahoGoogleMap.Base.markers[index].id + "\">Contact</a></p>";
        }

        marker += "<p class=\"markerDirections\">Get directions: <a href=\"http://maps.google.co.uk/maps?saddr=" +
					    IdahoGoogleMap.Base.userLat + "," + IdahoGoogleMap.Base.userLng +
						"&amp;daddr=" + lat + "," + lng + "&amp;hl=en\" target=\"_blank\">To Here</a>" +
						" / <a href=\"http://maps.google.co.uk/maps?saddr=" + lat + "," + lng +
						"&amp;daddr=" + IdahoGoogleMap.Base.userLat + "," + IdahoGoogleMap.Base.userLng + "&amp;hl=en\" target=\"_blank\">From Here</a></p>";
        return marker
    },

    // -----------------------------------------------------------------------------------------------------------------------------------------------------

    renderMidPointMarker: function(index, lat, lng) {

        var marker

        //create marker
        marker = "<h3 style=\"float: left; margin-left: 5px; width: 300px\" class=\"markerTitle\">" + IdahoGoogleMap.Base.markers[index].title + "</h3>";

        marker += "<dl class=\"mid-point-info\">"
        marker += "<dt class=\"top\">Author:</dt><dd class=\"top\">" + IdahoGoogleMap.Base.markers[index].author + "</dd>"
        marker += "<dt>Long Term Condition:</dt><dd>" + IdahoGoogleMap.Base.markers[index].ltc + "</dd>"
        marker += "<dt>Quality Requirement:</dt><dd>" + IdahoGoogleMap.Base.markers[index].qr + "</dd>"

        if (IdahoGoogleMap.Base.markers[index].summary.length > 0) {

            marker += "<dt>Summary</dt><dd>" + IdahoGoogleMap.Base.markers[index].summary + "</dd>"

        }

        marker += "</dl>"

        marker += "<a style=\"width: 200px;clear: left; float: left; font-size: 12px; display: block; color: #346397; margin-top: 5px\" href=\"/midpointreview.asp?action=download&id=" + IdahoGoogleMap.Base.markers[index].id + "\"><img style=\"float: left; margin-right: 3px; margin-top: 0px;\" src=\"" + IdahoGoogleMap.Base.markers[index].iconPath + "\" />Download this document</a>"

        return marker
    },

    // -----------------------------------------------------------------------------------------------------------------------------------------------------

    renderProfileMarker: function(index, lat, lng) {

        //create marker
        marker = "<h4 class=\"markerTitle\">" + IdahoGoogleMap.Base.markers[index].title + "</h4>";

        if (index != 0) { //we know it's the user whos profile is being viewed
            marker += "<p class=\"markerMiles\">" + IdahoGoogleMap.Base.markers[index].distanceFrom + " miles from your location</p>";
            marker += "<p class=\"markerContact\"><a href=\"contact.asp?id=" + IdahoGoogleMap.Base.markers[index].id + "\">Contact</a></p>";
        }
        else {
            marker += "<p class=\"markerMiles\">Your current location</p>";
        }

        marker += "<p class=\"markerDirections\">Get directions: <a href=\"http://maps.google.co.uk/maps?saddr=" +
					    IdahoGoogleMap.Base.userLat + "," + IdahoGoogleMap.Base.userLng +
						"&amp;daddr=" + lat + "," + lng + "&amp;hl=en\" target=\"_blank\">To Here</a>" +
						" / <a href=\"http://maps.google.co.uk/maps?saddr=" + lat + "," + lng +
						"&amp;daddr=" + IdahoGoogleMap.Base.userLat + "," + IdahoGoogleMap.Base.userLng + "&amp;hl=en\" target=\"_blank\">From Here</a></p>";
        return marker
    },

    // -----------------------------------------------------------------------------------------------------------------------------------------------------

    selectedItem: function(newlySelectedID) {
        if (IdahoGoogleMap.Base.currentlySelected)  // bubble still open
        {
            // clear currently selected
            IdahoGoogleMap.Base.currentlySelected.style.backgroundColor = "";
            this.changeLetterImageOff(IdahoGoogleMap.Base.currentlySelected);

            // closeFn will get called now - don't let it do anything
            IdahoGoogleMap.Base.goAhead = false;
        }

        IdahoGoogleMap.Base.currentlySelected = document.getElementById(newlySelectedID);

        if (IdahoGoogleMap.Base.isMidPointPage == 'True') {

            IdahoGoogleMap.Base.currentlySelected.style.backgroundColor = "#d3e0ee";

        }
        
        //this.changeLetterImageOn ( IdahoGoogleMap.Base.currentlySelected );
    },

    // -----------------------------------------------------------------------------------------------------------------------------------------------------

    changeLetterImageOn: function(div) {
        var children = div.childNodes;

        for (var i = 0, size = children.length; i < size; i++) {
            if (children[i].nodeName == "IMG") {
                var src = children[i].src;

                if (src.indexOf("_off.gif") > 0) {
                    var rExp = /_off/gi;
                    children[i].src = src.replace(rExp, "_on");
                }
            }
        }
    },

    // -----------------------------------------------------------------------------------------------------------------------------------------------------

    changeLetterImageOff: function(div) {
        var children = div.childNodes;

        for (var i = 0, size = children.length; i < size; i++) {
            if (children[i].nodeName == "IMG") {
                var src = children[i].src;

                if (src.indexOf("_on.gif") > 0) {
                    var rExp = /_on/gi;
                    children[i].src = src.replace(rExp, "_off");
                }
            }
        }
    },

    // -----------------------------------------------------------------------------------------------------------------------------------------------------

    zoomToUser: function(lat, lng) {
        var markerLatLng = new GLatLng(lat, lng);
        var index = IdahoGoogleMap.Base.markers.length - 1;
        IdahoGoogleMap.Base.map.openInfoWindowHtml(markerLatLng,
															IdahoGoogleMap.Results.renderProfileMarker(index, markerLatLng.lat(), markerLatLng.lng())
														);
    },

    // -----------------------------------------------------------------------------------------------------------------------------------------------------

    attachResultClickEvents: function(markers) {
        var div_results = document.getElementById("map-results");

        if (div_results) {
            for (var i = 0, size = IdahoGoogleMap.Base.markers.length; i < size; i++) {
                var marker = IdahoGoogleMap.Base.markers[i];

                var options = {
                    onCloseFn: function() {
                        // if window is open currentlySelected exists - clear colour and 'unselect'
                        if (IdahoGoogleMap.Base.goAhead) {
                            IdahoGoogleMap.Base.currentlySelected.style.backgroundColor = "";
                            IdahoGoogleMap.Results.changeLetterImageOff(IdahoGoogleMap.Base.currentlySelected);
                            IdahoGoogleMap.Base.currentlySelected = null;
                        }
                        else {
                            IdahoGoogleMap.Base.goAhead = true;
                        }
                    }
                };

                // grab the resultDiv
                var resultDiv = div_results.childNodes[i];

                resultDiv.index = i; // using this expando property to keep the current iteration value, REAL ARSE TO FIGURE OUT! Cant rely on i

                resultDiv.onclick = function() {

                    if (IdahoGoogleMap.Base.isMidPointPage == 'True') {

                        IdahoGoogleMap.Base.map.openInfoWindowHtml(new GLatLng(markers[this.index].lat, markers[this.index].lng),
															IdahoGoogleMap.Results.renderMidPointMarker(this.index, markers[this.index].lat, markers[this.index].lng),
															options
														);
                    } else {

                        IdahoGoogleMap.Base.map.openInfoWindowHtml(new GLatLng(markers[this.index].lat, markers[this.index].lng),
															IdahoGoogleMap.Results.renderMarker(this.index, markers[this.index].lat, markers[this.index].lng),
															options
														);

                    }

                    IdahoGoogleMap.Results.selectedItem("result" + this.index);
                }

            }
        }
    }
};

function addLoadEvent( func )
{
	var oldonload = window.onload;
	if ( typeof window.onload != "function" )
	{
		window.onload = func;
	}
	else
	{
		window.onload = function()
		{
			if ( oldonload )
			{
				oldonload();
			}
			func();
		}
	}
}

addLoadEvent( function() { IdahoGoogleMap.Base.InitMap(); } );

window.onunload = function()
{
	IdahoGoogleMap.Base.EndMap();			
}
