﻿dojo.require("dojo.parser");
dojo.require("dijit.dijit");
dojo.require("dijit.layout.BorderContainer");
dojo.require("dijit.Dialog");
dojo.require("dijit.layout.ContentPane");
dojo.require("dojo.data.ItemFileReadStore");
dojo.require("dijit.layout.TabContainer");
dojo.require("dijit.form.ComboBox");
dojo.require("dijit.form.Button");
dojo.require("dijit.form.CheckBox");
dojo.require("dojo.cookie");
/*dojo.require("dojox.grid.DataGrid");*/
dojo.require("dojo.io.script");
dojo.require("esri.dijit.Scalebar");

//version 2.7.0
dojo.require("esri.map");

dojo.declare("my.fsaLayer", esri.layers.DynamicMapServiceLayer, {
    constructor: function () {
        this.initialExtent = this.fullExtent = new esri.geometry.Extent({ "xmin": 380425.190770931, "ymin": 4906135.56930647, "xmax": 577580.229321643, "ymax": 5036910.32510176, "spatialReference": { "wkid": 26915} });
        this.spatialReference = new esri.SpatialReference({ wkid: 26915 });

        this.loaded = true;
        this.onLoad(this);
        this.visible = false;
    },

    getImageUrl: function (extent, width, height, callback) {
        var params = {
            request: "GetMap",
            transparent: true,
            format: "image/jpeg",
            bgcolor: "ffffff",
            version: "1.1.1",
            //version: "1.3.0",
            layers: "mncomp",
            styles: "default,default",
            exceptions: "application/vnd.ogc.se_xml",

            //changing values
            bbox: extent.xmin + "," + extent.ymin + "," + extent.xmax + "," + extent.ymax,
            srs: "EPSG:26915",
            width: width,
            height: height
        };

        callback("http://geoint.lmic.state.mn.us/cgi-bin/mncomp?" + dojo.objectToQuery(params));
    }
});
var myMap, basemap, hybrid, satlayer, busRoutesMapLayer, initExtent, zoomext, mout, mover, iWindow, onclickconn, mapclick, prlyr, nodelyr, stoplyr, routelyr, blueStopSymb, redStopSymb, grayStopSymb, routeStore, TTsignlyr, TTlyr, niceRidelyr, hourcarlyr, signvis, ttSignConn, ttConn, millDiff, gclayer, GoToCardLyr;

//detect ie 6 and redirect
if (dojo.isIE && dojo.isIE < 7) {
    window.location = "/map/BrowserUpgrade.htm";
}
 //var busrefresh;
//Users time - close to beginning. We are trying to get this nearly at the same time we get the server's time via .NET page load.
//assigning the millDiff variable here works with the simple Response.write javascript creation in the page behind
//Also this will get the server time and client time as close together as possible. The more complicated
//RegisterClientSide Script in the page behind will have less compatability issues with update panels.
//It also doesn't execute until after the DOM is fully loaded. This application does not use update panels.
//If timing issues are raised, switch to the simpler response.write, and uncomment the millDiff code below.

////Calculate the difference (returns milliseconds)
//var timeLocal = new Date();
//millDiff = timeLocal - timeServer;

//var timeServer = new Date('2/10/2010 8:51:01 AM');

function killlisteners() {
    //mover = mouse over
    //mout = mouse out
    if (typeof (mover) !== "undefined") {
        dojo.disconnect(mover);
    }
    if (typeof (mout) !== "undefined") {
        dojo.disconnect(mout);
    }
    if (typeof (iWindow) !== "undefined") {
        //console.log("kill iWindow");
        dojo.disconnect(iWindow);
    }
    if (typeof (onclickconn) !== "undefined") {
        //console.log("disconnect onlcickconn");
        dojo.disconnect(onclickconn);
    }
    if (typeof (ttSignConn) !== "undefinded") {
        dojo.disconnect(ttSignConn);
    }
    if (typeof (ttConn) !== "undefinded") {
        dojo.disconnect(ttSignConn);
    }
}

function killMapClick() {
    //Kills the listener for map clicks which launch the route identification function.
    dojo.disconnect(mapclick);
    mapclick = null;
}

function listenMapClick() {
    //Enables listener to detect map clicks and identify routes underneath map click. Should be disabled when a user clicks on a stop.
    //if mapclick is nothing then recreate mapclick
    if (mapclick != null) {
        //console.log("mapclick is simply not null");
        //mapclick = dojo.connect(myMap, "onClick", idRoutes);
    }
    else if(mapclick == null) {
        mapclick = dojo.connect(myMap, "onClick", idRoutes);
    }
    
}

function drawGoToCards(){
    //Get GoToCard Locations
    var Go2qt = new esri.tasks.QueryTask("http://gis2.metc.state.mn.us/ArcGIS/rest/services/transit/TIM_Points/MapServer/2");
    var Go2query = new esri.tasks.Query();
    Go2query.geometry = myMap.extent;
    Go2query.returnGeometry = true;
    Go2query.spatialRelationship = esri.tasks.Query.SPATIAL_REL_INTERSECTS;
    Go2query.outFields = ["Name", "Location", "City"];
    Go2query.where = "";

    var Go2symb = new esri.symbol.PictureMarkerSymbol('images/Go-To_icon.png', 20, 20);
    var Go2InfoTemplate = new esri.InfoTemplate();
    Go2InfoTemplate.setTitle("<a href=\"http://metrotransit.org/go-to-card.aspx\" target=\"_blank\">Go-To Card Retailer</a>");
    Go2InfoTemplate.setContent("${Name}<br/>" + "${Location}");
    dojo.connect(Go2qt, "onComplete", function(featureSet) {
        dojo.forEach(featureSet.features, function(feature) {
            var graphic = feature;
            graphic.setSymbol(Go2symb);
            //graphic.setInfoTemplate(Go2InfoTemplate);
            GoToCardLyr.add(graphic);
        });
        var Go2clickconn = dojo.connect(GoToCardLyr, "onClick", function(evt) {
            //suppress routeid
            killMapClick();
            var G2 = evt.graphic;
            var g2name = G2.attributes.Name;
            var g2loc = G2.attributes.Location;
            var g2City = G2.attributes.City;
            var g2zip = G2.attributes.Zipcode;
            var content, title, facid, thewidth, infoheight, infowidth;
            var UTMX = G2.geometry.x;
            var UTMY = G2.geometry.y;
            content="<div class=\"popup\">";
            content = content + g2name + "<br/>" + g2loc + ", " + g2City;
            var tripplanstring = "<div class=\"pfooter\"><b>Plan a transit trip:</b>&nbsp<a href=\"/TripPlanner/Default.aspx?s-dest=%26lt%3b" + escape(g2name) + "%26gt%3b+%23+" + escape(g2name) + " Park and Ride%7c" + escape(g2loc) + "%7c" + UTMY + "%7c" + UTMX + "%7c%7c%7c%7c0%7c0%7c0%7c0%7cStop%7c0\" target=\"_blank\">To here</a> | " + "<a href=\"/TripPlanner/Default.aspx?s-orig=%26lt%3b" + escape(g2name) + "%26gt%3b+%23+" + escape(g2name) + " Park and Ride%7c" + escape(g2loc) + "%7c" + UTMY + "%7c" + UTMX + "%7c%7c%7c%7c0%7c0%7c0%7c0%7cStop%7c0\" target=\"_blank\">From here</a></div>";
            content = content + tripplanstring + "</div>";
            myMap.infoWindow.resize(290, 135);
            myMap.infoWindow.setContent(content);
            myMap.infoWindow.setTitle("<div class=\"prTitle\"><a href=\"http://metrotransit.org/go-to-card.aspx\" target=\"_blank\">Go-To Card Retailer</a></div>");
            myMap.infoWindow.show(evt.screenPoint, myMap.getInfoWindowAnchor(evt.screenPoint));
            setTimeout("listenMapClick()", 500);
        });
    });
    Go2qt.execute(Go2query);
}
function hourcarFunc() {
    //get hourcar json data from Data/hourcarlocations.json
    //convert lat/lon to UTM
    //symbolize as graphics
    var i, len;
    for (i = 0, len = hourcarstations.Stations.length; i < len; ++i) {
                var theStation = hourcarstations.Stations[i];
                var utmXY = new Array(2);
                LatLonToUTMXY(DegToRad(parseFloat(theStation.lat)), DegToRad(parseFloat(theStation.long)), 15, utmXY);
                var point = new esri.geometry.Point(utmXY[0], utmXY[1]);
                var hourcarsymbol;
                var attr = { "id": theStation.id, "name": theStation.name };
                hourcarsymbol = new esri.symbol.PictureMarkerSymbol('images/hourcar.png', 47, 16);

                //esri.Graphic(geometry, symbol, attributes, infoTemplate)
                var hourcarTitle = "<div class=\"popup\"><div class=\"cTitle\">${name}</div>";
                var hourcarlink = "<br/><br/><a href=\"http://www.hourcar.org/\" target=\"_blank\">hourcar.org</a>";
                var hourcarcontent = hourcarTitle + hourcarlink + "</div>";
                //var infoTemplate = new esri.InfoTemplate("<div class=\"pTitle\">HOURCAR Hub</div>", hourcarcontent);
                var hcInfoTemp = new esri.InfoTemplate();
                hcInfoTemp.content = hourcarcontent;
                hcInfoTemp.title = "<div class=\"pTitle\">HOURCAR Hub</div>";
                var graphic = new esri.Graphic(point, hourcarsymbol, attr, hcInfoTemp);
                hourcarlyr.add(graphic);
    }
    var hconclickconn = dojo.connect(hourcarlyr, "onClick", function(evt) {
        myMap.infoWindow.resize(200, 150);
        myMap.infoWindow.show(evt.screenPoint, myMap.getInfoWindowAnchor(evt.screenPoint));
    });
}
function nicerideFunc() {
    //get NiceRide json data from Data/NiceRideStations.json
    //convert lat/lon to UTM
    //symbolize as graphics
    //add to niceridelyr
    var i, len;
    for (i = 0, len = niceridestations.Stations.length; i < len; ++i) {
        var theStation = niceridestations.Stations[i];

        var utmXY = new Array(2);
        LatLonToUTMXY(DegToRad(parseFloat(theStation.lat)), DegToRad(parseFloat(theStation.long)), 15, utmXY);
        var point = new esri.geometry.Point(utmXY[0], utmXY[1]);
        var bikesymbol;
        var attr = { "id": theStation.id, "name": theStation.name };
        var niceRideTitle = "<div class=\"popup\"><div class=\"cTitle\">${name}</div>";
        var niceridelink = "<br/><br/><a href=\"http://www.niceridemn.org/\" target=\"_blank\">niceridemn.org</a>";
        var niceRidecontent = niceRideTitle + niceridelink + "</div>";
        //var infoTemplate = new esri.InfoTemplate("<div class=\"pTitle\">Nice Ride Station</div>", niceRidecontent);
        var nrInfoTemp = new esri.InfoTemplate();
        nrInfoTemp.content = niceRidecontent;
        nrInfoTemp.title = "<div class=\"pTitle\">Nice Ride Station</div>";
        if (theStation.installed == "true" && theStation.locked == "false" && theStation.temporary == "false") {
            //                The green in service marker would be displayed when the XML looks like this:
            //                    <installed>true</installed>
            //                    <locked>false</locked>
            //                    <temporary>false</temporary>
            //var sms = new esri.symbol.SimpleMarkerSymbol().setStyle(esri.symbol.SimpleMarkerSymbol.STYLE_SQUARE).setColor(new dojo.Color([255,0,0,0.5]));
            bikesymbol = new esri.symbol.PictureMarkerSymbol('images/NiceRideGreen.png', 20, 16);
            var graphic = new esri.Graphic(point, bikesymbol, attr, nrInfoTemp);
            niceRidelyr.add(graphic);
        } else if (theStation.installed == "true" && theStation.locked == "true" && theStation.temporary == "false") {
            //                The red out of service marker is displayed when the station is in place on the street but all bikes are locked and not available for rental:
            //                    <installed>true</installed>
            //                    <locked>true</locked>
            //                    <temporary>false</temporary>
            bikesymbol = new esri.symbol.PictureMarkerSymbol('images/NiceRideRed.png', 20, 16);
        } else if (theStation.installed == "true" && theStation.locked == "false" && theStation.temporary == "true") {
            //                Yellow special event, used to show a temporary installation ( we've never done this and so far have no plans to )
            //                    <installed>true</installed>
            //                    <locked>false</locked>
            //                    <temporary>true</temporary>
            bikesymbol = new esri.symbol.PictureMarkerSymbol('images/NiceRideYellow.png', 20, 16);
            var graphic = new esri.Graphic(point, bikesymbol, attr, infoTemplate);
            niceRidelyr.add(graphic);
        } else if (theStation.installed == "false" && theStation.locked == "false" && theStation.temporary == "false") {
            //                The gray marker is displayed if the stations is not physically on the street, for example in the off season:
            //                    <installed>false</installed>
            //                    <locked>false</locked>
            //                    <temporary>false</temporary>
            bikesymbol = new esri.symbol.PictureMarkerSymbol('images/NiceRideGray.png', 20, 16);
        }
     }
     var nronclickconn = dojo.connect(niceRidelyr, "onClick", function(evt) {
        myMap.infoWindow.resize(200, 150);
        myMap.infoWindow.show(evt.screenPoint, myMap.getInfoWindowAnchor(evt.screenPoint));
    });
}

function refreshMap() {
    killlisteners();
    var currentRoute;
    var mapLevel = myMap.getLevel();
    if (dojo.byId("hidroute").value !== "") {
        currentRoute = dojo.byId("hidroute").value;
    }
    switch (mapLevel) {
        case 0:
            if (prlyr !== undefined) {
                prlyr.hide();
            }
            if (nodelyr !== undefined) {
                nodelyr.hide();
            }
            if (TTsignlyr !== undefined) {
                TTsignlyr.hide();
            }
            if (stoplyr !== undefined) {
                stoplyr.clear();
            }
            if (niceRidelyr !== undefined) {
                niceRidelyr.clear();
            }
            if (hourcarlyr !== undefined) {
                hourcarlyr.clear();
            }
            if (GoToCardLyr !== undefined) {
                GoToCardLyr.clear();
            }
            break;
        case 1:
            //myMap.addLayer(prlyr);
            prlyr.show();
            nodelyr.show();
            drawTTSigns();
            stoplyr.clear();
            niceRidelyr.clear();
            hourcarlyr.clear();
            if (GoToCardLyr !== undefined) {
                GoToCardLyr.clear();
            }
            break;
        case 2:
            //myMap.addLayer(prlyr);
            prlyr.show();
            nodelyr.show();
            drawTTSigns();
            stoplyr.clear();
            niceRidelyr.clear();
            hourcarlyr.clear();
            if (GoToCardLyr !== undefined) {
                GoToCardLyr.clear();
            }
            break;
        case 3:
            //myMap.addLayer(prlyr);
            prlyr.show();
            nodelyr.show();
            stoplyr.clear();
            drawTTSigns();
            niceRidelyr.clear();
            hourcarlyr.clear();
            if (GoToCardLyr !== undefined) {
                GoToCardLyr.clear();
            }
            break;
        case 4:
            prlyr.show();
            nodelyr.show();
            stoplyr.clear();
            drawTTSigns();
            niceRidelyr.clear();
            hourcarlyr.clear();
            if (GoToCardLyr !== undefined) {
                GoToCardLyr.clear();
            }
            break;
        case 5:
            prlyr.show();
            nodelyr.show();
            stoplyr.clear();
            niceRidelyr.clear();
            hourcarlyr.clear();
            if (GoToCardLyr !== undefined) {
                GoToCardLyr.clear();
            }
            //drawTTSigns(5);
            //Draw travel time signs
            if (TTsignlyr !== undefined) {
                drawTTSigns();
            } else {
                signvis = true;
                drawTTSigns();
            }
            break;
        case 6:
            prlyr.show();
            
            nodelyr.hide();
            niceRidelyr.clear();
            hourcarlyr.clear();
            if (GoToCardLyr !== undefined) {
                GoToCardLyr.clear();
            }
            if (dojo.isIE) {
                //console.info("IE");
                stoplyr.clear();
            }
            else {
                busstopFunc();
            }
            //Draw travel time signs
            if (TTsignlyr !== undefined) {
                drawTTSigns();
            } else {
                signvis = true;
                drawTTSigns();
            }
            break;
        case 7:
            prlyr.show();
            nodelyr.hide();
            nicerideFunc();
            hourcarFunc();
            busstopFunc();
            drawGoToCards();
            //Draw travel time signs
            if (TTsignlyr !== undefined) {
                drawTTSigns();
            } else {
                signvis = true;
                drawTTSigns();
            }
            break;
        case 8:
            prlyr.show();
            
            nodelyr.hide();
            nicerideFunc();
            hourcarFunc();
            busstopFunc();
            drawGoToCards();
            //Draw travel time signs
            if (TTsignlyr !== undefined) {
                drawTTSigns();
            } else {
                signvis = true;
                drawTTSigns();
            }
            break;
        case 9:
            prlyr.show();
            nodelyr.hide();
            nicerideFunc();
            hourcarFunc();
            busstopFunc();
            drawGoToCards();
            //Draw travel time signs
            if (TTsignlyr !== undefined) {
                drawTTSigns();
            } else {
                signvis = true;
                drawTTSigns();
            }
            break;
        default:
            //console.log("Case not found");
            break;
        }

        //if (currentRoute !== undefined) {
            //loadBusData(dojo.byId("hidroute").value);
            //clearInterval(busrefresh)
            //busrefresh = setInterval("refreshCurrent(" + dojo.byId("hidroute").value + ")", 30000);
        //}
    } 

function sortRouteArray(routes) {
    var routesLen = routes.length;
    if (routesLen < 2) {
        return routes;
    }   
    else {
        var sortRoutes;
        sortRoutes = routes;
        sortRoutes.sort(function(a, b) {
                //("sortRouteArray: " + "a zero " + a);
                //("sortRouteArray: " + "b zero " + b);
                return a - b;
        });
        //Array now becomes [7, 8, 25, 41]
        routes = sortRoutes;
    }
    return routes;
}


function buildPRInfoWindow(evt) {
    //("Build PR Info Window");
    //ParkRideQuery.outFields = ["PR_NUM", "NAME", "DESCRIPT", "CITY", "ROUTE_DIR", "CAPACITY"];
    var pr = evt.graphic;
    var prname = pr.attributes.NAME;
    var prdesc = pr.attributes.DESCRIPT;
    var prcity = pr.attributes.CITY;
    
    var prcap = pr.attributes.CAPACITY;
    var content, title, facid, thewidth, infoheight, infowidth;
    var UTMX = pr.geometry.x;
    var UTMY = pr.geometry.y;
    //var sLat, sLon;
    var prediv = "<div class=\"popup\">";  //.popup .footer"
    var postdiv = "</div>";
    //var llXY = new Array(2);
    //var zig2 = new UTMXYToLatLon(UTMX, UTMY, 15, false, llXY);
    content = prediv;
    var routes;
    if (pr.attributes.ROUTE_DIR !== "") {
        routes = pr.attributes.ROUTE_DIR.split(",");

    }
    else {
        routes = "";
    }
    
    var tripplanstring = "<div class=\"pfooter\"><b>Plan a transit trip:</b>&nbsp<a href=\"/TripPlanner/Default.aspx?s-dest=%26lt%3b" + escape(prname) + "%26gt%3b+%23+" + escape(prname) + " Park and Ride%7c" + escape(prcity) + "%7c" + UTMY + "%7c" + UTMX + "%7c%7c%7c%7c0%7c0%7c0%7c0%7cStop%7c0\" target=\"_blank\">To here</a> | " + "<a href=\"/TripPlanner/Default.aspx?s-orig=%26lt%3b" + escape(prname) + "%26gt%3b+%23+" + escape(prname) + " Park and Ride%7c" + escape(prcity) + "%7c" + UTMY + "%7c" + UTMX + "%7c%7c%7c%7c0%7c0%7c0%7c0%7cStop%7c0\" target=\"_blank\">From here</a></div>";
    //Trip planner string
    //var tripplanstring = "<b>Plan a transit trip:</b>&nbsp<a href=\"http://metrotransit.org/TripPlanner/Default.aspx?s-dest=%26lt%3b" + escape(prname) + "%26gt%3b+%23+" + escape(prname) + " Park and Ride%7c" + escape(prcity) + "%7c" + UTMY + "%7c" + UTMX + "%7c%7c%7c%7c0%7c0%7c0%7c0%7cStop%7c0\" target=\"_blank\">To here</a> | " + "<a href=\"http://metrotransit.org/TripPlanner/Default.aspx?s-orig=%26lt%3b" + escape(prname) + "%26gt%3b+%23+" + escape(prname) + " Park and Ride%7c" + escape(prcity) + "%7c" + UTMY + "%7c" + UTMX + "%7c%7c%7c%7c0%7c0%7c0%7c0%7cStop%7c0\" target=\"_blank\">From here</a></div>";
    //var drivedir = "<b>Driving directions:</b><a href=\"http://maps.google.com/maps?f=d&source=s_d&saddr=&daddr=" + RadToDeg(llXY[0]) + "," + RadToDeg(llXY[1]) + "&ie=UTF8&ll=" + RadToDeg(llXY[0]) + "," + RadToDeg(llXY[1]) + "&z=12&mrsp=0\" target=\"_blank\">To here</a>";
    //console.log(drivedir);
    var prtextprefix = "<div class=\"PA\"><span class=\"LotStatus\">LOT STATUS: </span><img class=\"PRAvail\" src=\"ParkingAvailabilityImage.ashx?facid=";
    var prtextsuffix = "\" /></div>";
    //217 = Blaine = Parking avail. facility ID 1
    //555 = Kenrick/Lakeville = Parking avail. facility ID 3
    //710 = Burnsville = Parking avail. facility ID 4
    //1040 = Roseville = Parking avail. facility ID 2
    switch (pr.attributes.PR_NUM) {
    case 217:
        facid = 1;
        //content = content + "<b>LOT STATUS: <img src=\"ParkingAvailabilityImage.ashx?facid=1\" />"
        break;
    case 555:
        facid = 3;
        //content = content + "<b>LOT STATUS: <img src=\"ParkingAvailabilityImage.ashx?facid=2\" />"
        break;
    case 710:
        facid = 4;
        //content = content + "<b>LOT STATUS: <img src=\"ParkingAvailabilityImage.ashx?facid=3\" />"
        break;
    case 1040:
        facid = 2;
        break;
    //content = content + "<b>LOT STATUS: <img src=\"ParkingAvailabilityImage.ashx?facid=4\" />" 
    default:
        facid = -99;
        break;
    }

    if (facid > 0) {
        content = content + prdesc + "<br/>" + prtextprefix + facid + prtextsuffix;
        title = prname;
        infoheight = 105;
        infowidth = 300;
    }
    else {
        title = "Park and Ride";
        if (prname === prdesc) {
            //console.log("Name is the same as description");
            content = content + "<b>" + prdesc + "</b>";
            thewidth = prdesc.length;
            infoheight = 100;
            //prname = "";
        }
        else {
            content = content + "<b>" + prname + "</b><br/>" + prdesc;
            if (prdesc.length > prname.length) {
                thewidth = prdesc.length;
            }
            else {
                thewidth = prname.length;
            }
            infoheight = 115;
        }
        //console.log("thewidth: " + thewidth * 8);
        //resize infoWindow
        if (thewidth * 8 > 300) {
            infowidth = thewidth * 8;
        }
        else {
            infowidth = 300;
        }

        if (infowidth > 400) {
            infowidth = 400;
            infoheight = infoheight + 18;
        }

    }
    //Add routes and directions
    
    
    content = content + tripplanstring + "</div>";
    myMap.infoWindow.resize(infowidth, infoheight);
    myMap.infoWindow.setContent(content);
    myMap.infoWindow.setTitle("<div class=\"prTitle\">" + title + "</div>");
    //Build info window


}

function buildInfoWindow(evt) {
    //determine layer?
    ﻿var stopurls = {"17874":["Warehouse District Hennepin Ave Station","/warehouse-district-hennepin-station.aspx"],"17875":["Warehouse District Hennepin Ave Station","/warehouse-district-hennepin-station.aspx"],"17976":["ride free on nicollet mall","/ride-free-on-nicollet-mall.aspx"],"17978":["ride free on nicollet mall","/ride-free-on-nicollet-mall.aspx"],"17980":["ride free on nicollet mall","/ride-free-on-nicollet-mall.aspx"],"17982":["ride free on nicollet mall","/ride-free-on-nicollet-mall.aspx"],"17984":["ride free on nicollet mall","/ride-free-on-nicollet-mall.aspx"],"17986":["ride free on nicollet mall","/ride-free-on-nicollet-mall.aspx"],"17990":["ride free on nicollet mall","/ride-free-on-nicollet-mall.aspx"],"17992":["ride free on nicollet mall","/ride-free-on-nicollet-mall.aspx"],"17994":["ride free on nicollet mall","/ride-free-on-nicollet-mall.aspx"],"17996":["ride free on nicollet mall","/ride-free-on-nicollet-mall.aspx"],"17997":["ride free on nicollet mall","/ride-free-on-nicollet-mall.aspx"],"17988":["ride free on nicollet mall","/ride-free-on-nicollet-mall.aspx"],"1920":["ride free on nicollet mall","/ride-free-on-nicollet-mall.aspx"],"19250":["ride free on nicollet mall","/ride-free-on-nicollet-mall.aspx"],"19327":["ride free on nicollet mall","/ride-free-on-nicollet-mall.aspx"],"41911":["ride free on nicollet mall","/ride-free-on-nicollet-mall.aspx"],"51405":["Mall of America Station","/mall-of-america-station.aspx"],"51408":["Nicollet Mall Station","/nicollet-mall-station.aspx"],"51409":["Government Plaza Station","/government-plaza-station.aspx"],"51410":["Metrodome Station","/metrodome-station.aspx"],"51411":["Cedar Riverside Station","/cedar-riverside-station.aspx"],"51412":["Franklin Ave Station","/franklin-station.aspx"],"51413":["Lake Street Station","/lake-street-station.aspx"],"51414":["38th Street Station","/38th-street-station.aspx"],"51415":["46th Street Station","/46th-street-station.aspx"],"51416":["50th Street Station","/50th-street-station.aspx"],"51417":["VA Medical Center Station","/va-medical-center-station.aspx"],"51418":["Fort Snelling Station","/fort-snelling-station.aspx"],"51419":["Airport Term 1","/lindbergh-station.aspx"],"51420":["Airport Term 2","/hubert-humphrey-station.aspx"],"51421":["Bloomington Central Station","/bloomington-central-station.aspx"],"51422":["28th Ave Station","/28th-avenue-station.aspx"],"51423":["Nicollet Mall Station","/nicollet-mall-station.aspx"],"51424":["Government Plaza Station","/government-plaza-station.aspx"],"51425":["Metrodome Station","/metrodome-station.aspx"],"51426":["Cedar Riverside Station","/cedar-riverside-station.aspx"],"51427":["Franklin Ave Station","/franklin-station.aspx"],"51428":["Lake Street Station","/lake-street-station.aspx"],"51429":["38th Street Station","/38th-street-station.aspx"],"51430":["46th Street Station","/46th-street-station.aspx"],"51431":["50th Street Station","/50th-street-station.aspx"],"51432":["VA Medical Center Station","/va-medical-center-station.aspx"],"51433":["Fort Snelling Station","/fort-snelling-station.aspx"],"51434":["Airport Term 1","/lindbergh-station.aspx"],"51435":["Airport Term 2","/hubert-humphrey-station.aspx"],"51436":["Bloomington Central Station","/bloomington-central-station.aspx"],"51437":["28th Ave Station","/28th-avenue-station.aspx"],"52320":["ride free on nicollet mall","/ride-free-on-nicollet-mall.aspx"],"53220":["Target Field","/target-field.aspx"],"53221":["Target Field","/target-field.aspx"],"53279":["American Blvd Station","/american-boulevard-station.aspx"],"53280":["American Blvd Station","/american-boulevard-station.aspx"],"53287":["MARQUETTE & WASHINGTON - STOP A","/marquette-and-2nd-avenues.aspx"],"53288":["MARQUETTE AV & 4 ST - STOP A","/marquette-and-2nd-avenues.aspx"],"53289":["MARQUETTE AV & 6 ST - STOP A","/marquette-and-2nd-avenues.aspx"],"53290":["MARQUETTE AV & 8 ST - STOP A","/marquette-and-2nd-avenues.aspx"],"53291":["MARQUETTE AV & 10 ST - STOP A","/marquette-and-2nd-avenues.aspx"],"53292":["Marquette and Second Ave","/marquette-and-2nd-avenues.aspx"],"53293":["Marquette and Second Ave","/marquette-and-2nd-avenues.aspx"],"53294":["Marquette and Second Ave","/marquette-and-2nd-avenues.aspx"],"53295":["Marquette and Second Ave","/marquette-and-2nd-avenues.aspx"],"53296":["Marquette and Second Ave","/marquette-and-2nd-avenues.aspx"],"53297":["MARQUETTE AV & 3 ST - STOP C","/marquette-and-2nd-avenues.aspx"],"53298":["MARQUETTE AV & 5 ST - STOP C","/marquette-and-2nd-avenues.aspx"],"53299":["MARQUETTE AV & 7 ST - STOP C","/marquette-and-2nd-avenues.aspx"],"53300":["MARQUETTE AV & 9 ST - STOP C","/marquette-and-2nd-avenues.aspx"],"53301":["MARQUETTE AV & 11 ST - STOP C","/marquette-and-2nd-avenues.aspx"],"53302":["Marquette and Second Ave","/marquette-and-2nd-avenues.aspx"],"53303":["Marquette and Second Ave","/marquette-and-2nd-avenues.aspx"],"53304":["Marquette and Second Ave","/marquette-and-2nd-avenues.aspx"],"53305":["Marquette and Second Ave","/marquette-and-2nd-avenues.aspx"],"53306":["2 AV S & 12 ST - STOP E","/marquette-and-2nd-avenues.aspx"],"53307":["2 AV S & 10 ST - STOP E","/marquette-and-2nd-avenues.aspx"],"53308":["2 AV S & 8 ST - STOP E","/marquette-and-2nd-avenues.aspx"],"53309":["2 AV S & 6 ST - STOP E","/marquette-and-2nd-avenues.aspx"],"53310":["2 AV S & 4 ST - STOP E","/marquette-and-2nd-avenues.aspx"],"53311":["Marquette and Second Ave","/marquette-and-2nd-avenues.aspx"],"53312":["Marquette and Second Ave","/marquette-and-2nd-avenues.aspx"],"53313":["Marquette and Second Ave","/marquette-and-2nd-avenues.aspx"],"53314":["Marquette and Second Ave","/marquette-and-2nd-avenues.aspx"],"53315":["2 AV S & 11ST - STOP G","/marquette-and-2nd-avenues.aspx"],"53316":["2 AV S & 9 ST - STOP G","/marquette-and-2nd-avenues.aspx"],"53317":["2 AV S & 7 ST - STOP G","/marquette-and-2nd-avenues.aspx"],"53318":["2 AV S & 5 ST - STOP G","/marquette-and-2nd-avenues.aspx"],"53319":["Marquette and Second Ave","/marquette-and-2nd-avenues.aspx"],"53320":["Marquette and Second Ave","/marquette-and-2nd-avenues.aspx"],"53321":["Marquette and Second Ave","/marquette-and-2nd-avenues.aspx"],"53342":["Target Field","/target-field.aspx"],"53343":["Fridley Station","/fridley-station.aspx"],"53344":["Coon Rapids Riverdale Station","/coon-rapids-riverdale-station.aspx"],"53345":["Anoka Station","/anoka-station.aspx"],"53346":["Elk River Station","/elk-river-station.aspx"],"53347":["Big Lake Station","/big-lake-station.aspx"],"53349":["Elk River Station","/elk-river-station.aspx"],"53350":["Anoka Station","/anoka-station.aspx"],"53351":["Coon Rapids Riverdale Station","/coon-rapids-riverdale-station.aspx"],"53352":["Fridley Station","/fridley-station.aspx"]};
    var routes, nodestring;
    var busstops = evt.graphic;
    var atts = busstops.attributes;
    var siteon = atts.site_on;
    var siteat = atts.site_at;
    var nodeid = atts.node_id;
    var CTU_NAME = atts.city_id;
    var UTMX = busstops.geometry.x;
    var UTMY = busstops.geometry.y;
    var siteID = atts.siteid;
    var siteLoc = siteon + " & " + siteat; 
    //$("#nextripstop").html(siteLoc);
    dojo.byId("nextripstop").innerHTML = siteLoc;
    dojo.byId("nextripstopnumber").innerHTML = "Stop Number " + siteID;
    //if siteID is found in the stopurls oboject then make it a hyper link.
    if (stopurls[siteID]){
        siteLoc = "<a href=\"" + stopurls[siteID][1] + "\" target=\"_blank\">" + siteLoc + "</a>";
    }
    //if siteLoc contains "Target Field" then make it a hyper link.
    //if (siteLoc.indexOf("TARGET FIELD") > -1) {
        //siteLoc = "<a href=\"/target-field.aspx\" target=\"_blank\">" + siteLoc + "</a>";
    //}
    var routestring;

    if (atts.ROUTEDIRS !== "") {
        routes = atts.ROUTEDIRS.split(",");
    }
    else {
        routes = "";
    }

    var sortRoutes=[];
  
    for (var i = 0, len = routes.length; i < len; ++i) {
        sortRoutes[i] = routes[i].split(":");
    }
    if (routes.length > 1) {    
        sortRoutes.sort(function(a, b) {
            //console.log("a zero " + a[0]);
            //console.log("b zero " + b[0]);
            return a[0] - b[0];
        });
    }     //Array now becomes [7, 8, 25, 41]
    for (i = 0, len = routes.length; i < len; ++i) {
        routes[i] = sortRoutes[i].join(":");
    }
    //routes.sort(function(a, b) { return a - b }) //Array now becomes [7, 8, 25, 41]
    //routes.sort();

    var infoheight, infowidth;
    //resize infoWindow - ! Large infowindows will go off the screen.
    //maximum height 250
    //maximum width 300
    //minumum height 200

    infowidth = 250;
    infoheight = 200;
    //Build info window
    var content = "<div class=\"popup\"><div class=\"cTitle\">" + siteLoc + "</div>";
    if (routes.length < 4) {
        //infoheight = 150 + routes.length * 10;
        infoheight = 160;
        //routestring = "<b>Served by</b><br/><div class=\"routelist style=\"height: 70px; overflow-x: hidden; overflow-y: visible; scrollbar-arrow-color: blue; scrollbar-face-color: #e7e7e7; scrollbar-3dlight-color: #a0a0a0; scrollbar-darkshadow-color:#888888\">";
        routestring = "<b>Served by</b><div class=\"routelistsmall\">";
    }
    else {
        infoheight = 200;
        //infowidth = infowidth + 35;
        //routestring = "<b>Served by</b><br/><div class=\"routelist\" style=\"height: 90px; overflow-x: hidden; overflow-y: scroll; scrollbar-arrow-color: blue; scrollbar-face-color: #e7e7e7; scrollbar-3dlight-color: #a0a0a0; scrollbar-darkshadow-color:#888888\">";
        routestring = "<b>Served by</b><br/><div class=\"routelist\">";
    }
    //infoheight = 150 + routes.length * 10
 
    //<div style="width: 150px; height: 150px; overflow-y: scroll; scrollbar-arrow-color: blue; scrollbar-face-color: #e7e7e7; scrollbar-3dlight-color: #a0a0a0; scrollbar-darkshadow-color:#888888">
    //var rURLP = "http://www.metrotransit.org/serviceInfo/route";
    //var rURLP = "http://transit.metc.state.mn.us/Schedules/WebSchedules.aspx?route=";
    var rURLP = "/Schedules/WebSchedules.aspx?route=";
    var rURLNTpre = "http://nextrip.metc.state.mn.us/NextripFull.aspx%5C?";
    //http://nextrip.metc.state.mn.us/NextripFull.aspx%5C?route=16&direction=2&stop=SNUN;
    var strRoute = "route=";
    var strDir = "&direction=";
    var strStop = "&stop=";
    var rURLS = ".asp";
    var rtestring = "Rte";
    var curRoute = dojo.byId("hidroute").value;
    var failed = function failed(error) {
        //Do something with the provided error.
        //console.log("fetch item error");
    };
    for (i = 0, len = routes.length; i < len; ++i) {
        rtdirs = routes[i].split(":");
        var rt = rtdirs[0];
        var dirs = rtdirs[1];
        routeStore.fetchItemByIdentity({
            identity: rt,
            onItem: function (item) {
                if (item !== null) {
                    var routeid = routeStore.getValue(item, "LINE_ID");
                    var routedesc = routeStore.getValue(item, "Description");

                    var schedulelink = "<a href= \"" + rURLP + routeid + "\" title=\"" + routedesc + "\" target=\"_blank\">" + routeid + "&nbsp; - &nbsp;" + routedesc + "</a>";


                    var cbhtmlstring;
                    var cblabelstring;
                    //URL with code to map new route if clicked - new version
                    if (routeid === curRoute) {
                        cbhtmlstring = "<input id=\"cb" + routeid + "\" dojotype=\"dijit.form.RadioButton\" onclick=\"javascript:OptionRoute(" + routeid + "," + "\'" + nodeid + "\'" + "," + "\'" + dirs + "\'" + ",0);return true;\" checked=\"checked\" name=\"optRoute\" type=\"radio\" />";
                        cblabelstring = "<label for=\"cb" + routeid + "\">" + schedulelink + "</label>";
                    }
                    else {
                        cbhtmlstring = "<input id=\"cb" + routeid + "\" dojotype=\"dijit.form.RadioButton\" onclick=\"javascript:OptionRoute(" + routeid + "," + "\'" + nodeid + "\'" + "," + "\'" + dirs + "\'" + ",0);return true;\" name=\"optRoute\" type=\"radio\" />";
                        cblabelstring = "<label for=\"cb" + routeid + "\">" + schedulelink + "</label>";
                    }
                    routestring = routestring + cbhtmlstring + cblabelstring + "<br/>";
                    //routestring = routestring + "<a href=\"#\" onclick=\"javascript:NewRoute(" + routeid + ", 0);return false;\">" + routeid + " " + routedesc + "</a> " + schedulelink + "<br/>"
                    //                }

                    rtestring = "Rte";
                }
            },
            onError: failed
        });
    }

    //Trip planner string
    var tripplanstring = "</div><div class=\"pfooter\"><b>Plan a transit trip:</b>&nbsp<a href=\"/TripPlanner/Default.aspx?s-dest=%26lt%3b" + escape(siteID) + "%26gt%3b+%23+" + escape(siteon) + "+%26amp%3b+" + escape(siteat) + "%7c" + escape(CTU_NAME) + "%7c" + UTMY + "%7c" + UTMX + "%7c%7c%7c%7c0%7c0%7c0%7c0%7cStop%7c0\" target=\"_blank\">To here</a> | " + "<a href=\"/TripPlanner/Default.aspx?s-orig=%26lt%3b" + siteID + "%26gt%3b+%23+" + escape(siteon) + "+%26amp%3b+" + escape(siteat) + "%7c" + escape(CTU_NAME) + "%7c" + UTMY + "%7c" + UTMX + "%7c%7c%7c%7c0%7c0%7c0%7c0%7cStop%7c0\" target=\"_blank\">From here</a></div>";

    content = content + "<div class=\"pContent\">" + routestring + "</div>" + tripplanstring + "</div>";
    myMap.infoWindow.resize(infowidth, infoheight);
    myMap.infoWindow.setContent(content);
    myMap.infoWindow.setTitle("<div class=\"pTitle\">Stop Number " + siteID + "</div>");

}
function busstopFunc() {
    var stopid = dojo.byId("hidstop").value;
    //var loading = dojo.byId("loadingImg");
    //esri.show(loading);
    var stopqt = new esri.tasks.QueryTask("http://gis2.metc.state.mn.us/ArcGIS/rest/services/transit/TIM_Points/MapServer/1");
    var stopquery = new esri.tasks.Query();
    stopquery.geometry = myMap.extent;
    stopquery.returnGeometry = true;
    stopquery.spatialRelationship = esri.tasks.Query.SPATIAL_REL_INTERSECTS;
    stopquery.outFields = ["SITEID", "SITE_ON", "SITE_AT", "CORN_DESC", "NODE_ID", "ROUTES", "ROUTEDIRS", "UTMX", "UTMY", "CITY_ID", "SYMBOL", "NROUTES"];
    stopquery.where = "NROUTES <> 0";

    var currentRoute = dojo.byId("hidroute").value;
    //listen for onComplete event
    dojo.connect(stopqt, "onComplete", function (featureSet) {
        var stopgraphics = new Array();
        var stopids = new Array();
        var newStops = new Array();
        var iExG, fsl, clearall;
        //Create an array of the existing stop graphics
        stopgraphics = stoplyr.graphics;
        iExG = stopgraphics.length;
        fsl = featureSet.features.length;

        if (iExG > 400 || fsl < 30) {
            //console.log("this will be a clear all");
            ClearStopGraphics();
            clearall = true;
        }
        else if (iExG === 0) {
            //console.log("stop graphics is zero");
            clearall = true;
        }
        else {
            //create an array of existing stopids as an index
            //console.log("there are " + iExG + " stopgraphics");
            for (var ixx = 0; ixx < iExG; ixx++) {
                //console.log(stopgraphics[ixx].attributes.siteid);
                stopids.push(stopgraphics[ixx].attributes.siteid);
            }
            clearall = false;
        }

        //}
        //else {
        //    ClearStopGraphics();
        //}


        var graystopsymbol = new esri.symbol.PictureMarkerSymbol('images/BusGreyWhite.png', 15, 15);
        var routeSymbol = new esri.symbol.PictureMarkerSymbol('images/BusBlueWhite.png', 15, 15);
        var lrtsymbol = new esri.symbol.PictureMarkerSymbol('images/LRTGreyWhite.png', 15, 15);
        var hrtsymbol = new esri.symbol.PictureMarkerSymbol('images/heavyRailGreyWhite.png', 15, 15);
        var highlightSymbol = new esri.symbol.PictureMarkerSymbol('images/bus-red.png', 30, 30);
        //var genericSymbol = new esri.symbol.SimpleMarkerSymbol();
        var routesObj, graphic, routenum, routesArray;
        //QueryTask returns a featureSet.  Loop through features in the featureSet and add them to the map.
        for (var i = 0; i < fsl; i++) {
            //Get the current feature from the featureSet.
            //Feature is a graphic

            graphic = featureSet.features[i];
            //graphic.hide();
            //graphic.setSymbol(genericSymbol);
            routesArray = graphic.attributes.ROUTES.split(" ");
            routesObj = new Object();
            for (var j = 0; j < routesArray.length; j++) {
                routenum = String(routesArray[j]);
                routesObj[routenum] = routesArray[j];
            }
            if (routesObj[currentRoute]) {
                if (graphic.attributes.Symbol === 1) {
                    graphic.setSymbol(new esri.symbol.PictureMarkerSymbol('images/LRTBlueWHite.png', 15, 15));
                }
                else if (graphic.attributes.Symbol === 2) {
                    graphic.setSymbol(new esri.symbol.PictureMarkerSymbol('images/heavyRailBlueWhite.png', 15, 15));
                }
                else {
                    graphic.setSymbol(routeSymbol);
                }
            }
            else {
                //console.log("Current route: " + currentRoute + " is not indexed in " + graphic.attributes.ROUTES);

                if (graphic.attributes.Symbol === 1) {
                    graphic.setSymbol(lrtsymbol);
                }
                else if (graphic.attributes.Symbol === 2) {
                    graphic.setSymbol(hrtsymbol);
                }
                else {
                    graphic.setSymbol(graystopsymbol);
                    //graphic.setSymbol(genericSymbol);
                }
            }


            if (dojo.lastIndexOf(stopids, graphic.attributes.siteid) == -1) {
                //newStops.push(graphic);
                stoplyr.add(graphic);
            }

        }

        //myMap.graphics.enableMouseEvents();


        mover = dojo.connect(stoplyr, "onMouseOver", function (evt) {
            var stoptype = evt.graphic.attributes.Symbol;
            //evt.graphic.setSymbol(redStopSymb);
            //originalSymbol = evt.graphic.symbol;
            //console.log("onMouseOver");
            var currentRoute = dojo.byId("hidroute").value;
            if (currentRoute === "" || evt.graphic.attributes.ROUTES.indexOf(currentRoute) === -1) {
                switch (stoptype) {
                    case 0:
                        evt.graphic.setSymbol(new esri.symbol.PictureMarkerSymbol('images/BusWhiteBlue.png', 25, 25));
                        break;

                    case 1:
                        evt.graphic.setSymbol(new esri.symbol.PictureMarkerSymbol('images/LRTWhiteBlue.png', 25, 25));
                        break;

                    case 2:
                        evt.graphic.setSymbol(new esri.symbol.PictureMarkerSymbol('images/heavyRailWhiteBlue.png', 25, 25));
                        break;

                    default:
                        evt.graphic.setSymbol(new esri.symbol.PictureMarkerSymbol('images/BusWhiteBlue.png', 25, 25));
                        break;

                }
            }
            else {
                switch (stoptype) {
                    case 0:
                        evt.graphic.setSymbol(new esri.symbol.PictureMarkerSymbol('images/BusBlueWhite.png', 25, 25));
                        break;

                    case 1:
                        evt.graphic.setSymbol(new esri.symbol.PictureMarkerSymbol('images/LRTBlueWhite.png', 25, 25));
                        break;

                    case 2:
                        evt.graphic.setSymbol(new esri.symbol.PictureMarkerSymbol('images/heavyRailBlueWhite.png', 25, 25));
                        break;

                    default:
                        evt.graphic.setSymbol(new esri.symbol.PictureMarkerSymbol('images/BusBlueWhite.png', 25, 25));
                        break;

                }
            }

            myMap.graphics.disableMouseEvents();
            dojo.disconnect(iWindow);
            var mapHeight = myMap.height;
            var mapWidth = myMap.width;
            var xOffset, yOffset;
            if (evt.screenPoint.x < (mapWidth / 2)) {
                xOffset = 5;
            } else {
                xOffset = -5;
            }
            if (evt.screenPoint.y < (mapHeight / 2)) {
                yOffset = 5;
            } else {
                yOffset = -5;
            }


            //myMap.infoWindow.show(evt.screenPoint.offset(xOffset,yOffset),myMap.getInfoWindowAnchor(evt.screenPoint));  
            dojo.disconnect(iWindow);
            //buildInfoWindow(evt);
            //myMap.infoWindow.show(evt.screenPoint,myMap.getInfoWindowAnchor(evt.screenPoint));  

        });

        mout = dojo.connect(stoplyr, "onMouseOut", function (evt) {
            dojo.disconnect(iWindow);
            var stoptype = evt.graphic.attributes.Symbol;
            var currentRoute = dojo.byId("hidroute").value;
            //            var rg = new RegExp("\b" + currentRoute,"ig");
            var rx = new RegExp("\\b" + currentRoute + "\\b");
            if (currentRoute === "" || evt.graphic.attributes.ROUTES.search(rx) === -1) {
                switch (stoptype) {
                    case 0:
                        evt.graphic.setSymbol(new esri.symbol.PictureMarkerSymbol('images/BusGreyWhite.png', 15, 15));
                        break;

                    case 1:
                        evt.graphic.setSymbol(new esri.symbol.PictureMarkerSymbol('images/LRTGreyWhite.png', 15, 15));
                        break;

                    case 2:
                        evt.graphic.setSymbol(new esri.symbol.PictureMarkerSymbol('images/heavyRailGreyWhite.png', 15, 15));
                        break;

                    default:
                        evt.graphic.setSymbol(new esri.symbol.PictureMarkerSymbol('images/BusGreyWhite.png', 15, 15));
                        break;

                }
            }
            else {
                switch (stoptype) {
                    case 0:
                        evt.graphic.setSymbol(new esri.symbol.PictureMarkerSymbol('images/BusBlueWhite.png', 15, 15));
                        break;

                    case 1:
                        evt.graphic.setSymbol(new esri.symbol.PictureMarkerSymbol('images/LRTBlueWhite.png', 15, 15));
                        break;

                    case 2:
                        evt.graphic.setSymbol(new esri.symbol.PictureMarkerSymbol('images/heavyRailBlueWhite.png', 15, 15));
                        break;

                    default:
                        evt.graphic.setSymbol(new esri.symbol.PictureMarkerSymbol('images/BusBlueWhite.png', 15, 15));
                        break;

                }
            }
        });

        onclickconn = dojo.connect(stoplyr, "onClick", function (evt) {
            //This event occurs when a stop is clicked
            //It kills the click event so that no further action is taken.
            killMapClick();
            var stopid = evt.graphic.attributes.siteid;
            dojo.byId("hidstop").value = stopid;
            fillNexTrip(stopid);

            //get attributes
            buildInfoWindow(evt);
            myMap.infoWindow.show(evt.screenPoint, myMap.getInfoWindowAnchor(evt.screenPoint));
            setTimeout("listenMapClick()", 500);
            //setTimeout(someFunction, 2);
            

        });
    });

    stopqt.execute(stopquery);
}
function extentChange(ext,delt,bLod) {
    //console.log("absolute value of delt.x: " + Math.abs(delt.x) + " absolute value of delt.y: " + Math.abs(delt.y));
    if (Math.abs(delt.x) > 1 || Math.abs(delt.y) > 1 || bLod) {
        //console.log("refreshmap call from extentChange");
        refreshMap();
    }
    else {
        //console.log("did not meet delta requirements - no refreshMap");
    }
}


function stopNodeRefresh() {
//Look at existing stop layers and color based on selected route
    //First get current stoplyr items
    var graystopsymbol = new esri.symbol.PictureMarkerSymbol('images/BusGreyWhite.png', 15, 15);
    var routeSymbol = new esri.symbol.PictureMarkerSymbol('images/BusBlueWhite.png', 15, 15);
    var lrtsymbol = new esri.symbol.PictureMarkerSymbol('images/LRTGreyWhite.png', 15, 15);
    var hrtsymbol = new esri.symbol.PictureMarkerSymbol('images/heavyRailGreyWhite.png', 15, 15);
    var highlightSymbol = new esri.symbol.PictureMarkerSymbol('images/bus-red.png', 30, 30);
    var curstopgraphics = stoplyr.graphics;
    var routesArray;
    var routesObj;
    
    var currentRoute = dojo.byId("hidroute").value;
    for (var i = 0, il = curstopgraphics.length; i < il; i++) {
        var graphic = curstopgraphics[i];
        routesArray = graphic.attributes.ROUTES.split(" ");
        routesObj = new Object();
       
        for (var j = 0; j < routesArray.length; j++) {
            var routenum = String(routesArray[j]);
            routesObj[routenum] = routesArray[j];
        }

        if (routesObj[currentRoute]) {
            if (graphic.attributes.Symbol === 1) {
                graphic.setSymbol(new esri.symbol.PictureMarkerSymbol('images/LRTBlueWHite.png', 15, 15));
            }
            else if (graphic.attributes.Symbol === 2) {
                graphic.setSymbol(new esri.symbol.PictureMarkerSymbol('images/heavyRailBlueWhite.png', 15, 15));
            }
            else {
                graphic.setSymbol(routeSymbol);
            }
        }
        else {
            if (graphic.attributes.Symbol === 1) {
                graphic.setSymbol(lrtsymbol);
            }
            else if (graphic.attributes.Symbol === 2) {
                graphic.setSymbol(hrtsymbol);
            }
            else {
                graphic.setSymbol(graystopsymbol);
            }
        }
         
    }
  

}
function drawParkRides() {
    var ParkRideQT = new esri.tasks.QueryTask("http://gis2.metc.state.mn.us/ArcGIS/rest/services/transit/TIM_Points/MapServer/3");
    var ParkRideQuery = new esri.tasks.Query();
    var facid;
    ParkRideQuery.geometry = initExtent;
    ParkRideQuery.returnGeometry = true;
    ParkRideQuery.outFields = ["PR_NUM", "NAME", "DESCRIPT", "CITY", "ROUTE_DIR", "CAPACITY"];
    //ROUTE_DIR, ROUTES, DSTNATN, STOPS, CAPACITY 
    var prsymb = new esri.symbol.PictureMarkerSymbol('images/ParkBlue.png', 16, 16);
    var prSmartSymb = new esri.symbol.PictureMarkerSymbol('images/ParkSmart.png', 16, 16);
    var prInfoTemplate = new esri.InfoTemplate();
    prInfoTemplate.setTitle("Park and Ride");
    prInfoTemplate.setContent("${DESCRIPT}<br/>" + "${CITY}");
    var prSmartInfoTemplate = new esri.InfoTemplate();
    prSmartInfoTemplate.setTitle("Park and Ride");
    prSmartInfoTemplate.setContent("<img src=\"ParkingAvailabilityImage.ashx?facid=99\" />");
    //ParkRideQuery.where = "USAGE >= 0 AND NAME <> ''";
    //217 = Blaine = Parking avail. facility ID 1
    //555 = Kenrick/Lakeville = Parking avail. facility ID 3
    //710 = Burnsville = Parking avail. facility ID 4
    //1040 = Roseville = Parking avail. facility ID 2
    var smartPRs = [];
    var iSmartPR = 0;
    dojo.connect(ParkRideQT, "onComplete", function(featureSet) {
        dojo.forEach(featureSet.features, function(feature) {

            var graphic = feature;
            if (graphic.attributes.PR_NUM === 217 || graphic.attributes.PR_NUM === 555 || graphic.attributes.PR_NUM === 710 || graphic.attributes.PR_NUM === 1040) {
                graphic.setSymbol(prSmartSymb);
                graphic.setInfoTemplate(prSmartInfoTemplate);
                //add to array to save and add to map later.
                smartPRs[iSmartPR++] = graphic;
            }
            else {
                graphic.setSymbol(prsymb);
                graphic.setInfoTemplate(prInfoTemplate);
                prlyr.add(graphic);
            }
        });

        //add smart park and rides to map after other park and rides
        //so they come out on top.
        while (iSmartPR > 0) {
            prlyr.add(smartPRs[--iSmartPR]);
        }
        var PRonclickconn = dojo.connect(prlyr, "onClick", function(evt) {
            //get attributes
            buildPRInfoWindow(evt);
        });
    });
    ParkRideQT.execute(ParkRideQuery);
}



function drawTTSigns(zoomlevel) {

    var signqt = new esri.tasks.QueryTask("http://gis2.metc.state.mn.us/ArcGIS/rest/services/Transit/TIM_Points/MapServer/0");
    //http://gis2.metc.state.mn.us/ArcGIS/rest/services/transit/TIM_BusRoutes/MapServer/0/query?text=84&geometry=&geometryType=esriGeometryEnvelope&inSR=&spatialRel=esriSpatialRelIntersects&where=LINE_ID_N%3D84&returnGeometry=true&outSR=102113&outFields=LINE_ID%2CRT_DESC%2CLINE_ID_N%2CLINE_ID_PD&f=html
    var signquery = new esri.tasks.Query();
    signquery.returnGeometry = true;
    //var signOL = new esri.symbol.SimpleLineSymbol('STYLE_NULL', new dojo.Color([255, 255, 255, 0.1]), 0);
    var TTSignsymb;
    //var TTSignsymb1 = new esri.symbol.PictureMarkerSymbol('TravelTimeImage.ashx?pathID=1', 329, 60);
    //var TTSignsymb2 = new esri.symbol.PictureMarkerSymbol('TravelTimeImage.ashx?pathID=2', 329, 60);
    //var TTSignsymb3 = new esri.symbol.PictureMarkerSymbol('TravelTimeImage.ashx?pathID=3', 329, 60);
    //var TTSignsymb = new esri.symbol.PictureMarkerSymbol('images/ParkBlue.png', 30, 30);

    signquery.geometry = myMap.extent;

    signquery.spatialRelationship = esri.tasks.Query.SPATIAL_REL_INTERSECTS;
    signquery.outFields = ["Location_Desc", "ParkandRideName", "MapSignType", "ParkandRideID", "Designation", "PlanNumber", "Description", "Fac_Type"];
    signquery.outSR = "26915";
    //signquery.where = "Fac_Type = \'Freeway\' AND MapSignType = \'TT\'";

    //listen for onComplete event
    //Clear existing sign graphics
    ClearSignGraphics();
    dojo.connect(signqt, "onComplete", function(featureSet) {
        dojo.forEach(featureSet.features, function(feature) {
            var locGeom = feature.geometry;
            var graphic = feature;
            switch (feature.attributes.Designation) {
                case "B-1":
                    //var TTSignsymb = new esri.symbol.PictureMarkerSymbol('TravelTimeImage.ashx?pathID=3', 329, 60);
                    //var rgba = TTSignsymb.color.toRgba();
                    break;
                case "L-2":
                    //var TTSignsymb = new esri.symbol.PictureMarkerSymbol('TravelTimeImage.ashx?pathID=4', 329, 60);
                    break;
                case "95-2":
                    TTSignsymb = new esri.symbol.PictureMarkerSymbol('TravelTimeImage.ashx?pathID=1', 329, 60);
                    break;
                case "TL-3":
                    TTSignsymb = new esri.symbol.PictureMarkerSymbol('TravelTimeImage.ashx?pathID=2', 329, 60);
                    break;
                default:
                    //(feature.attributes.Designation);
                    TTSignsymb = new esri.symbol.PictureMarkerSymbol('TravelTimeImage.ashx?pathID=4', 329, 60);
                    break;
            }

            //convert graphic coordinates to screen coordinates
            var screengraphic = esri.geometry.toScreenGeometry(myMap.extent, myMap.width, myMap.height, graphic.geometry);
            //Manipulate screen coordinates to put the graphic in the correct spot on the map regarless of scale
            screengraphic.x = screengraphic.x + 170;
            screengraphic.y = screengraphic.y + 35;
            //Convert graphic back to map geometry
            graphic.geometry = esri.geometry.toMapGeometry(myMap.extent, myMap.width, myMap.height, screengraphic);
            //Symbolize and add graphic to the map graphics layer
            graphic.setSymbol(TTSignsymb);
            TTsignlyr.add(graphic);
            if (signvis === true) {
                TTsignlyr.show();
            } else {
                TTsignlyr.hide();
            }



        });
        //("zoom is " + zoom);

        //signclickconn = dojo.connect(TTsignlyr, "onClick", function(evt) {
        ttSignConn = dojo.connect(TTsignlyr, "onClick", function(evt) {
            //("clicked TTSign");
            TTsignlyr.hide();
            signvis = false;
        });

    });
    //("pre execute route query");
    signqt.execute(signquery);
    //Begin Testing Layer Definitions Approach to mapping bus routes
    //End Testing
    //("Execute Route Query");

}
function drawTTPoints() {

    //("Draw TT Points: ");
    var signqt = new esri.tasks.QueryTask("http://gis2.metc.state.mn.us/ArcGIS/rest/services/transit/TIM_Points/MapServer/0");
    //http://gis2.metc.state.mn.us/ArcGIS/rest/services/transit/TIM_BusRoutes/MapServer/0/query?text=84&geometry=&geometryType=esriGeometryEnvelope&inSR=&spatialRel=esriSpatialRelIntersects&where=LINE_ID_N%3D84&returnGeometry=true&outSR=102113&outFields=LINE_ID%2CRT_DESC%2CLINE_ID_N%2CLINE_ID_PD&f=html
    var signquery = new esri.tasks.Query();
    signquery.returnGeometry = true;
    var signOL = new esri.symbol.SimpleLineSymbol('STYLE_NULL', new dojo.Color([255, 255, 255, 0.1]), 0);
    //var signOL = new esri.symbol.SimpleLineSymbol('STYLE_NULL', new dojo.Color([100, 255, 40, 1]), 0);
    var TTPointsymb = new esri.symbol.SimpleMarkerSymbol('STYLE_CIRCLE', 18, signOL, new dojo.Color([255, 255, 255, 0.1]));
    //signquery.geometry = myMap.extent;
    signquery.geometry = initExtent;
    signquery.spatialRelationship = esri.tasks.Query.SPATIAL_REL_INTERSECTS;
    signquery.outFields = ["Location_Desc", "ParkandRideName", "MapSignType", "ParkandRideID", "Designation", "PlanNumber", "Description", "Fac_Type"];
    signquery.outSR = "26915";
    //(signquery);
    var iCount = 0;
    //signquery.where = "Fac_Type = \'Freeway\' AND MapSignType = \'TT\'";
    dojo.connect(signqt, "onComplete", function (featureSet) {
        dojo.forEach(featureSet.features, function (feature) {
            // iCount = iCount + 1;
            //("Travel Time Sign " + iCount);
            var locGeom = feature.geometry;
            //(locGeom);
            var graphic = new esri.Graphic(feature.geometry, TTPointsymb, feature.attributes);
            TTlyr.add(graphic);
        });

        ttConn = dojo.connect(TTlyr, "onClick", function (evt) {
            //("clicked TT Location");
            //If tt sign location is clicked, suppress route click.
            //(evt);
            if (!signvis) {
                //("Not Sign vis");
                signvis = true;
                //TTsignlyr.show();
                drawTTSigns();
            }
            else if (signvis === true) {
                //("Signvis was true");
                signvis = false;
                //drawTTSigns();
                TTsignlyr.hide();
            }
            else if (signvis === false) {
                //("Signvis was false");
                signvis = true;
                //TTsignlyr.show();
                drawTTSigns();
            }


        });
    });
    //("pre execute route query");
    signqt.execute(signquery);
    //Begin Testing Layer Definitions Approach to mapping bus routes
    //End Testing
    //("Execute Route Query");

}

function ClearBuses() {
    var glayer = myMap.graphics;
    //("delete bus graphics");
    var iGraphics = glayer.graphics.length;
    //glayer.graphics[0].vehicle
    //var i = 0
    for (var i = iGraphics - 1; i >= 0; i--){
    //for (var g in glayer.graphics) b
    
        //look for graphics with vehicle attribute
        //(bus stops will not have a vehicle attribute) 
        try {
            if ('vehicle' in glayer.graphics[i].attributes) {
                glayer.remove(glayer.graphics[i]);
            }
        } catch (e) {
            return "ClearBuses error";
        }

    }

}

function isEven(num) {
  return !(num % 2);
}



function fillNexTrip(stopid) {
    //("fill nextrip " + stopid);
    //$("#accordion").accordion("option", "clearStyle", true);
    //update link to launch nextrip badge in a separate window with new stop id
    //http: //metrotransit.org/NexTripBadge.aspx?stopnumber=1235
    var iH = "<a href=javascript://NexTrip id= \"activetab\" name=\"OpenNextripButton\" onClick=\"OpenNextrip(" + stopid + ");\"><span>Launch <B><I>Nex</I>Trip</B> in a separate window</span></a>";
    $("#nextriplaunch").html(iH);


    //populate nextrip information
    dojo.xhrGet({
        //http://svc.metrotransit.org/NexTrip/{STOPID}
        //url: "http://svc.metrotransit.org/NexTrip/" + stopid,
        url: "NextBusDepartures.ashx?stopid=" + stopid,
        headers: {"Content-Type": "application/json"},
        handleAs: "json",
        timeout: 5000,
        load: function nextripresp(response, io) {
            var sNextDepartureHeader;
            var NexTripDepartures = response.Departures;
            var iDeps = NexTripDepartures.length;

            //If there are no trips
            if (iDeps === 0) {
                $("#nextripheader").html("No Trips Available at This Time");
                $("#nextripcontent").html("");
            }
            //If there is only one trip don't show anything below the yellow bar.
            else if (iDeps === 1) {
                //If the one trip is due, show "Due" in the yellow bar.
                if (NexTripDepartures[0].DepartureText === "Due") {
                    $("#nextripheader").html("");
                }


                //If it is not due, show either the Actual time or the scheduled time.
                else {
                    if (NexTripDepartures[0].Actual == "True") {
                        $("#nextripheader").html("<b><i>Nex</i>Trip</b> departs in <b>" + NexTripDepartures[0].DepartureText + "</b>");
                    }
                    else {
                        $("#nextripheader").html("<b><i>Nex</i>Trip</b> departs at <b>" + NexTripDepartures[0].DepartureText + "</b>");
                    }
                }
                $("#nextripcontent").html("");
            }
            else {
                //write response to the nextrip panel
                //sCurrentTime =
                //(timeServer);
                //If the next Trip is due, show Departure[1] in the yellow band.
                
                var nextDep;
                nextDep = NexTripDepartures[0];
                nexti = 0;
                while (nextDep.DepartureText === "Due") {

                    nextDep = NexTripDepartures[i];

                    nexti++;
                }
                //console.log(nextDep.DepartureText);
                //console.log(nextDep.RouteNumber);
                //check if NexTripDepartures[i] is a value
                if (nextDep !== null) {
                    if (nextDep.Actual == "True") {
                        $("#nextripheader").html("<b><i>Nex</i>Trip</b> departs in <b>" + nextDep.DepartureText + "</b>");
                    }
                    else {
                        $("#nextripheader").html("<b><i>Nex</i>Trip</b> departs at <b>" + nextDep.DepartureText + "</b>");
                    }
                }
                else {
                    $("#nextripheader").html("");
                }
                var sColumnHeaders = "<div class=\"dataheaders\"><span class=\"col1header\">Route</span><span class=\"col3header\">Departs</span></div>";
                var sNexTripFooterKey = "<div class=\"nextripfooterkey\"><span style=\"margin: 6px 2px;position: relative; color: rgb(0, 0, 0);\">• Real Time</span><br /><span class=\"red\" style=\"margin: 1px 1px;position: relative;\">• Scheduled</span></div>";
                var sNTDepTab = "<div class=\"nextripDepartures\">";
                //var sNTTable = "<table class=\"\"><tr><td>Route</td><td>description</td><td>departs</td></tr>";
                //for (var x = 0, il = NexTripDepartures.length; x < il; x++) {
                NexTripDepartures = response.Departures;
                for (var dep in NexTripDepartures) {

                    if (isEven(dep)) {
                        sNTDepTab = sNTDepTab + "<div class=\"data row\">";
                    }
                    else {
                        sNTDepTab = sNTDepTab + "<div class=\"data altrow\">";
                    }

                    if (NexTripDepartures[dep].Actual == "True") {
                        //dispaly Depature text in red
                        sNTDepTab = sNTDepTab + "<span class=\"col1\"><a href=\"/Schedules/WebSchedules.aspx?route=" + NexTripDepartures[dep].Route + "\" target=\"_blank\">" + NexTripDepartures[dep].Route + NexTripDepartures[dep].Terminal + "</a></span><span class=\"col2\"><a href=\"/Schedules/WebSchedules.aspx?route=" + NexTripDepartures[dep].Route + "\" target=\"_blank\">" + NexTripDepartures[dep].Description + "</a></span><span class=\"col3\"; style=\"color:#000000\">" + NexTripDepartures[dep].DepartureText + "</span></div>";
                    }
                    else {
                        sNTDepTab = sNTDepTab + "<span class=\"col1\"><a href=\"/Schedules/WebSchedules.aspx?route=" + NexTripDepartures[dep].Route + "\" target=\"_blank\">" + NexTripDepartures[dep].Route + NexTripDepartures[dep].Terminal + "</a></span><span class=\"col2\"><a href=\"/Schedules/WebSchedules.aspx?route=" + NexTripDepartures[dep].Route + "\" target=\"_blank\">" + NexTripDepartures[dep].Description + "</a></span><span class=\"col3\"; style=\"color:#ed1e2e\">" + NexTripDepartures[dep].DepartureText + "</span></div>";
                    }

                    //sNTTable = sNTTable + "<tr><td>" + NexTripDepartures[x].Route + "</td><td>" + NexTripDepartures[x].Description + "</td><td>" + NexTripDepartures[x].DepartureText + "</td></tr>";

                }

                sNTDepTab = sNTDepTab + "</div>";
                //sNTTable = sNTTable + "</table>"
                //sNextTripText = NexTripDepartures[0].DepartureTime
                //$("#nextripcontent").html(sNTTable);
                //console.log(sColumnHeaders + sNTDepTab + sNexTripFooterKey);
                $("#nextripcontent").html(sColumnHeaders + sNTDepTab + sNexTripFooterKey);
                //$("#nextripfooterkey").html();

                setTimeout(function () { $("#accordion").accordion("resize"); }, 200);
            }
        },
        error: function (err) {
            //("An error occured: " + err);
        }

    });

}

function loadBusData(route) {
    //("loadBusData " + route);
}

function refreshCurrent(route) {
    //("RefreshCurrent");
    ClearBuses();
    if (route !== undefined) {
        //("Route = " + route);
        loadBusData(route);
    }
}

function ClearStopGraphics() {
    stoplyr.clear();
}

function ClearSignGraphics() {
    //ttSignConn is nothing
    //ttConn is Nothing
    //TTlyr.clear();
    TTsignlyr.clear();
}

function ClearNodeLyr() {
    nodelyr.clear();
}

function ClearRouteGraphics() {
    //Function to delete bus routes and nodes graphics
    //("Clear Node Layer");
    nodelyr.clear();
    //("Clear Route Layer");
    routelyr.clear();
}

//Clear Functions
function ClearGraphics() {
    //("ClearGraphics");
    ClearRouteGraphics();
}
function drawRouteNodes(route) {
    //("Draw Route Nodes for route: " + route);
    var RouteNodeQT = new esri.tasks.QueryTask("http://gis2.metc.state.mn.us/ArcGIS/rest/services/transit/TIM_Points/MapServer/3");
    var RouteNodeQuery = new esri.tasks.Query();
    //RouteNodeQuery.geometry = initExtent;
    RouteNodeQuery.geometry = new esri.geometry.Extent({ "xmin": 380425.190770931, "ymin": 4906135.56930647, "xmax": 577580.229321643, "ymax": 5136910.32510176, "spatialReference": { "wkid": 26915} });
    RouteNodeQuery.returnGeometry = true;
    RouteNodeQuery.outFields = ["SITEID", "CTU_NAME", "SITE_ON", "SITE_AT", "UTMX", "UTMY", "NODE_ID", "ROUTES", "ROUTEDIRS", "LINE_ID_N", "X", "Y"];
    var nodesymb;
    var nodesymbSel;
    if (route == "55") {
        nodesymb = new esri.symbol.PictureMarkerSymbol('images/LRTBlueWhite.png', 15, 15);
        nodesymbSel = new esri.symbol.PictureMarkerSymbol('images/LRTBlueWhite.png', 25, 25);
    }else if (route == "888") {
        nodesymb = new esri.symbol.PictureMarkerSymbol('images/HeavyRailBlueWhite.png', 15, 15);
        nodesymbSel = new esri.symbol.PictureMarkerSymbol('images/HeavyRailBlueWhite.png', 25, 25);
    }
    //nodesymb.setColor(new dojo.Color("red"));
    var nodeInfoTemplate = new esri.InfoTemplate();
    nodeInfoTemplate.setTitle("${NODE_ID}");
    nodeInfoTemplate.setContent("${*}");

    RouteNodeQuery.where = "LINE_ID_N = " + route + " AND NODE_ID <> \' \'";
    dojo.connect(RouteNodeQT, "onComplete", function(featureSet) {
        //Add  to the nodes layer
        dojo.forEach(featureSet.features, function(feature) {
            var graphic = feature;
            graphic.setSymbol(nodesymb);
            graphic.setInfoTemplate(nodeInfoTemplate);
            nodelyr.add(graphic);
        });

        myMap.graphics.enableMouseEvents();
        nodeover = dojo.connect(nodelyr, "onMouseOver", function(evt) {
            evt.graphic.setSymbol(nodesymbSel);
            myMap.graphics.disableMouseEvents();
            dojo.disconnect(iWindow);
            var mapHeight = myMap.height;
            var mapWidth = myMap.width;
            var xOffset, yOffset;
            if (evt.screenPoint.x < (mapWidth / 2)) {
                xOffset = 5;
            } else {
                xOffset = -5;
            }
            if (evt.screenPoint.y < (mapHeight / 2)) {
                yOffset = 5;
            } else {
                yOffset = -5;
            }

            dojo.disconnect(iWindow);

        });

        nodeout = dojo.connect(nodelyr, "onMouseOut", function(evt) {
            dojo.disconnect(iWindow);
            evt.graphic.setSymbol(nodesymb);
            //myMap.infoWindow.hide();
            //dojo.connect(myMap,"onMouseMove",myMap.graphics.enableMouseEvents);
            //evt.graphic.setSymbol(symbol);
        });

        nodeclickconn = dojo.connect(nodelyr, "onClick", function(evt) {
            //disconnect mouseover, mouseout
            //dojo.disconnect(mover)
            //dojo.disconnect(mout)

            //var stopid = evt.graphic.attributes['SITE_ID'];
            var stopid = evt.graphic.attributes.siteid;
            fillNexTrip(stopid);
            dojo.byId("hidstop").value = stopid;

            //get attributes
            buildInfoWindow(evt);
            evt.graphic.setSymbol(nodesymbSel);
            //Listen for infoWindow onHide event
            //iWindow = dojo.connect(myMap.infoWindow, "onHide", infoHide;
            iWindow = dojo.connect(myMap.infoWindow, "onHide", function() {
                dojo.disconnect(iWindow);
                //reconnect mouseover and mouse out
                //console.log("InfoWindow Hidden");
                //mouseconnect();
            });

            //dojo.connect(myMap.infoWindow, "onHide", infoHide);
            //infoHide();
            myMap.graphics.disableMouseEvents();
            dojo.disconnect(onclickconn);
            //why is this refresh map being called?
            //refreshMap();
            myMap.infoWindow.show(evt.screenPoint, myMap.getInfoWindowAnchor(evt.screenPoint));


        });

    });
    RouteNodeQT.execute(RouteNodeQuery);

}

function drawRoutes(route, zoom, busdata) {
    //Map bus route
    //zoom value should be 0 (false - don't zoom to route) or 1 (zoom to route)
    //route should be an array of routes to be mapped
    //bus data should be 0 (false) or 1 (true) on whether to include live bus location refresh
    //
    //Check if route is an array

    var rq;
    var ir = 0;
    //var hfn = false;
    if (route instanceof Array) {
        //cycle through array and build the route query string
        //if there are more than 5 routes selected... what to do.
        rq = "ROUTENUM = " + route[0];
        dojo.byId("hidroute").value = route;
        if (route[1]) {
            rq = rq + " OR ROUTENUM = " + route[1];
            dojo.byId("hidroute").value = "";
        }
        if (route[2]) {rq = rq + " OR ROUTENUM = " + route[2]; }
        if (route[3]) {rq = rq + " OR ROUTENUM = " + route[3]; }
        if (route[4]) {rq = rq + " OR ROUTENUM = " + route[4]; }


        //jslint error, The body of a for in should be wrapped in an if statement to filter unwanted properties from the prototype.
        //for (var x in route) {        
        //        rq = rq + " OR ROUTENUM = " + route[x];
        //}

    }
    //else { busdata = 1 }
    else {
        rq = "ROUTENUM = " + route;
        //set hidden route field to route
        dojo.byId("hidroute").value = route;
    }
    //refresh selected items in routelist
    //Change Layer Definitions of bus route layer

    var layerDefinitions = [];
    layerDefinitions[0] = rq;

    busRoutesMapLayer.setLayerDefinitions(layerDefinitions);
    //Check if bus routes layer is visible. If it isn't, make it visible.
    if (dojo.indexOf(busRoutesMapLayer.visibleLayers, 0) === -1) {
        busRoutesMapLayer.setVisibleLayers([0]);
    }
    
    
    var routeqt = new esri.tasks.QueryTask("http://gis2.metc.state.mn.us/ArcGIS/rest/services/transit/TIM_BusRoutes/MapServer/0");
    //http://gis2.metc.state.mn.us/ArcGIS/rest/services/transit/TIM_BusRoutes/MapServer/0/query?text=84&geometry=&geometryType=esriGeometryEnvelope&inSR=&spatialRel=esriSpatialRelIntersects&where=LINE_ID_N%3D84&returnGeometry=true&outSR=102113&outFields=LINE_ID%2CRT_DESC%2CLINE_ID_N%2CLINE_ID_PD&f=html
    var routequery = new esri.tasks.Query();
    routequery.returnGeometry = true;

    routequery.geometry = initExtent;
    routequery.spatialRelationship = esri.tasks.Query.SPATIAL_REL_INTERSECTS;
    routequery.outFields = ["LINE_ID", "ROUTENUM", "ROUTEDESCRIPTION"];
    routequery.outSR = "26915";
    //LINE_ID_N = 16 OR LINE_ID_N = 21
    routequery.where = rq;
    //listen for onComplete event
    dojo.connect(routeqt, "onComplete", function(featureSet) {
        //myMap.graphics.clear();

        var symbol = new esri.symbol.SimpleLineSymbol("STYLE_SOLID", new dojo.Color([140, 20, 20, 0.5]), 5);
        for (var i = 0, il = featureSet.features.length; i < il; i++) {
            //Get the current feature from the featureSet.
            //Feature is a graphic
            var graphic = featureSet.features[i];
            graphic.setSymbol(symbol);
            //Add graphic to the map graphics layer.
            //routelyr.add(graphic);
            //myMap.graphics.add(graphic);
            if (i === 0) {
                zoomext.xmin = graphic.geometry.getExtent().xmin;
                zoomext.ymin = graphic.geometry.getExtent().ymin;
                zoomext.xmax = graphic.geometry.getExtent().xmax;
                zoomext.ymax = graphic.geometry.getExtent().ymax;
            }
            if (graphic.geometry.getExtent().xmin < zoomext.xmin) { zoomext.xmin = graphic.geometry.getExtent().xmin; }
            if (graphic.geometry.getExtent().ymin < zoomext.ymin) { zoomext.ymin = graphic.geometry.getExtent().ymin; }
            if (graphic.geometry.getExtent().xmax > zoomext.xmax) { zoomext.xmax = graphic.geometry.getExtent().xmax; }
            if (graphic.geometry.getExtent().ymax > zoomext.ymax) { zoomext.ymax = graphic.geometry.getExtent().ymax; }
        }

        if (zoom !== 0) {
            myMap.setExtent(zoomext, true);
        }

    });
    routeqt.execute(routequery);
    //query route_stops
    //if (hfn !== true) {
    if ((route == "55") || (route == "888")) {
        drawRouteNodes(route);
    }
        stopNodeRefresh(route);
    }
    function idRouteEvt(idResults, evt) {
        //myMap.infoWindow.resize(415, 200);
        var routelist,routestring;
        var routeliststring;
        var streetname;
        routeliststring = idResults[0].feature.attributes.ROUTES;
        streetname = idResults[0].feature.attributes.NAME;
        routelist = routeliststring.split(",");

        var routes = sortRouteArray(routelist);
        var infowidth = 250;
        var infoheight = 200;
        //Build info window
        var content = "<div class=\"popup\"><div class=\"cTitle\"> " + streetname + " </div>";
        if (routes.length < 4) {
            //infoheight = 150 + routes.length * 10;
            infoheight = 160;
            //routestring = "<b>Served by</b><br/><div class=\"routelist style=\"height: 70px; overflow-x: hidden; overflow-y: visible; scrollbar-arrow-color: blue; scrollbar-face-color: #e7e7e7; scrollbar-3dlight-color: #a0a0a0; scrollbar-darkshadow-color:#888888\">";
            routestring = "<b>Served by</b><div class=\"routelistsmall\">";
        }
        else {
            infoheight = 200;
            //infowidth = infowidth + 35;
            //routestring = "<b>Served by</b><br/><div class=\"routelist\" style=\"height: 90px; overflow-x: hidden; overflow-y: scroll; scrollbar-arrow-color: blue; scrollbar-face-color: #e7e7e7; scrollbar-3dlight-color: #a0a0a0; scrollbar-darkshadow-color:#888888\">";
            routestring = "<b>Served by</b><br/><div class=\"routelist\">";
        }
        //infoheight = 150 + routes.length * 10

        var rURLP = "/Schedules/WebSchedules.aspx?route=";
        var rURLNTpre = "/Mobile/Nextrip.aspx%5C?";
        var strRoute = "route=";
        var strDir = "&direction=";
        var strStop = "&stop=";
        var rURLS = ".asp";
        var rtestring = "Rte";
        var nodeid = 0;
        var dirs = "";
        var curRoute = dojo.byId("hidroute").value;
        for (var i = 0, len = routes.length; i < len; ++i) {
            var rt = routes[i];
            routeStore.fetchItemByIdentity({
                identity: rt,
                onItem: function(item) {
                    if (routeStore.isItem(item)) {
                        var routeid = routeStore.getValue(item, "LINE_ID");
                        var routedesc = routeStore.getValue(item, "Description");
                        var schedulelink = "<a href= \"" + rURLP + routeid + "\" title=\"" + routedesc + "\" target=\"_blank\">" + routeid + "&nbsp; - &nbsp;" + routedesc + "</a>";
                        var cbhtmlstring;
                        var cblabelstring;
                        //URL with code to map new route if clicked - new version
                        if (routeid === curRoute) {
                            cbhtmlstring = "<input id=\"cb" + routeid + "\" dojotype=\"dijit.form.RadioButton\" onclick=\"javascript:OptionRoute(" + routeid + "," + "\'" + nodeid + "\'" + "," + "\'" + dirs + "\'" + ",0);return true;\" checked=\"checked\" name=\"optRoute\" type=\"radio\" />";
                            cblabelstring = "<label for=\"cb" + routeid + "\">" + schedulelink + "</label>";
                        }
                        else {
                            cbhtmlstring = "<input id=\"cb" + routeid + "\" dojotype=\"dijit.form.RadioButton\" onclick=\"javascript:OptionRoute(" + routeid + "," + "\'" + nodeid + "\'" + "," + "\'" + dirs + "\'" + ",0);return true;\" name=\"optRoute\" type=\"radio\" />";
                            cblabelstring = "<label for=\"cb" + routeid + "\">" + schedulelink + "</label>";
                        }
                        routestring = routestring + cbhtmlstring + cblabelstring + "<br/>";
                        //routestring = routestring + "<a href=\"#\" onclick=\"javascript:NewRoute(" + routeid + ", 0);return false;\">" + routeid + " " + routedesc + "</a> " + schedulelink + "<br/>"
                        //                }

                        rtestring = "Rte";
                    } 
                    //else {
                        //This should never occur.
                    //}
                },
                onError: function(item, request) {
                    /* Handle the error... */
                    var ytt = 0
                    //console.log("Problem identifying route: " + rt);
                }
            });
        }

        //Trip planner string
        //var tripplanstring = "</div><div class=\"pfooter\"><b>Plan a transit trip:</b>&nbsp<a href=\"/TripPlanner/Default.aspx?s-dest=%26lt%3b" + escape(siteID) + "%26gt%3b+%23+" + escape(siteon) + "+%26amp%3b+" + escape(siteat) + "%7c" + escape(CTU_NAME) + "%7c" + UTMY + "%7c" + UTMX + "%7c%7c%7c%7c0%7c0%7c0%7c0%7cStop%7c0\" target=\"_blank\">To here</a> | " + "<a href=\"/TripPlanner/Default.aspx?s-orig=%26lt%3b" + siteID + "%26gt%3b+%23+" + escape(siteon) + "+%26amp%3b+" + escape(siteat) + "%7c" + escape(CTU_NAME) + "%7c" + UTMY + "%7c" + UTMX + "%7c%7c%7c%7c0%7c0%7c0%7c0%7cStop%7c0\" target=\"_blank\">From here</a></div>";
        var tripplanstring = ""; 
        content = content + "<div class=\"pContent\">" + routestring + "</div>" + tripplanstring + "</div>";
        myMap.infoWindow.resize(infowidth, infoheight);
        
        myMap.infoWindow.setTitle("<div class=\"pTitle\">Routes</div>");
        myMap.infoWindow.setContent(content);
        myMap.infoWindow.show(evt.screenPoint, myMap.getInfoWindowAnchor(evt.screenPoint));
    }


    function idRoutes(evt) {
        //Geographically search for nearbyRoutes - should be fired on map click when another feature has not been clicked.
        //console.log("id routes event")
        //http://gis2.metc.state.mn.us/ArcGIS/rest/services/transit/TIM_AllBusRoutes/MapServer/identify?geometryType=esriGeometryPoint&geometry={%22x%22:473928.766,%22y%22:4979697.338,%22spatialReference%22:{%22wkid%22:26915}}&sr=26915&layers=0&tolerance=5&mapExtent=466089,4977512,477500,4987134&imageDisplay=600,550,96&returnGeometry=false
        //http://testgis/ArcGIS/rest/services/Transit/NexTripAllBusRoutes/MapServer/identify?geometryType=esriGeometryPoint&geometry={%22x%22:487091,%22y%22:4978092,%22spatialReference%22:{%22wkid%22:26915}}%0D%0A&sr=&layers=all:1&tolerance=3&mapExtent=466089,4977512,477500,4987134&imageDisplay=600,550,96&returnGeometry=false
        var routeIdentifyTask = new esri.tasks.IdentifyTask("http://gis2.metc.state.mn.us/ArcGIS/rest/services/transit/TIM_AllBusRoutes/MapServer");
        //var routeIdentifyTask = new esri.tasks.IdentifyTask("http://raapgis1p.mc.local/ArcGIS/rest/services/transit/TIM_AllBusRoutes/MapServer");
        var identifyParams = new esri.tasks.IdentifyParameters();

        identifyParams.tolerance = 3;
        identifyParams.returnGeometry = false;
        identifyParams.layerIds = [1];
        //identifyParams.layerOption = "LAYER_OPTION_ALL"
        identifyParams.layerOption = esri.tasks.IdentifyParameters.LAYER_OPTION_ALL;
        identifyParams.geometry = evt.mapPoint;
        identifyParams.mapExtent = myMap.extent;

        routeIdentifyTask.execute(identifyParams, function(idResults) { idRouteEvt(idResults, evt); });

    }

//The ticking clock function
function TimeTick() {
    //var AMPM;
    var timestring;
    //if hidstop value is Null then refresh the nextrip info
    if (typeof dojo.byId("hidstop").value != 'undefined') {
        if (dojo.byId("hidstop").value !== '') {
            fillNexTrip(dojo.byId("hidstop").value);
        }
    }
    
    //grab updated time
    timeLocal = new Date();
    //add time difference
    timeLocal.setMilliseconds(timeLocal.getMilliseconds() - millDiff);
    var hours = timeLocal.getHours();
    var minutes = timeLocal.getMinutes();
    var suffix = "AM";
    if (hours >= 12) {
        suffix = "PM";
        hours = hours - 12;
    }
    if (hours === 0) {
        hours = 12;
    }


    if (minutes < 10){
        minutes = "0" + minutes;
    }

    timestring = hours + ":" + minutes + " " + suffix;

    //display the value
    document.getElementById("spanTime").innerHTML = "Current Time: " + timestring;
}
//function NewRoute(route, zoom) {
    //ClearGraphics();
    //ClearBuses();
    //dojo.byId("hidroute").value = route;
    //drawRoutes(route, zoom);
    //loadBusData(route);
    //clearInterval(busrefresh);
    //busrefresh = setInterval("refreshCurrent(" + dojo.byId("hidroute").value + ")", 30000);
//}
function configparams() {
    var lods = myMap.__tileInfo.lods.length;
    //Create graphics layers
    nodelyr = new esri.layers.GraphicsLayer();
    routelyr = new esri.layers.GraphicsLayer();
    if (dojo.isIE) {
        stoplyr = new esri.layers.GraphicsLayer(true, "stopslyr");
    }
    else {
        stoplyr = new esri.layers.GraphicsLayer(true, "stopslyr");
    }
    prlyr = new esri.layers.GraphicsLayer();
    TTsignlyr = new esri.layers.GraphicsLayer();
    TTlyr = new esri.layers.GraphicsLayer();
    GoToCardLyr = new esri.layers.GraphicsLayer();
    niceRidelyr = new esri.layers.GraphicsLayer();
    hourcarlyr = new esri.layers.GraphicsLayer();
    gclayer = new esri.layers.GraphicsLayer();
    

    blueStopSymb = new esri.symbol.PictureMarkerSymbol('images/bus-blue.png', 10, 10);
    redStopSymb = new esri.symbol.PictureMarkerSymbol('images/bus-red.png', 20, 20);

    
    
    //grayStopSymb
    myMap.addLayer(routelyr);
    myMap.addLayer(gclayer);
    myMap.addLayer(hourcarlyr);
    myMap.addLayer(niceRidelyr);
    myMap.addLayer(GoToCardLyr);
    myMap.addLayer(stoplyr);
    //dojo.connect(stoplyr, "onUpdate", hideLoading);
    myMap.addLayer(prlyr);
    myMap.addLayer(nodelyr);
    myMap.addLayer(TTsignlyr);
    myMap.addLayer(TTlyr);
    


    //prlyr.hide();

    if (gup('route') !== '') {
        var routeid = gup('route');
        //Set hidden field value
        dojo.byId("hidroute").value = routeid;
        if ((gup('bbox') !== '')) {
            NewRoute(routeid, 0);
        } else {
            NewRoute(routeid, 1); 
        }
    }
    if (gup('stopid') !== '') {
        var stopid = gup('stopid');
    }

    
    
    
    //Draw Park Rides
    drawParkRides();
    drawTTPoints();
    //drawGoToCards();
    var scalebar = new esri.dijit.Scalebar({
        map:myMap,
        attachTo:"bottom-right",
        scalebarUnit:'english'
    });

    dojo.connect(myMap, "onExtentChange", extentChange);
    dojo.connect(myMap,"onUpdateStart",showLoading);
    dojo.connect(myMap,"onUpdateEnd",hideLoading);
    listenMapClick();
    dojo.connect(myMap.graphics, "onClick", function(evt) {
        myMap.infoWindow.resize(320, 190);
    });
    var mySlider = dojo.byId("mapDiv_zoom_slider");
    //console.log("slider:");
    //console.dir(mySlider);
    dojo.connect(mySlider, "onmouseover", function (e) {
        $(".dijitRuleLabelContainer").css("display","block"); 
        //showLabels(2);
    });
    dojo.connect(mySlider, "onmouseout", function (e) {
        $(".dijitRuleLabelContainer").css("display","none"); 
        //showLabels(1);
    }); 
}

function fireMapMouseUp(e) {
    var oEvent = null;

    if (document.createEvent) {
        oEvent = document.createEvent("MouseEvents");
        oEvent.initMouseEvent("mouseup", true, true, window, 0, 0, 0, e.pageX, e.pageY, false, false, false, false, 0, null);
    } else if (document.createEventObject) {
        oEvent = document.createEventObject();
        oEvent.detail = 0;
        oEvent.screenX = 0;
        oEvent.screenY = 0;
        oEvent.clientX = e.pageX;
        oEvent.clientY = e.pageY;
        oEvent.ctrlKey = false;
        oEvent.altKey = false;
        oEvent.shiftKey = false;
        oEvent.metaKey = false;
        oEvent.button = 0;
        oEvent.relatedTarget = null;
    }

    var fired = false;
    var mapElement = document.getElementById('mapDiv');

    if (document.createEvent) {
        fired = mapElement.dispatchEvent(oEvent);
    } else if (document.createEventObject) {
        fired = mapElement.fireEvent('onmouseup', oEvent);
    }

}

function showLoading(){          
    var loading = dojo.byId("loadingImg");
    esri.show(loading);
    //myMap.disableMapNavigation();
    //myMap.hideZoomSlider();
          
}
function hideLoading(){
    var loading = dojo.byId("loadingImg");  
    esri.hide(loading);
    //myMap.enableMapNavigation();
    //myMap.showZoomSlider();
}
function init() {
        TimeTick();
        var timeClock = setInterval("TimeTick()", 30000);
        esriConfig.defaults.map.slider = { left: "30px", top: "80px", width: null, height: "200px" };
        //build slider labels
        var sliderlabels = [];
        sliderlabels[0] = "";
        sliderlabels[1] = "View Park and Rides";
        sliderlabels[2] = "View Transit Routes";
        sliderlabels[3] = "";
        sliderlabels[4] = "";
        sliderlabels[5] = "";
        sliderlabels[6] = "View Transit Stops";
        sliderlabels[7] = "";
        sliderlabels[8] = "";
        sliderlabels[9] = "";
        if (dojo.isIE) {
            sliderlabels[6] = "";
            sliderlabels[7] = "View Transit Stops";
        } 
        esriConfig.defaults.map.sliderLabel = {
            tick: 2,
            labels: sliderlabels,
            style: "white-space: nowrap;overflow: visible;width:0em; font-family:Arial; font-size:85%; font-weight:bold; color:#fff; padding-left:8px;"
        };

        //esriConfig.defaults.map.panDuration = 1000; //time in milliseconds; default panDuration:250
        esriConfig.defaults.map.panRate = 1; //refresh rate of zoom animation; default panRate:25
        esri.config.defaults.map.logoLink = "http://metrotransit.org";
        initExtent = new esri.geometry.Extent({ "xmin": 380425.190770931, "ymin": 4906135.56930647, "xmax": 577580.229321643, "ymax": 5036910.32510176, "spatialReference": { "wkid": 26915} });
        
        //zoomext = new esri.geometry.Extent({ "xmin": 466089, "ymin": 4977512, "xmax": 477500, "ymax": 4987134, "spatialReference": { "wkid": 26915} });
        //zoomext = new esri.geometry.Extent({ "xmin": 465089, "ymin": 4957512, "xmax": 500000, "ymax": 4998134, "spatialReference": { "wkid": 26915} });
        //bbox=465089,4957512,500000,4998134

        var spatialRef = new esri.SpatialReference({ wkid: 26915 });
        var startExtent = new esri.geometry.Extent();
        routeStore = new dojo.data.ItemFileReadStore({
            url: "RouteList.ashx"
        });
        routeStore.fetchItemByIdentity({
            identity: 3,
            onItem: function(item) { }
        });
        dojo.parser.parse();
        myMap = new esri.Map("mapDiv", { extent: zoomext,logo: false});
        //myMap = new esri.Map("mapDiv", { extent: zoomext});

        var ADASplash;

        if ($(window).height() < 600) {
            ADASplash = new dijit.Dialog({
                id: "ADASplash",
                title: "Interactive Twin Cities Transit Map",
                style: "width: 40em; color:#ffffff",
                href: "SplashSmall.htm"
            });
        }
        else {
            ADASplash = new dijit.Dialog({
                id: "ADASplash",
                title: "Interactive Twin Cities Transit Map",
                style: "width: 40em;color:#ffffff",
                href: "Splash.htm"
            });

        }
        // show the dialog
        //DEV ONLY Comment out before moving to production so splash always shows in Dev
        //dojo.cookie("Map.ShowSplash", null, { expires: -1 });
        
        //
        var ShowSplash = dojo.cookie("Map.ShowSplash");
        var accSettingsCheck = dojo.byId("chkACCSplash");
        //document.forms[0].checkbox.checked = true
        if (typeof (ShowSplash) !== "undefined") {
            if (ShowSplash == "true") {
                
                //set about accordion pane checkbox to checked.
                dojo.byId("chkACCSplash").click();
                ADASplash.show();

            }

        }
        else {
            dojo.cookie("Map.ShowSplash", true);
            dojo.byId("chkACCSplash").click();
            ADASplash.show();
        }

        dojo.connect(dijit.byId("ADASplash"), "onClick", ADASplash, "hide");

           if (gup('bbox') !== '') {
               var bbox = gup('bbox');
               //check if bbox has 4 elements
               if (bbox.split(",").length === 4) {
                   var env = bbox.split(",");
                   //check values of envelop. Must be numbers
                   //startExtent.xmin = parseFloat(env[0]);startExtent.ymin = parseFloat(env[1]);startExtent.xmax = parseFloat(env[2]);startExtent.ymax = parseFloat(env[3]);startExtent.spatialReference = spatialRef;

                   zoomext = new esri.geometry.Extent({ "xmin":  parseFloat(env[0]), "ymin":  parseFloat(env[1]), "xmax":  parseFloat(env[2]), "ymax":  parseFloat(env[3]), "spatialReference": { "wkid": 26915} });
                   //zoomext = startExtent;
               }
               else {
                   bbox = null;
                   zoomext = new esri.geometry.Extent({ "xmin": 465089, "ymin": 4957512, "xmax": 500000, "ymax": 4998134, "spatialReference": { "wkid": 26915} });
                   //zoomext = initExtent;
               }
           }
           else {
               //bbox = null;
               zoomext = new esri.geometry.Extent({ "xmin": 465089, "ymin": 4957512, "xmax": 500000, "ymax": 4998134, "spatialReference": { "wkid": 26915} });
           }
           
           myMap.setExtent(zoomext);
        var iParms = new esri.layers.ImageParameters();
        iParms.layerOption = "LAYER_OPTION_SHOW";
        iParms.layerIds = [0]; //  array of layer ids

        dojo.connect(myMap, "onLoad", configparams);
        dojo.connect(myMap, "onMouseOut", fireMapMouseUp);
        //connect to window's resize event

        dojo.connect(window, "onresize", function() {
            //clear any existing resize timer
            if (dojo.isIE) {
                var windowTimer;
                clearTimeout(windowTimer);
                //create new resize timer with delay of 500 milliseconds
                windowTimer = window.setTimeout(function() { myMap.resize(); $("#accordion").accordion("resize"); }, 500);
            }
            else {
                //not ie
                myMap.resize();

                $("#accordion").accordion("resize");

                dojo.byId("ListBoxRoutes").style.height = "200%";
                
            }
        });
        basemap = new esri.layers.ArcGISTiledMapServiceLayer("http://gis.metc.state.mn.us/ArcGIS/rest/services/BaseLayer/UTMBaseMap/MapServer");
        hybrid = new esri.layers.ArcGISTiledMapServiceLayer("http://gis.metc.state.mn.us/ArcGIS/rest/services/BaseLayer/HybridBaseMap/MapServer", { visible: false });
        //var allBusRoutesLayer = new esri.layers.ArcGISTiledMapServiceLayer("http://raapgis1p.mc.local/ArcGIS/rest/services/transit/TIM_AllBusRoutes/MapServer",{ "id":"allbusrts", "opacity":0.35, "visible": true });
        busRoutesMapLayer = new esri.layers.ArcGISDynamicMapServiceLayer("http://gis2.metc.state.mn.us/ArcGIS/rest/services/transit/TIM_BusRoutes/MapServer", { "opacity": 0.66 });
        var highwaySignsLayer = new esri.layers.ArcGISDynamicMapServiceLayer("http://gis2.metc.state.mn.us/ArcGIS/rest/services/transit/TIM_Points/MapServer", { "id":"hwysigns", "opacity": 1, "imageParameters": iParms });
        var allBusRoutesLayer = new esri.layers.ArcGISDynamicMapServiceLayer("http://gis2.metc.state.mn.us/ArcGIS/rest/services/transit/TIM_AllBusRoutes/MapServer",{ "id":"allbusrts", "opacity":0.35, "imageParameers": iParms });

        myMap.addLayer(basemap, 0);
        satlayer = new my.fsaLayer();
        myMap.addLayer(satlayer, 1);
        myMap.addLayer(hybrid, 2);
        myMap.addLayer(busRoutesMapLayer);
        myMap.addLayer(highwaySignsLayer);
        myMap.addLayer(allBusRoutesLayer,3);
        busRoutesMapLayer.setVisibleLayers([]);
      }
      
dojo.addOnLoad(init);

function search(searchString) {
    if (searchString === "FTH"){
        searchString = "Heywood";
    }
    //console.log("search: " + escape(searchString));
    gclayer.clear();
    var GCurl = "http://gis2.metc.state.mn.us/ArcGIS/rest/services/Metro_Transit_Composite/GeocodeServer/findAddressCandidates?SingleLine=" + escape(searchString) + "&outFields=Loc_name%2C+User_fld&outSR=&f=json&callback=searchResult";
    //make request
    bObj = new JSONscriptRequest(GCurl);
    // Build the dynamic script tag
    bObj.buildScriptTag();
    // Add the script tag to the page
    bObj.addScriptTag();
}

function mapSearchPoint(gcaddress, gcx,gcy){
    gclayer.clear();
    var thepoint = new esri.geometry.Point(gcx, gcy, 26915);
    var gcpms = new esri.symbol.PictureMarkerSymbol('images/SearchPin.PNG', 62, 62);
    var gcattr = { "address": unescape(gcaddress)};
    var searchPopupContent = "<div class=\"popup\"><div class=\"cTitle\">" + unescape(gcaddress) + "</div><div class=\"pContent\"></div>";
    var postdiv = "</div>";
    var tripplanstring = "<div class=\"pfooter\"><b>Plan a transit trip:</b>&nbsp<a href=\"/TripPlanner/Default.aspx?s-dest=%23+" + gcaddress.replace(" ", "+") + "%7c" + "" + "%7c" + parseInt(gcy) + "%7c" + parseInt(gcx) + "%7c%7c%7c%7c0%7c0%7c0%7c0%7cStop%7c0\" target=\"_blank\">To here</a> | " + "<a href=\"/TripPlanner/Default.aspx?s-orig=%23+" + gcaddress.replace(" ", "+") + "%7c" + "city+not+specified" + "%7c" + parseInt(gcy) + "%7c" + parseInt(gcx) + "%7c%7c%7c%7c0%7c0%7c0%7c0%7cStop%7c0\" target=\"_blank\">From here</a></div>";
    var gcitInfoTemplate = new esri.InfoTemplate("<div class=\"pTitle\">Search Result</div>", searchPopupContent + tripplanstring + postdiv);
    var gcgraphic = new esri.Graphic(thepoint, gcpms, gcattr, gcitInfoTemplate);
    gclayer.add(gcgraphic);
    zoomext.xmin = Number(gcx) - 250;
    zoomext.ymin = Number(gcy) - 250;
    zoomext.xmax = Number(gcx) + 250;
    zoomext.ymax = Number(gcy) + 250;
    myMap.setExtent(zoomext, true);
}

function searchResult(jsonSearch) {
    var candidates = jsonSearch.candidates;
    if (candidates.length == 0) {
        //No results
        dojo.byId("searchResults").innerHTML = "<br/><br/>No results";
    }
    else {
        //one or more results
        //sort candidates by geocoding result score
        candidates.sort(function (a, b) { return parseFloat(b.score) - parseFloat(a.score) });

        //remove duplicates
        var newcandidates = [];
        var uniquecandidates = {};
        dojo.forEach(candidates, function(item) {
            if (!uniquecandidates[item.address]) {
                    newcandidates.push(item);
                    uniquecandidates[item.address] = item;
            }
        });

        var gcpoints = new esri.geometry.Multipoint(myMap.spatialReference);
        var i = 0;
        var resultstring = "<br/><br/>Choose:<br/><ul>";
        dojo.some(newcandidates, function (candidate) {
            var gcpoint = new esri.geometry.Point(candidate.location.x, candidate.location.y, jsonSearch.spatialReference.wkid);
            var sCand = "\"" + escape(candidate.address) + "\"," + candidate.location.x + "," + candidate.location.y;
            resultstring = resultstring + "<li>" + "<span class=\"searchresultcls\" id=\"searchresult" + i.toString() + "\" onclick='mapSearchPoint(" + sCand + ")'><a href=\"#\">" + candidate.address + "</a></li></span>";
            var gcarray;
            gcpoints.addPoint(gcpoint); 
            i++;
            if (i >= 10) {
                return true;
            }
        });
        resultstring = resultstring + "</ul>";
        //}
        if (gcpoints.getExtent().getHeight() < 2000 && gcpoints.getExtent().getWidth() < 2000) {
            myMap.setExtent(gcpoints.getExtent().expand(4));
            //console.log("extent factored");
        }
        dojo.byId("searchResults").innerHTML = resultstring;
    }
}
function Button2_onclick() {
    //dojo.byId("searchResults").innerHTML = "";
    dojo.byId("searchResults").innerHTML = "<img src=\"images/ajax-loader.gif\" alt=\"Search Loading\" />";
    gclayer.clear();
    var SelText = dojo.byId("MapSearchInput").value;
    search(SelText);
}


function ListBoxRoutes_onclick(select, maxNumber) {
    //Clear existing Route Graphics
    ClearRouteGraphics();
    //ClearBuses();
    //clearInterval(busrefresh)
    
    //close infowindow

    if (myMap._infoWindowIsShowing === true) {
        myMap.infoWindow.hide();
    }
    
    dojo.byId("hidroute").value = "";
    //Check for multiple Routes
    var selectedRoutes = [];
    var routesList = dojo.byId("ListBoxRoutes");
    var i;
    var count = 0;
    for (i = 0; i < routesList.options.length; i++) {
        if (routesList.options[i].selected) {
            var multiRoute = routesList.options[i].value.split(",");
            //use for aggregating route selections in the future. e.g. urban local routes.
//            if (multiRoute.length > 0) {
//                //multiRoute);
//                for (j = 0; j < multiRoute.length; j++) {
//                    selectedRoutes[count] = multiRoute[j];
//                    count++;
//                }
//            }
//            else {
                selectedRoutes[count] = routesList.options[i].value;
                if (selectedRoutes.length > maxNumber) {
                    alert('You may only choose ' + maxNumber + ' routes.');
                    routesList.options[i].selected = false;
                    selectedRoutes.pop();
                    document.body.focus();
                }  
                count++;
                
//            }
            
        }
    }
    drawRoutes(selectedRoutes, 1, 1);
    
}

function NewRoute(route, zoom){
    ClearGraphics();
    ClearBuses();
    dojo.byId("hidroute").value = route;
    drawRoutes(route, zoom);
    loadBusData(route);
    //clearInterval(busrefresh);
    //busrefresh = setInterval("refreshCurrent(" + dojo.byId("hidroute").value + ")", 30000);
}
function OpenNextripStart() {
    window.open("/NexTripBadge.aspx", "", "width=350px,height=480px,scrollbars=yes,menubar=no,status=no,location=no,toolbar=no,titlebar=no;");
}


function OpenNextrip(stopid) {
    if (stopid === 'null') {
        var nextripstring = "http://metrotransit.org/NexTripBadge.aspx";
    }
    else {
        nextripstring = "http://metrotransit.org/NexTripBadge.aspx" + "?stopnumber=" + stopid;
    }
    window.open(nextripstring, "", "width=350px,height=500px,scrollbars=yes,menubar=no,status=no,location=no,toolbar=no;resizable=no,top=100,left=300,screenX=300,screenY=300;");
}

function OptionRoute(route, stopid, dirID, zoom) {

    var dir;
    //SB = 1
    //EB = 2
    //WB = 3
    //NB = 4
    
    switch(dirID){
        case "EB":
            dir = 2;
            break;
        case "WB":
            dir = 3;
            break;
        case "NB":
            dir = 4;
            break;
        case "SB":
            dir = 1;
            break;
        default:
            break;
    }

    //nextripstring = "/Mobile/Nextrip.aspx?route=" + route + "&direction=" + dir + "&stop=" + stopid;
    
    //http: //nextrip.metc.state.mn.us/NextripFull.aspx
    //Get dir from stop and route+
    //window.open(nextripstring, "", "width=328px,height=580px,scrollbars=no,menubar=no,status=no,location=no,toolbar=no,titlebar=no;");
    //var iH = "<a target=_blank href=\"" + nextripstring + "\" tabindex=-1,onclick=window.open(" + nextripstring + ", \"\", \"width=328px,height=580px,scrollbars=no,menubar=no,location=no,toolbar=no,titlebar=no;>Launch NexTrip in a separate window</a>";


    //var iH = "<hr/><a href=javascript://NexTrip id= \"activetab\" name=\"OpenNextripButton\" onClick=\"OpenNextrip(" + route + "," + dir + ",\'" + stopid + "\');\"><span>Launch <B><I>Nex</I>Trip</B> in a separate window</span></a>";
    //$("#nextriplaunch").html(iH);
    TimeTick();
    $("#accordion").accordion( 'activate' , 2 );

    NewRoute(route, zoom);
    //set list to point to selected route
    dojo.byId("ListBoxRoutes").value = route;
    //document.getElementById('dropdown').value = 'one';
    //window.open(nextripstring, "", "width=328px,height=580px,scrollbars=no,menubar=no,status=no,location=no,toolbar=no,titlebar=no;");
    //document.all.frNextrip.src = "http://www.yahoo.com";
}


function showSat() {
    //change color of text for zoom slider label
    $(".dijitRuleLabelContainer").css("color", "white");
    //$(".dijitRuleLabelContainer").css("background-color", "#0053A0");
    basemap.hide();
    satlayer.show();
    hybrid.show();
}

function showMap() {
    //change color of text for zoom slider label
    $(".dijitRuleLabelContainer").css("color", "#0053A0");
    //$(".dijitRuleLabelContainer").css("background-color", "white");
    satlayer.hide();
    hybrid.hide();
    basemap.show();
}

function ADASplashChkClick(value) {
    dojo.byId("chkACCSplash").click();
    showSplash(value);
}
function showSplash(value) {
    dojo.cookie("Map.ShowSplash", value);
}

function AccSplashChkClick(value) {
    showSplash(value);
}



