//globals
var goMap;
var ignoreEvents = false;
var link_interface;
var mapping;
var docURL;
var polylineIDs = new Array();
var polylineStates = new Array();
var mainPolyline = new Array();
var overviewPolyline = new Array();

var myMap = function(mapCont, listCont) {
    var self = this;
    //Initializes
    // Sets the basic parameters for the map
    this.init = function() {
        var defaultResults = document.getElementById(listCont).title;
        var longLatArray = defaultResults.split(";");
        this.lng = parseFloat(longLatArray[0]);
        this.lat = parseFloat(longLatArray[1]);
        this.zoom = parseFloat(longLatArray[2]);
        if (GBrowserIsCompatible()) {
            this.createMap();
        }
    };

    // Creates the map
    this.createMap = function() {
        //get the container
        var container = document.getElementById(mapCont);
        //SMALL
        if (this.mapSize == 'small') {
            this.map = new GMap2(container);
            this.map.addControl(new GSmallMapControl());

        }
        //MEDIUM
        else if (this.mapSize == 'medium') {
            this.map = new GMap2(container);
            this.map.addControl(new GLargeMapControl());

        }
        else //BIG BOY - used on POI listing page
        {
            //create a container
            var mapdiv = document.createElement("div");
            mapdiv.setAttribute("id", "map");
            container.appendChild(mapdiv);
            this.map = new GMap2(mapdiv);
            this.mapControl = new GLargeMapControl(); //gets the map
            this.map.addControl(this.mapControl); //zooming etc. top left
            this.map.addControl(new GScaleControl()); //scale bit to the right of logo
            this.map.addControl(new TrafficControl()); //adds the button to toggle traffic display

        }
        //set the centre of the map - may be overridden later
        var point = new GLatLng(this.lat, this.lng);
        this.map.setCenter(point, this.zoom);
        this.map.addControl(new GMapTypeControl());


        //NEW

        this.map.addMapType(G_PHYSICAL_MAP); //terrain

        //END OF NEW
    };

    this.reloadMapLocation = function() {
        if (self.ignoreEvents == false) {
            self.ignoreEvents = true; // prevents recursive triggering of functions
            this.reloadPoints(docURL, 1);
        }
        return true;
    };

    // Looks at the locations specified within the container locations and triggers the process of building the markers
    this.analLinks = function(showCentre) {
        //update the links for add to  plan
        checkOverridePlanner();
        var container = document.getElementById(listCont);
        var Links = getElementsByClassName(container, "div", "result");
        //hack to make events listing work
        if (Links.length == 0) Links = getElementsByClassName(container, "div", "event");
        self.map.clearOverlays();
        var bounds = new GLatLngBounds();
        //draw the viewport

        for (var i = 0; i < Links.length; i++) {
            var longLat = Links[i].getAttribute("title").split(";");
            if (longLat) {
                Links[i].colat = parseFloat(longLat[0]);
                Links[i].colong = parseFloat(longLat[1]);
                var point = new GLatLng(Links[i].colat, Links[i].colong);
                var element = Links[i].innerHTML;
                var linkObj
                if (longLat[2]) {
                    var icon = "/images/marker" + longLat[2] + ".gif";
                }
                else {
                    var icon = "/images/marker01.gif";
                }
                var showMap = getElementsByClassName(Links[i], "a", "buttonMap");
                for (var j = 0; j < showMap.length; j++) {
                    linkObj = showMap[j];
                    showMap[j].onclick = function() {
                        self.ignoreEvents = true;
                        link_interface = this;
                        mapping.showMap(this);
                        checkOverridePlanner();


                    };
                };
                if (showCentre == 1) bounds.extend(point);
                self.map.addOverlay(self.createMarker(point, i + 1, element, icon, linkObj));

            }
        }
        //set centre
        var clat = (bounds.getNorthEast().lat() + bounds.getSouthWest().lat()) / 2;
        var clng = (bounds.getNorthEast().lng() + bounds.getSouthWest().lng()) / 2;
        if (clat != 0 && clng != 0 && (self.mapSize == 'small' | self.mapSize == 'medium') | document.getElementById('lastSearch') != null) {
            self.map.setCenter(new GLatLng(clat, clng));
            var newZoom = self.map.getBoundsZoomLevel(bounds);
            if (newZoom > 14) newZoom = 15;
            self.map.setZoom(newZoom);
        }
        if (document.getElementById("vpRadius")) {
            self.drawCircle(document.getElementById("vpRadius").value);
        }
        if (self.showTraffic) mapping.map.addOverlay(new GTrafficOverlay()); //traffic
        self.ignoreEvents = false;
    };

    this.drawCircle = function(radius) {
        //radius is in km
        var x;
        var y;
        var A = [];
        var i = 0;
        var skew = 1.7; //aproximation for projection - gets mad on world map view
        var b = self.map.getBounds();
        var ne = b.getNorthEast();
        var sw = b.getSouthWest();
        var c = self.map.getCenter();

        A[0] = new GLatLng(sw.lat(), c.lng());
        A[1] = new GLatLng(sw.lat() - 2 * (ne.lat() - sw.lat()), c.lng());
        A[2] = new GLatLng(sw.lat() - 2 * (ne.lat() - sw.lat()), sw.lng() - 2 * (ne.lng() - sw.lng()));
        A[3] = new GLatLng(ne.lat() + 2 * (ne.lat() - sw.lat()), sw.lng() - 2 * (ne.lng() - sw.lng()));
        A[4] = new GLatLng(ne.lat() + 2 * (ne.lat() - sw.lat()), c.lng());
        A[5] = new GLatLng(ne.lat(), c.lng());
        i = 6;
        //do left side of polygon
        for (var theta = Math.PI / 2; theta <= 3 * Math.PI / 2; theta += 2 * 3.14 / 100) {

            x = Math.cos(theta) * radius;
            y = Math.sin(theta) * radius;
            //convert x back to lat long
            var c = self.map.getCenter();
            x = x * 360 / 40010 + c.lng();
            y = y * 360 / 40010 / skew + c.lat();
            A[i] = new GLatLng(y, x);
            i++;
        }

        //do right of polygon	
        A[i] = new GLatLng(sw.lat(), c.lng());
        A[i + 1] = new GLatLng(sw.lat() - 2 * (ne.lat() - sw.lat()), c.lng());
        A[i + 2] = new GLatLng(sw.lat() - 2 * (ne.lat() - sw.lat()), ne.lng() + 2 * (ne.lng() - sw.lng()));
        A[i + 3] = new GLatLng(ne.lat() + 2 * (ne.lat() - sw.lat()), ne.lng() + 2 * (ne.lng() - sw.lng()));
        A[i + 4] = new GLatLng(ne.lat() + 2 * (ne.lat() - sw.lat()), c.lng());
        A[i + 5] = new GLatLng(ne.lat(), c.lng());
        i += 6;
        for (theta = 0; theta <= Math.PI; theta += 2 * 3.14 / 100) {

            x = Math.sin(theta) * radius;
            y = Math.cos(theta) * radius;
            //convert x back to lat long
            var c = self.map.getCenter();
            x = x * 360 / 40010 + c.lng();
            y = y * 360 / 40010 / skew + c.lat();
            A[i] = new GLatLng(y, x);
            i++;
        }
        //draw it
        P = new GPolygon(A, "", 0, 0.2, "#666666", 0.2);
        self.map.addOverlay(P);
        A = [];
        i = 0;
        //draw the pretty red circle inside the polygon (1/2 overlap)
        for (theta = 0; theta <= 2 * Math.PI; theta += 2 * 3.14 / 100) {

            x = Math.sin(theta) * radius;
            y = Math.cos(theta) * radius;
            //convert x back to lat long
            var c = self.map.getCenter();
            x = x * 360 / 40010 + c.lng();
            y = y * 360 / 40010 / skew + c.lat();
            A[i] = new GLatLng(y, x);
            i++;
        }
        P = new GPolygon(A, "#FF0000", 5, 0.4);
        self.map.addOverlay(P);

    };

    this.showMap = function(obj) {
        //shows an entry on the map - treatment for map sizes has a lot of duplication, needs rationalising
        //make sure the popuplinks still work
        this.ignoreEvents = true;
        if (this.mapSize != 'small') {
            //clear the map - then re-add points
            self.map.clearOverlays();
            self.analLinks(false);
            try {
                self.loadPolyLines();
            } catch (e) {
                // Continue
            }

            //now add a pretty custom marker for the current point
            var icon = new GIcon();
            icon.iconAnchor = new GPoint(0, 24);
            icon.infoWindowAnchor = new GPoint(0, 24);
            icon.image = '/images/markerCurrent.gif';
            var point = new GLatLng(obj.parentNode.colat, obj.parentNode.colong);
            var marker = new GMarker(point, icon);
            self.map.addOverlay(marker);
            //setup the html for the inro bubble
            var _cont = document.createElement("div");
            _cont.innerHTML = obj.parentNode.innerHTML;
            var _element = _cont.getElementsByTagName("a");
            for (var k = 0; k < _element.length; k++) {
                if (_element[k].innerHTML == 'Show on map' || _element[k].innerHTML == 'Remove from plan') {
                    _cont.removeChild(_element[k]);
                    k = k - 1;
                }
                element = _cont.innerHTML;
                element = "<div id = \"bubblediv\" class = \"bubblediv\">" + element + "</div>";
            }
            //pan to the selected point
            var point = new GLatLng(obj.parentNode.colat, obj.parentNode.colong);
            mapping.ignoreEvents = true; //it will have been unset by analLinks
            self.map.panTo(point);
            showInfo = self.map.openInfoWindow(point, element);
            //disable events on big maps
            if (this.mapSize != 'medium') setTimeout("mapping.ignoreEvents=false;mapping.mapControl = new GLargeMapControl();mapping.map.addControl(mapping.mapControl);", 5000);
        }
        else {
            //clear the map - then re-add points
            self.map.clearOverlays();
            self.analLinks(false);
            //now add a pretty custom marker for the current point
            var icon = new GIcon();
            icon.iconAnchor = new GPoint(0, 24);
            icon.infoWindowAnchor = new GPoint(0, 24);
            icon.image = '/images/markerCurrent.gif';
            var point = new GLatLng(obj.parentNode.colat, obj.parentNode.colong);
            var marker = new GMarker(point, icon);
            self.map.addOverlay(marker);
            //setup the html for the info bubble
            var _cont = document.createElement("div");
            _cont.innerHTML = obj.parentNode.innerHTML;
            var _element = _cont.getElementsByTagName("a");
            for (var k = 0; k < _element.length; k++) {
                if (_element[k].innerHTML == 'Show on map' || _element[k].innerHTML == 'Remove from plan' || _element[k].innerHTML == 'Add to plan') {
                    _cont.removeChild(_element[k]);
                    k = k - 1;
                }
                element = _cont.innerHTML;
                element = "<div id = \"mapInfoWindow\" class = \"bubbledivSmall\">" + element + "</div>";
            }
            //pan to the selected point
            var point = new GLatLng(obj.parentNode.colat, obj.parentNode.colong);
            self.map.panTo(point);
            showInfo = self.map.openInfoWindow(point, element);

            self.map.panTo(point);

        }

        makePopupLinks();

    };
    // Creates a marker at the given point with the given label
    this.createMarker = function(point, number, element, vicon, obj) {

        var title = obj.parentNode.getElementsByTagName("a")[0].innerHTML;
        title = title.replace("&amp;", "&");
        var icon = new GIcon();
        icon.iconAnchor = new GPoint(0, 24);
        icon.infoWindowAnchor = new GPoint(0, 24);
        icon.image = vicon;
        var marker = new GMarker(point, { title: title, icon: icon });
        GEvent.addListener(marker, "click", function() {
            self.showMap(obj);
        });
        return marker;
    };

    // Creates the link for expanding and colapsing the map
    this.biggerMap = function(beforeThis) {
        var biggerLink = document.createElement("p");
        var insertBeforeThis = document.getElementById(beforeThis);
        biggerLink.setAttribute("class", "right");
        biggerLink.innerHTML = '<a href="#" class="map_bigger" id="mapBigger">Bigger Map</a>';
        insertBeforeThis.parentNode.insertBefore(biggerLink, insertBeforeThis);
        var newLink = document.getElementById("mapBigger");
        newLink.onclick = function() {
            if (document.getElementById("mapContainer")) {
                document.getElementById("mapContainer").setAttribute("id", "mapContainerWide");
                document.getElementById("mapBigger").innerHTML = "Smaller Map";
                document.getElementById("sidecol_mapcontrols").className = "sidecol_mapcontrols_wide";
            }
            else {
                document.getElementById("mapContainerWide").setAttribute("id", "mapContainer");
                document.getElementById("mapBigger").innerHTML = "Bigger Map";
                document.getElementById("sidecol_mapcontrols").className = "";
            }
            return false;
        }
    };

    // Triggers the expanding and colapsing of the search results
    this.resultsColapse = function() {
        var resultsHead = getElementsByClassName(document, "h3", "title");
        for (var i = 0; i < resultsHead.length; i++) {
            resultsHead[i].onclick = function() {
                if (this.style.backgroundPosition == 'left bottom' || this.style.backgroundPosition == '') {
                    this.style.backgroundPosition = '0 -3px';
                    self.hideResults(this);
                }
                else {
                    this.style.backgroundPosition = 'left bottom';
                    self.hideResults(this);
                }
            }
        }
    };
    // Hides the search results of a clicked heading
    this.hideResults = function(theHeading) {
        var divToHide = getElementsByClassName(theHeading.parentNode, "div", "results");

        for (var i = 0; i < divToHide.length; i++) {
            if (divToHide[i].style.display == 'block' || divToHide[i].style.display == '') {
                divToHide[i].style.display = 'none';
            }
            else {
                divToHide[i].style.display = 'block';
            }
        }
    };

    // AJAX code forking
    this.getHTTPOject = function() {
        var xhr = false;
        if (window.ActiveXObject) {
            try {
                xhr = new ActiveXObject("Msxml2.XMLHTTP");
            } catch (e) {
                try {
                    xhr = new ActiveXObject("Microsoft.XMLHTTP");
                } catch (e) {
                    xhr = false;
                }
            }
        } else if (window.XMLHttpRequest) {
            try {
                xhr = new XMLHttpRequest();
            } catch (e) {
                xhr = false;
            }
        }
        return xhr;
    };

    // AJAX - Grabs a predefined file to pull back into the page
    this.grabFile = function(file, theaction) {
        var request = self.getHTTPOject();
        if (request) {
            request.onreadystatechange = function() {
                self.displayResponse(request, theaction);
            };
            request.open("GET", file, true);
            request.send(null);
        }
    };

    //AJAX - Once the file is found this decides what to do with it.
    this.displayResponse = function(request, theaction) {
        if (request.readyState == 4) {
            if (theaction == "categories") {
                document.getElementById("sidecol_mapcontrols").innerHTML = request.responseText;
                self.categoriesLinks("sidecol_mapcontrols");
                document.getElementById('polylineDiv').style.display = "block";
            }
            if (theaction == "poi") {
                document.getElementById("mapresultsbox").innerHTML = request.responseText;
                self.analLinks(0);
                self.resultsColapse();
                //show we have loaded
                document.getElementById("pageCover").style.display = "none";
                document.getElementById("pageCoverLoading").style.display = "none";

                for (var i = 0, len = polylineIDs.length; i < len; ++i) {
                    self.loadPolyLines(polylineIDs[i]);
                }
                //_map.addOverlay(new GTrafficOverlay()); //traffic
            }
        }
    };

    this.loadPolyLines = function(lineid) {
        if (polylineStates[lineid] == 1) {
            mainPolyline[lineid] = new Array();
            overviewPolyline[lineid] = new Array();
            var plDiv = document.getElementById("polyLine");
            var oMap = goMap.getOverviewMap();
            var nPolyCount = 0;
            if (plDiv != null) {
                //for each type of line
                var div1s = document.getElementById("lineid" + lineid);
                if (div1s != null) {
                    var lineNum = 0;
                    //for(var d1=0;d1<div1s.length;d1++)
                    //{
                    //var div1 = div1s[d1];
                    var div2s = div1s.getElementsByTagName("div");
                    //for each section 

                    if (div2s != null) {
                        for (var d2 = 0; d2 < div2s.length; d2++) {
                            lineNum++;

                            var points = [];
                            var inputs = div2s[d2].getElementsByTagName("input");
                            for (var i = 0; i < inputs.length; i++) {
                                var _input = inputs[i];
                                var s = _input.value.split(",")
                                points.push(new GLatLng(parseFloat(s[0]), parseFloat(s[1])));
                                //var gm = new GMarker(new GLatLng(parseFloat(s[0]),parseFloat(s[1])));
                                //self.map.addOverlay(gm);
                                //alert (s[0] + ',' + s[1]);
                            }
                            lineCol = div1s.title;
                            //add to main map
                            mainPolyline[lineid][nPolyCount] = new GPolyline(points, lineCol, 5, 1);
                            overviewPolyline[lineid][nPolyCount] = new GPolyline(points, lineCol, 3, 1);
                            self.map.addOverlay(mainPolyline[lineid][nPolyCount]);
                            //add to overview map
                            oMap.addOverlay(overviewPolyline[lineid][nPolyCount]);
                            //increment
                            nPolyCount++;
                        }
                    }
                    //}
                }
            }
        }
    };

    this.hidePolyLines = function(lineid) {
        if (mainPolyline.length > 0) {
            try {
                for (var i = 0; i < mainPolyline[lineid].length; i++) {
                    self.map.removeOverlay(mainPolyline[lineid][i]);
                    goMap.getOverviewMap().removeOverlay(overviewPolyline[lineid][i]);
                }
            } catch (e) { }
        }
    };

    this.reloadPoints = function(href, ignoreCat) {
        //show we are reloading
        //document.getElementById("waitImg").style.display = "block";
        document.getElementById("pageCoverLoading").style.display = "block";
        document.getElementById("pageCover").style.display = "block";

        self.map.clearOverlays();
        //mapping.map.removeControl(goMap);
        //goMap = new GOverviewMapControl(new GSize(200,200));
        //mapping.map.addControl(goMap);
        //get the bounds of the viewport on GMap
        var bounds = self.map.getBounds();
        var sw = bounds.getSouthWest();
        var ne = bounds.getNorthEast();
        var maxLat = ne.lat();
        var minLat = sw.lat();
        var maxLong = ne.lng();
        var minLong = sw.lng();

        //end get bounds
        var catArray = href.split("?");
        var qs = '';
        if (catArray[1]) {
            qs = catArray[1];
            qs += '&';
        }
        //alert (maxLong + ',' + minLong + ',' + maxLat + ',' + minLat);
        qs += "x2=" + maxLong + "&x1=" + minLong + "&y2=" + maxLat + "&y1=" + minLat;
        if (ignoreCat == null) {

            var catURL = "poi_frag_cat.asp?" + qs;
            self.grabFile(catURL, "categories");
        }
        else {
            qs += "&opn=" + document.getElementById("h_opn").value;
            qs += "&chk=" + document.getElementById("h_chk").value;
        }
        var poiURL = "poi_frag_poi.asp?" + qs;
        self.grabFile(poiURL, "poi");
        //update by r thornton to update the form submission values

        if (catArray[1]) {

            var catQS = catArray[1].split("&");

            for (var j = 0; j < catQS.length; j++) {
                if (catQS[j].substring(0, 3) == "opn") {
                    document.getElementById("h_opn").value = catQS[j].substring(4);
                }
                if (catQS[j].substring(0, 3) == "chk") {
                    document.getElementById("h_chk").value = catQS[j].substring(4);
                }
            }
        };
        return false;
    };

    // AJAX call on project categories
    this.categoriesLinks = function(catID) {
        var theContainer = document.getElementById(catID);
        var theLinks = theContainer.getElementsByTagName("a");
        for (var i = 0; i < theLinks.length; i++) {
            if (theLinks[i].href.indexOf('javascript:') < 0)
                theLinks[i].onclick = function() { docURL = this.href; return self.reloadPoints(this.href) };

        }
    }

}

function loadSmallMap(lat, lng, mapId) {
    checkOverridePlanner();

    if (GBrowserIsCompatible()) {
        doOnload();

        var map = new GMap2(document.getElementById(mapId));
        map.addControl(new GSmallMapControl());
        var center = new GLatLng(lat, lng);
        map.setCenter(center, 13);
        //Create a marker
        var icon = new GIcon();
        icon.iconAnchor = new GPoint(9, 34);
        icon.infoWindowAnchor = new GPoint(9, 2);
        icon.image = "/images/marker01.gif";
        var marker = new GMarker(center, icon);
        map.addOverlay(marker);
    }
}


//entry point function to load multi point maps
function loadMaps(mapContainer, mapResults, mapSize) {
    try {
        checkOverridePlanner();
        doOnload();
        if (document.getElementById("doc_url")) docURL = document.getElementById("doc_url").value.split("#")[0];

        if (mapContainer == null | mapResults == null) {
            mapContainer = "mapContainer";
            mapResults = "mapresultsbox"
        }
        mapping = new myMap(mapContainer, mapResults);
        mapping.mapSize = mapSize;
        mapping.init();
        mapping.analLinks(1);

        if (mapSize == null) {
            document.getElementById('polylineDiv').style.display = "block";
            GEvent.addListener(mapping.map, "moveend", function() { mapping.reloadMapLocation(); })
            GEvent.addListener(mapping.map, "zoomend", function() { mapping.ignoreEvents = false; mapping.reloadMapLocation(); })
            GEvent.addListener(mapping.map, "zoomstart", function() { mapping.ignoreEvents = false; })
            //GEvent.addListener(mapping.map , "click", mapClick);		
            GEvent.addListener(mapping.map, "dragstart", function() { mapping.ignoreEvents = false; })
            mapping.biggerMap("postcodeSearch");
            mapping.categoriesLinks("sidecol_mapcontrols");
            mapping.resultsColapse();
            mapping.ignoreEvents = false;
            polylineIDs = document.getElementById("polyLineIDs").innerHTML.split(",");
            polylineStates = new Array(polylineIDs.length);
        }

        //mapping.loadPolyLines();
    }
    catch (exc) {
    }
}

function setupOverview() {
    //create and add an overview map
    goMap = new GOverviewMapControl(new GSize(200, 200));
    mapping.map.addControl(goMap);
    // Initialise poly, but delay otherwise overview map doesn't load in time!!
    setTimeout("initPolyline()", 1000);
}

function initPolyline() {
    for (var i = 0, len = polylineIDs.length - 1; i < len; ++i) {
        polylineStates[i] = 0;
        if (document.getElementById("polylineOn" + polylineIDs[i]).innerHTML == '1') {
            polylineOn(false, polylineIDs[i]);
        }
        else if (document.cookie.indexOf('polyLine' + polylineIDs[i] + '=1') != -1) {
            polylineOn(true, polylineIDs[i]);
        }
        else {
            polylineOff(true, polylineIDs[i]);
        }
    }
}

function mapClick(marker, clickedPoint) {
    alert(clickedPoint.lat());
    alert(clickedPoint.lng());


}

//runs on map submit
function mapSearchSubmit() {
    var bounds = mapping.map.getBounds();
    var sw = bounds.getSouthWest();
    var ne = bounds.getNorthEast();
    var maxLat = ne.lat();
    var minLat = sw.lat();
    var maxLong = ne.lng();
    var minLong = sw.lng();

    document.getElementById("ax1").value = minLong;
    document.getElementById("ax2").value = maxLong;
    document.getElementById("ay1").value = minLat;
    document.getElementById("ay2").value = maxLat;

}

function checkOverridePlanner() {
    //this function overrides the planner links in the document to use ajax calls
    var _aTags = document.getElementsByTagName("a");
    var _element;
    for (var i = 0; i < _aTags.length; i++) {
        _element = _aTags[i];
        if (_element.href.indexOf('?pa=') > 0 || _element.href.indexOf('&pa=') > 0) {
            _element.onclick = function() {
                return OverridePlanner(this);
            }
        }
    }
}
function OverridePlanner(item) {
    try {
    }
    catch (ex) {
        return true;
    }
    grabFile('/planner_frag.asp' + item.href.substring(item.href.indexOf("?"), 100), item);
    return false;
}

function getHTTPOject() {
    var xhr = false;
    if (window.ActiveXObject) {
        try {
            xhr = new ActiveXObject("Msxml2.XMLHTTP");
        } catch (e) {
            try {
                xhr = new ActiveXObject("Microsoft.XMLHTTP");
            } catch (e) {
                xhr = false;
            }
        }
    } else if (window.XMLHttpRequest) {
        try {
            xhr = new XMLHttpRequest();
        } catch (e) {
            xhr = false;
        }
    }
    return xhr;
}

// AJAX - Grabs a predefined file to pull back into the page

function grabFile(file, theaction) {
    var request = getHTTPOject();
    if (request) {
        request.onreadystatechange = function() {
            displayResponse(request, theaction);
        };
        request.open("GET", file, true);
        request.send(null);
    }
}

//AJAX - Once the file is found this decides what to do with it.
function displayResponse(request, theaction) {
    if (request.readyState == 4) {
        if (theaction.innerHTML == "Add to plan") {
            document.getElementById("plannerDiv").innerHTML = request.responseText;
            theaction.innerHTML = "Included in plan";
            theaction.removeAttribute("href");
            theaction.className = theaction.className.replace("buttonPlan", "buttonInPlan");
        }
    }
}

function polylineOn(setcookie, lineid) {
    polylineStates[lineid] = 1;
    if (setcookie == true) { document.cookie = 'polyLine' + lineid + '=1;path=/'; }
    document.getElementById("polyOn" + lineid).className = "polyOn polySelected";
    document.getElementById("polyOff" + lineid).className = "polyOff";
    mapping.loadPolyLines(lineid);
}

function polylineOff(setcookie, lineid) {
    polylineStates[lineid] = 0;
    if (setcookie == true) { document.cookie = 'polyLine' + lineid + '=0;path=/'; }
    document.getElementById("polyOn" + lineid).className = "polyOn";
    document.getElementById("polyOff" + lineid).className = "polyOff polySelected";
    mapping.hidePolyLines(lineid);
    //mapping.map.removeControl(goMap);
    //goMap = new GOverviewMapControl(new GSize(200,200));
    //mapping.map.addControl(goMap);
}

// A TextualZoomControl is a GControl that displays textual "Zoom In"
// and "Zoom Out" buttons (as opposed to the iconic buttons used in
// Google Maps).

// We define the function first
function TrafficControl() {
}

// To "subclass" the GControl, we set the prototype object to
// an instance of the GControl object
TrafficControl.prototype = new GControl();

// Creates a one DIV for each of the buttons and places them in a container
// DIV which is returned as our control element. We add the control to
// to the map container and return the element for the map class to
// position properly.
TrafficControl.prototype.initialize = function(map) {
    var container = document.createElement("div");
    jQuery(container).css({
        color: '#000',
        backgroundColor: '#fff',
        border: '1px solid #222',
        padding: '4px'
    });

    var toggleBtn = jQuery('<input type="checkbox" id="toggleTraffic" />').click(function() {
        mapping.showTraffic = !mapping.showTraffic;
        mapping.reloadMapLocation();
    });
    jQuery(container).append(toggleBtn).append('<label for="toggleTraffic">Show traffic</label>').find('input,label').css({ 'float': 'left', 'clear': 'none', 'margin': '2px', 'lineHeight': '1em' });

    map.getContainer().appendChild(container);
    return container;
}

// By default, the control will appear in the top left corner of the
// map with 7 pixels of padding.
TrafficControl.prototype.getDefaultPosition = function() {
    return new GControlPosition(G_ANCHOR_TOP_RIGHT, new GSize(400, 7));
}
