﻿//Declarations section
var map = null;
var dynamicMap = null;
var queryOverlays = null;
var cityOverlays = new Array();
var mapExtension = null;
var geocoder = null;
var gsvc = null;
var qtask = null;
var query = null;
var idtask = null;
var cityQuery = null;
var cQuery = null;
var citytask = null;
var directions = null;
var polyCenter = null;
var addressMarker = null;
var bufferMarker = null;
var BaseIcon = null;
var imagePath = 'http://www.marc.org/rideshare/images/pnrmap/lots/';
var imageThumbPath = 'http://www.marc.org/rideshare/images/pnrmap/lots_sm/';

//Dojo setup
dojo.require("dojox.grid.Grid");
dojo.require("dojox.grid._data.model");
dojo.require("dojo.parser");
dojo.require("dojo.dnd.Mover");
dojo.require("dojo.dnd.Moveable");
dojo.require("dojo.dnd.move");
dojo.require("dijit.ProgressBar");

//Dojo Grid Setup
var m1, m2, m3;
var initDND = function() {
    m1 = new dojo.dnd.Moveable("gridDisplay", { handle: "handle" });
    m2 = new dojo.dnd.Moveable("directions");
    m3 = new dojo.dnd.Moveable("help");

    dojo.subscribe("/dnd/move/start", function(mover) {
        console.debug("Start move", mover);
    });
    dojo.subscribe("/dnd/move/stop", function(mover) {
        console.debug("Stop move", mover);
    });

    dojo.connect(m1, "onMoveStart", function(mover) {
        console.debug("Start moving m1", mover);
    });
    dojo.connect(m1, "onMoveStop", function(mover) {
        console.debug("Stop moving m1", mover);
    });
};

//Setup the call to nifty corners to round the help and error corners
var iniNifty = function() {
    Nifty("div#help,div#error");
}
dojo.addOnLoad(initDND);
dojo.addOnLoad(iniNifty);

//Function to initialize the map display
function initialize() {
    if (GBrowserIsCompatible()) {
        //Override the array object to add a contains method
        Array.prototype.contains = function(element) {
            for (var i = 0; i < this.length; i++) {
                if (this[i] == element) {
                    return true;
                }
            }
            return false;
        }
        //Map Setup
        map = new GMap2(document.getElementById("map"));
        map.setCenter(new GLatLng(38.95, -94.44), 9);
        map.addControl(new GLargeMapControl());
        map.addControl(new GMapTypeControl());
        map.addControl(new GScaleControl());
        map.enableScrollWheelZoom();

        //Create the display marker for the searched address
        BaseIcon = new GIcon();
        BaseIcon.image = '../images/persondom.png'
        BaseIcon.shadow = '../images/shadow50.png';
        BaseIcon.iconSize = new GSize(20, 34);
        BaseIcon.shadowSize = new GSize(37, 34);
        BaseIcon.iconAnchor = new GPoint(9, 34);
        BaseIcon.infoWindowAnchor = new GPoint(9, 2);
        BaseIcon.infoShadowAnchor = new GPoint(18, 25);
        
        //Instantiate the geocoder object
        geocoder = new GClientGeocoder();

        //Instantiate the directions object
        directions = new GDirections(map, document.getElementById('directions'));

        //Listen for errors in the getting directions
        GEvent.addListener(directions, "error", function(results) {
            if (directions.getStatus().code == G_GEO_UNKNOWN_ADDRESS) {
                document.getElementById('errorDetail').innerHTML = "<p>No corresponding geographic location could be found for one of the specified addresses. This may be due to the fact that the address is relatively new, or it may be incorrect.<br />Error code: " + directions.getStatus().code + "</p>";
            }
            else if (directions.getStatus().code == G_GEO_SERVER_ERROR) {
                document.getElementById('errorDetail').innerHTML = "<p>A geocoding or directions request could not be successfully processed, yet the exact reason for the failure is not known.<br /> Error code: " + directions.getStatus().code + "</p>";
            }
            else if (directions.getStatus().code == G_GEO_MISSING_QUERY) {
                document.getElementById('errorDetail').innerHTML = "<p>The HTTP q parameter was either missing or had no value. For geocoder requests, this means that an empty address was specified as input. For directions requests, this means that no query was specified in the input.<br /> Error code: " + directions.getStatus().code + "</p>";
            }
            else if (directions.getStatus().code == G_GEO_BAD_KEY) {
                document.getElementById('errorDetail').innerHTML = "<p>The given key is either invalid or does not match the domain for which it was given. <br /> Error code: " + directions.getStatus().code + "</p>";
            }
            else if (directions.getStatus().code == G_GEO_BAD_REQUEST) {
                document.getElementById('errorDetail').innerHTML = "<p>A directions request could not be successfully parsed.<br /> Error code: " + directions.getStatus().code + "</p>";
            }
            else {
                document.getElementById('errorDetail').innerHTML = "<p>An unknown error occurred.</p>";
            }
            document.getElementById('error').style.visibility = 'visible';
        });

        //Add the ArcServer service
        addDynamicMap();
        
        //Create MapExtension utility class
        mapExtension = new esri.arcgis.gmaps.MapExtension(map);

        //identify proxy page to use if the toJson payload to the geometry service is greater than 2000 characters.
        //If this null or not available the buffer operation will not work.  Otherwise it will do a http post to the proxy.
        esri.arcgis.gmaps.Config.proxyUrl = "proxy.ashx";

        //Setup the identify task for use with clicking on the dynamicMap service
        idtask = new esri.arcgis.gmaps.IdentifyTask("http://gis.marc2.org/marcgis/rest/services/ParkAndRide/MapServer");

        //Setup query tasks for address query and city query
        qtask = new esri.arcgis.gmaps.QueryTask("http://gis.marc2.org/marcgis/rest/services/ParkAndRide/MapServer/0");
        citytask = new esri.arcgis.gmaps.QueryTask("http://gis.marc2.org/marcgis/rest/services/ParkAndRide/MapServer/0");

        //Listen for QueryTask executecomplete event
        GEvent.addListener(qtask, "executecomplete", function(fset) {
            //Check to see if any features are returned
            if (fset.features.length == 0) {
                toggleProgressBar();
                document.getElementById('address').style.visibility = 'hidden';
                document.getElementById('city').style.visibility = 'hidden';
                document.getElementById('errorDetail').innerHTML = "<p>No stops returned for that search.<br />Please try again."
                document.getElementById('error').style.visibility = 'visible';
                return;
            }

            //Do this code only if features were returned
            var distArray = new Array();
            var bounds = new GLatLngBounds();
            var dist = null;

            var myMarkerOptions = {
                title: "{Name}"
            };
            var overlayOptions = {
                markerOptions: myMarkerOptions
            };

            //Check to see if we are searching for an address or a city
            if (document.getElementById('address').style.visibility == 'visible') {
                for (var i = 0; i < fset.features.length; i++) {
                    var feature = fset.features[i]
                    var geometry = fset.features[i].geometry;
                    for (var j = 0; j < geometry.length; j++) {
                        var lat = parseFloat(geometry[j].getLatLng().lat());
                        var lng = parseFloat(geometry[j].getLatLng().lng());
                        var point = new GLatLng(lat, lng);
                        bounds.extend(point);
                        dist = point.distanceFrom(polyCenter);
                        var distAtt = ((dist * 3.2808399) / 5280).toFixed(2);
                        var att = [parseFloat(distAtt), feature.attributes["Name"], feature.attributes["Address"], feature.attributes["Routes_Ser"], lat, lng];
                        distArray.push(att);
                    }
                };

                //Sort the return value array
                distArray.sort(function(a, b) { a = a[0]; b = b[0]; return a - b });
                
                // Set up dojox grid
                var model = new dojox.grid.data.Table(null, distArray);

                var view1 = {
                    cells: [
                      [{ name: 'Distance to Lot (mi)', width: '25%' }, { name: 'Lot Name', width: '25%' }, { name: 'Lot Address', width: '25%' }, { name: 'Routes Served', width: '25%' }, { name: 'Lat', width: '0%' }, { name: 'Lng', width: '0%'}]
                    ]
                };
                var layout = [view1];
                gridWidget.setModel(model);
                gridWidget.setStructure(layout);
                document.getElementById('gridDisplay').style.visibility = 'visible';

                // Show the feature when the mouse clicks the corresponding grid row
                dojo.connect(gridWidget, "onRowClick", function(e) {
                    try {
                        mapExtension.removeFromMap(queryOverlays);
                        var name = gridWidget.model.data[e.rowIndex][1];
                        var feature = null;
                        var myResults = null;
                        var myResults1 = null;
                        var myResults2 = null;
                        var attributes = null;
                        var thisAdd = null;
                        var lead = null;
                        var tab1 = null;
                        var tab2 = null;
                        var tab3 = null;
                        var geometry = null;
                        var lat = null;
                        var lng = null;
                        var point = null;
                        for (var i = 0; i < fset.features.length; i++) {
                            feature = fset.features[i];
                            if (name == feature.attributes["Name"]) {
                                myResults = "";
                                attributes = feature.attributes;
                                thisAdd = attributes["Address"].replace("'", "") + ' ' + attributes["City"].replace("'", "") + ',' + attributes["State"];
                                lead = attributes["Lead_Agenc"];
                                var imgURL = attributes["ID"];
                                myResults += "<div id='infoInfo'><br /><b>";
                                myResults += attributes["Name"];
                                myResults += "</b><br />";
                                myResults += "<div id='thumbnail'><a href='";
                                myResults += imagePath + imgURL + ".jpg' target='_blank'>";
                                myResults += "<img src='";
                                myResults += imageThumbPath + imgURL + ".jpg' width=100px height=75px border=0/></a>";
                                myResults += "</div>";
                                myResults += thisAdd;
                                myResults += "<br /><br />Agency: ";
                                myResults += attributes["Lead_Agenc"];
                                myResults += "&nbsp;&nbsp;";
                                if (lead.toUpperCase() == 'METRO') {
                                    myResults += "<a href='http://www.kcata.org' target='_blank'>The Metro</a>";
                                }
                                else if (lead.toUpperCase() == 'JO') {
                                    myResults += "<a href='http://www.thejo.com' target='_blank'>The JO</a>";
                                }
                                myResults += "<br />Bus Routes: ";
                                myResults += attributes["Routes_Ser"];
                                myResults += "<br />Shelter: ";
                                myResults += attributes["Shelter"];
                                myResults += "</div>";
                                tab1 = new GInfoWindowTab("Information", myResults);
                                myResults1 = "";
                                myResults1 += "<div id='infoDir'>Enter your address to see driving <br /> directions to this Park and Ride Location";
                                myResults1 += "<p>Address: <input id='txtToAddress' type='text' />";
                                myResults1 += "<br /> (ex: 600 Broadway Blvd Kansas City MO)</p>";
                                myResults1 += "<input id='btnToAddress' type='button' value='Show Directions'";
                                myResults1 += " onclick=\"showDirections(\'" + thisAdd + "')\" /></p>";
                                myResults1 += "</div>";
                                tab2 = new GInfoWindowTab("Driving", myResults1);
                                myResults2 = "";
                                myResults2 += "<div id='infoTransit'>Transit Options";
                                myResults2 += "<p>Enter Address: <input id='txtToAddressTransit' type='text' /></p>";
                                //myResults2 += "<br /> (ex: 600 Broadway Blvd Kansas City MO)</p>";
                                myResults2 += "<p>Get transit options ";
                                myResults2 += "<a href='' onclick=\"showTransit(\'" + thisAdd + "\',\'FROM\');return false;\">to this lot from the address.</a><br />";
                                myResults2 += "Get transit options ";
                                myResults2 += "<a href='' onclick=\"showTransit(\'" + thisAdd + "\',\'TO\');return false;\">from this lot to the address.</a>";
                                myResults2 += "</p></div>";
                                tab3 = new GInfoWindowTab("Transit", myResults2);
                                lat = gridWidget.model.data[e.rowIndex][4];
                                lng = gridWidget.model.data[e.rowIndex][5];
                                point = new GLatLng(lat, lng);
                                var tabs = [tab1, tab2, tab3];

                                map.openInfoWindowTabsHtml(point, tabs)
                                hideDiv('gridDisplay');
                                break;
                            }
                        }
                    } catch (e) {
                        document.getElementById('errorDetail').innerHTML = "<p>An exception occurred in the script. Error name: " + e.name
                    + ". Error message: " + e.message + "</p>";
                        document.getElementById('error').style.visibility = 'visible';
                    }
                });

                // Highlight the feature when the mouse hovers over the corresponding grid row
                dojo.connect(gridWidget, "onRowMouseOver", function(e) {
                    mapExtension.removeFromMap(queryOverlays);
                    var name = gridWidget.model.data[e.rowIndex][1];
                    for (var i = 0; i < fset.features.length; i++) {
                        var feature = fset.features[i]
                        if (name == feature.attributes["Name"]) {
                            queryOverlays = mapExtension.addToMap(feature);
                        }
                    }
                });
            }

            //Check to see if we are searching by city
            if (document.getElementById('city').style.visibility == 'visible') {
                for (var i = 0; i < fset.features.length; i++) {
                    var feature = fset.features[i]
                    var geometry = fset.features[i].geometry;
                    for (var j = 0; j < geometry.length; j++) {
                        var lat = parseFloat(geometry[j].getLatLng().lat());
                        var lng = parseFloat(geometry[j].getLatLng().lng());
                        var point = new GLatLng(lat, lng);
                        bounds.extend(point);
                        var myResults = "";
                        var attributes = feature.attributes;
                        var thisAdd = attributes["Address"].replace("'", "") + ' ' + attributes["City"].replace("'", "") + ',' + attributes["State"];
                        var lead = attributes["Lead_Agenc"];
                        var imgURL = attributes["ID"];
                        myResults += "<div id='infoInfo'><br /><b>";
                        myResults += attributes["Name"];
                        myResults += "</b><br />";
                        myResults += "<div id='thumbnail'><a href='";
                        myResults += imagePath + imgURL + ".jpg' target='_blank'>";
                        myResults += "<img src='";
                        myResults += imageThumbPath + imgURL + ".jpg' width=100px height=75px border=0/></a>";
                        myResults += "</div>";
                        myResults += thisAdd;
                        myResults += "<br /><br />Agency: ";
                        myResults += attributes["Lead_Agenc"];
                        myResults += "&nbsp;&nbsp;";
                        if (lead.toUpperCase() == 'METRO') {
                            myResults += "<a href='http://www.kcata.org' target='_blank'>The Metro</a>";
                        }
                        else if (lead.toUpperCase() == 'JO') {
                            myResults += "<a href='http://www.thejo.com' target='_blank'>The JO</a>";
                        }
                        myResults += "<br />Bus Routes: ";
                        myResults += attributes["Routes_Ser"];
                        myResults += "<br />Shelter: ";
                        myResults += attributes["Shelter"];
                        myResults += "</div>";
                        var tab1 = new GInfoWindowTab("Information", myResults);
                        var myResults1 = "";
                        myResults1 += "<div id='infoDir'>Enter your address to see driving <br /> directions to this Park and Ride Location";
                        myResults1 += "<p>Address: <input id='txtToAddress' type='text' />";
                        myResults1 += "<br /> (ex: 600 Broadway Blvd Kansas City MO)</p>";
                        myResults1 += "<input id='btnToAddress' type='button' value='Show Directions'";
                        myResults1 += " onclick=\"showDirections(\'" + thisAdd + "')\" /></p>";
                        myResults1 += "</div>";
                        var tab2 = new GInfoWindowTab("Driving", myResults1);
                        var myResults2 = "";
                        myResults2 += "<div id='infoTransit'>Transit Options";
                        myResults2 += "<p>Enter Address: <input id='txtToAddressTransit' type='text' /></p>";
                        //myResults2 += "<br /> (ex: 600 Broadway Blvd Kansas City MO)</p>";
                        myResults2 += "<p>Get transit options ";
                        myResults2 += "<a href='' onclick=\"showTransit(\'" + thisAdd + "\',\'FROM\');return false;\">to this lot from the address.</a><br />";
                        myResults2 += "Get transit options ";
                        myResults2 += "<a href='' onclick=\"showTransit(\'" + thisAdd + "\',\'TO\');return false;\">from this lot to the address.</a>";
                        myResults2 += "</p></div>";
                        var tab3 = new GInfoWindowTab("Transit", myResults2);
                        var infoWindowOptionsTabs = {
                            contentTabs: [{ label: "Information", content: myResults
                            },
                            { label: "Driving", content: myResults1
                            }, { label: "Transit", content: myResults2}], selectedTab: 0
                        };
                        queryOverlays = mapExtension.addToMap(feature, overlayOptions, infoWindowOptionsTabs);
                        cityOverlays.push(queryOverlays);
                    }
                };
            }

            //Setup a maximum zoom level so things are not so tight when one record is searched
            var lvlZoom;
            if (map.getBoundsZoomLevel(bounds) > 15) {
                lvlZoom = 15;
            }
            else {
                lvlZoom = map.getBoundsZoomLevel(bounds);
            }
            map.setZoom(lvlZoom);
            map.setCenter(bounds.getCenter());
            document.getElementById('address').style.visibility = 'hidden';
            document.getElementById('city').style.visibility = 'hidden';
            toggleProgressBar();
        });

        //Setup address query parameters
        query = new esri.arcgis.gmaps.Query();
        query.returnGeometry = true;
        query.outFields = ["Name","Address","City","State","Zip","Routes_Ser","Lead_Agenc","Shelter","ID"];
        
        //Instantiate the geometry object to use when doing a buffer
        gsvc = new esri.arcgis.gmaps.Geometry("http://gis.marc2.org/marcgis/rest/services/Geometry/GeometryServer");
        
        //Listen for GeometryService buffercomplete event
        GEvent.addListener(gsvc, "buffercomplete", function(results) {
            //Construct a 1-dimensional array of polygons to use in the query.queryGeometry.
            var bufferPolys = [];
            for (var x = 0; x < results.geometries.length; x++) {
                for (var y = 0; y < results.geometries[x].length; y++) {
                    bufferPolys.push(results.geometries[x][y]);
                }
            }
            polyCenter = bufferPolys[0].getBounds().getCenter();
            query.queryGeometry = bufferPolys;
            qtask.execute(query);
        });
        
        //Listen for GMap click event
        GEvent.addListener(map, "click", doIdentify);

        //Query for the city,state combinations in the service
        cQuery = new esri.arcgis.gmaps.Query();
        cQuery.returnGeometry = false;
        cQuery.outFields = ["City","State"];
        cQuery.where = "OBJECTID > 0";
        citytask.execute(cQuery,false,addCity);
    }
}

//Function to geocode the address and kick off a buffer operation
function getAddress() {
    if (geocoder) {
        var address = document.getElementById('txtAddress').value;
        geocoder.getLatLng(address, doBuffer);
    }
}

//Function to do a buffer around the geocoded point
function doBuffer(bufPoint) {
    //Buffer parameters
    var buffParams = new esri.arcgis.gmaps.BufferParameters();
    buffParams.unit = esri.arcgis.gmaps.SRUnitType.SURVEY_MILE;
    buffParams.unionResults = true;

    clearMyOverlays();

    //Setup the marker to be displayed
    markerOptions = { icon: BaseIcon, title: 'Your Home', clickable:false }
    bufferMarker = new GMarker(bufPoint,markerOptions);
    map.addOverlay(bufferMarker);

    var buffIndex = document.getElementById('selBuffer');
    var buffDistances = buffIndex.options[buffIndex.selectedIndex].text;
    buffParams.distances = [buffDistances];  //distance in unit type as defined above

    //define buffer geometry to be that of the returned click point
    buffParams.geometries = [bufPoint];
    gsvc.buffer(buffParams);
}

//Function that kicks off an address search
function doSearch() {
    toggleProgressBar();
    clearMyOverlays();
    getAddress();
}

//Function run when a user clicks on the dynamicMap service
function doIdentify(overlay, point) {
    if (overlay) {
        return;
    }
    toggleProgressBar();
    var dim = map.getSize();
    var idparams = new esri.arcgis.gmaps.IdentifyParameters();
    idparams.geometry = point;
    idparams.tolerance = 5;
    idparams.bounds = map.getBounds();
    idparams.width = dim.width;
    idparams.height = dim.height;
    idparams.layerIds = [0];
    idparams.layerOption = "all";

    idtask.execute(idparams, function(response, error) {
        if (error) {
            //do something here
            alert("Error " + error.code + ": " + (error.message || (error.details && error.details.join(" ")) || "Unknown error"));
            toggleProgressBar();
            return;
        }
        idcallback(response, point);
    }
    );
}

//Callback function that runs when the identify has completed
function idcallback(response, point) {
    clearMyOverlays();

    var idResults = response.identifyResults;
    layers = { "0": [] };
    for (var i = 0; i < idResults.length; i++) {
        var result = idResults[i];
        layers[result.layerId].push(result);
    };
    
    //Build the info window that is displayed when the user clicks
    for (var layerId in layers) {
        var results = layers[layerId];
        var myResults = "";
        for (var j = 0; j < results.length; j++) {
            var attributes = results[j].feature.attributes;
            var thisAdd = attributes["Address"].replace("'","") + ' ' + attributes["City"].replace("'","") + ',' + attributes["State"];
            var lead = attributes["Lead_Agenc"];
            myResults += "<div id='infoInfo'><br /><b>";
            myResults += attributes["Name"];
            myResults += "</b><br />";
            myResults += "<div id='thumbnail'><a href='";
            myResults += imagePath + attributes["ID"] + ".jpg' target='_blank'>";
            myResults += "<img src='";
            myResults += imageThumbPath + attributes["ID"] + ".jpg' width=100px height=75px border=0/></a>";
            myResults += "</div>";
            myResults += thisAdd;
            myResults += "<br /><br />Agency: ";
            myResults += attributes["Lead_Agenc"];
            myResults += "&nbsp;&nbsp;";
            if (lead.toUpperCase() == 'METRO') {
                myResults += "<a href='http://www.kcata.org' target='_blank'>The Metro</a>";
            }
            else if (lead.toUpperCase() == 'JO') {
            myResults += "<a href='http://www.thejo.com' target='_blank'>The JO</a>";
            }
            myResults += "<br />Bus Routes: ";
            myResults += attributes["Routes_Ser"];
            myResults += "<br />Shelter: ";
            myResults += attributes["Shelter"];
            myResults += "</div>";            
            var tab1 = new GInfoWindowTab("Information",myResults);
            var myResults1 = "";
            myResults1 += "<div id='infoDir'>Enter your address to see driving <br /> directions to this Park and Ride Location";
            myResults1 += "<p>Address: <input id='txtToAddress' type='text' />";
            myResults1 += "<br /> (ex: 600 Broadway Blvd Kansas City MO)</p>";
            myResults1 += "<input id='btnToAddress' type='button' value='Show Directions'";
            myResults1 += " onclick=\"showDirections('" + thisAdd + "')\" /></p>";
            myResults1 += "</div>";
            var tab2 = new GInfoWindowTab("Driving",myResults1);
            var myResults2 = "";
            myResults2 += "<div id='infoTransit'>Transit Options";
            myResults2 += "<p>Enter Address: <input id='txtToAddressTransit' type='text' /></p>";
            //myResults2 += "<br /> (ex: 600 Broadway Blvd Kansas City MO)</p>";
            myResults2 += "<p>Get transit options ";
            myResults2 += "<a href='' onclick=\"showTransit(\'" + thisAdd + "\',\'FROM\');return false;\">to this lot from the address.</a><br />";
            myResults2 += "Get transit options ";
            myResults2 += "<a href='' onclick=\"showTransit(\'" + thisAdd + "\',\'TO\');return false;\">from this lot to the address.</a>";
            myResults2 += "</p></div>";
            var tab3 = new GInfoWindowTab("Transit",myResults2);
        }
        var tabs = [tab1,tab2,tab3];
    };
    if (myResults.length > 1) {
        map.openInfoWindowTabsHtml(point, tabs);
    }
    toggleProgressBar();
}

//Function that queries the REST service for the city,state pairs
function doCityQuery() {
    toggleProgressBar();
    clearMyOverlays();
    cityQuery = new esri.arcgis.gmaps.Query();
    cityQuery.returnGeometry = true;
    cityQuery.outFields = ["Name", "Address", "City", "State", "Zip", "Routes_Ser", "Lead_Agenc", "Shelter","ID"];
    var selText = document.getElementById('selCitySearch')[document.getElementById('selCitySearch').selectedIndex].text
    var selArray = selText.split(",");
    var city = selArray[0];
    var state = selArray[1];
    cityQuery.where = "City = '" + city.replace("'", "''") + "' AND State = '" + state + "'";
    qtask.execute(cityQuery);
}

//Function to add the city,state results to the combo box
function addCity(result) {
    var comboArray = new Array();
    for (var i = 0; i < result.features.length; i++) {
        var feature = result.features[i];
        var city = feature.attributes["City"];
        var state = feature.attributes["State"];
        var cityText = city + "," + state;
        comboArray.push(cityText);
    }
    var obj = document.getElementById('selCitySearch');
    var cityName = unique(comboArray.sort());
    for (var i = 0; i < cityName.length; i++) {
        obj.options[i] = new Option(cityName[i], i);
    };
}

//Function to find the unique combinations of city,state that were returned from the query
function unique(arrayName) {
    var newArray = new Array();
    var myString;
    for (i = 0; i < arrayName.length; i++) {
        myString = arrayName[i];
        if (newArray.contains(myString) == false) {
            newArray.push(myString);
        }
    }
    return newArray;
}

//Function that shows the driving directions
function showDirections(addFrom) {
    map.getInfoWindow().hide();
    var address = document.getElementById('txtToAddress').value;

    clearMyOverlays();
    directions.load("from: " + address + " to: " + addFrom);
    document.getElementById('directions').style.visibility = "visible";
}

//Function that shows the transit directions
function showTransit(addFrom,direction) {
    var address = document.getElementById('txtToAddressTransit').value;
    clearMyOverlays();
    if (direction == 'TO') {
        var strURL = 'http://maps.google.com/maps?f=d&dirflg=r&saddr=' + addFrom + '&daddr=' + address + '&submit.x=0&submit.y=0&submit=Get+transit+directions&utm_campaign=en&utm_medium=ha&utm_source=en-ha-na-us-gns-trs'
    }
    else {
        var strURL = 'http://maps.google.com/maps?f=d&dirflg=r&saddr=' + address + '&daddr=' + addFrom + '&submit.x=0&submit.y=0&submit=Get+transit+directions&utm_campaign=en&utm_medium=ha&utm_source=en-ha-na-us-gns-trs'
    }
    window.open(strURL);
}

//Function to trap the enter key on the address form (not enabled)
function enterKey(e) {
    var keynum;
    if (window.event) // IE
    {
        keynum = e.keyCode;
    }
    else if (e.which) // Netscape/Firefox/Opera
    {
        keynum = e.which;
    }
    if (keynum == 13) {
        doSearch();
        return false;
    }
}

//Helper function to hide divs
function hideDiv(myDiv) {
    document.getElementById(myDiv).style.visibility = 'hidden';
}

//Helper function to show divs
function showDiv(myDiv, openDiv) {
    //map.clearOverlays();
    clearMyOverlays();
    if (openDiv == 'Find') {
        document.getElementById('address').style.left = '170px';
        hideDiv('city');
    }
    if (myDiv == 'city') {
        hideDiv('address');
    }
    document.getElementById(myDiv).style.visibility = 'visible';
}

//Helper functions to handle the Search button actions
function changeAddressBtn() {
    document.getElementById('imgAddress').src = 'images/btnSearchOff.png';
}
function changeAddressBack() {
    document.getElementById('imgAddress').src = 'images/btnSearchOn.png';
}
function changeCityBtn() {
    document.getElementById('imgCity').src = 'images/btnSearchOff.png';
}
function changeCityBack() {
    document.getElementById('imgCity').src = 'images/btnSearchOn.png';
}

//Function to add the ArcServer service to the map
function addDynamicMap() {
    //Setup the ArcGIS service for lots
    var mapIMGParams = new esri.arcgis.gmaps.ImageParameters();
    mapIMGParams.format = 'gif';
    dynamicMap = new esri.arcgis.gmaps.DynamicMapServiceLayer("http://gis.marc2.org/marcgis/rest/services/ParkAndRide/MapServer", mapIMGParams, 100, null);

    GEvent.addListener(dynamicMap, "load", function(groundov) {
        map.addOverlay(groundov);
    });
}

//Function to reset the map to its original state
function resetMap() {
    map.clearOverlays();
    map.closeInfoWindow();
    map.setCenter(new GLatLng(38.95, -94.44), 9);
    addDynamicMap();
}

//Function to clear the map of anything we added previously
function clearMyOverlays() {
    mapExtension.removeFromMap(queryOverlays);
    mapExtension.removeFromMap(cityOverlays);
    map.closeInfoWindow();
    if (addressMarker) {
        map.removeOverlay(addressMarker);
    }
    if (bufferMarker) {
        map.removeOverlay(bufferMarker);
    }
    directions.clear();
}

//Function to toggle the progress div to show things are working
function toggleProgressBar() {
    var progressbar_container = dojo.byId("progressbar_container");

    if (progressbar_container.style.display == "block") {
        progressbar_container.style.display = "none";
    } else {
        progressbar_container.style.display = "block";
    }
}


