/*---------------------------------------------------------------------
 * BuckeyeTrafficMode Enum Type
 *
 * This type represents the mode the map is operating in.  
 *--------------------------------------------------------------------*/

function BuckeyeTrafficMode(name) {
    this._name = name;
}

BuckeyeTrafficMode.prototype.toString = function() {
    return this._name;
}

// represents the view mode where a user can interact with the map freely
BuckeyeTrafficMode.VIEW = new BuckeyeTrafficMode('view');

// represents the view mode in which a user creates a camera site
BuckeyeTrafficMode.CREATE_CAMERA = new BuckeyeTrafficMode('create_camera');

// represents the edit mode in which users can modify a camera site
BuckeyeTrafficMode.EDIT_CAMERA = new BuckeyeTrafficMode('edit_camera');

// represents the camera delete mode
BuckeyeTrafficMode.DELETE_CAMERA = new BuckeyeTrafficMode('delete_camera');

// opens a window to select a camera to control 
BuckeyeTrafficMode.CONTROL_CAMERA = new BuckeyeTrafficMode('control_camera');

// opens a window to select a camera for fullscreen view
BuckeyeTrafficMode.CAMERA_PANEL = new BuckeyeTrafficMode('camera_panel');

// opens a camera bank window
BuckeyeTrafficMode.CAMERA_BANK = new BuckeyeTrafficMode('camera_bank');

// opens a window that can edit camera tours
BuckeyeTrafficMode.EDIT_CAMERA_TOURS = new BuckeyeTrafficMode('edit_camera_tours');

// represents the road activity creation mode
BuckeyeTrafficMode.CREATE_ROAD_ACTIVITY = new BuckeyeTrafficMode('create_road_activity');

// represents the edit road activity mode
BuckeyeTrafficMode.EDIT_ROAD_ACTIVITY = new BuckeyeTrafficMode('edit_road_activity');

// represents the delete road activity mode
BuckeyeTrafficMode.DELETE_ROAD_ACTIVITY = new BuckeyeTrafficMode('delete_road_activity');

// represents the edit winter location activity mode
BuckeyeTrafficMode.EDIT_WINTER_LOCATION = new BuckeyeTrafficMode('edit_winter_location');

// represents the add message sign mode
BuckeyeTrafficMode.ADD_MESSAGE_SIGN = new BuckeyeTrafficMode('add_message_sign');

// represents the edit message sign mode
BuckeyeTrafficMode.EDIT_MESSAGE_SIGN = new BuckeyeTrafficMode('edit_message_sign');

// represents the delete message sign mode
BuckeyeTrafficMode.DELETE_MESSAGE_SIGN = new BuckeyeTrafficMode('delete_message_sign');

// represents the manage message sign mode
BuckeyeTrafficMode.MANAGE_MESSAGE_SIGN = new BuckeyeTrafficMode('manage_message_sign');

// represents the add har mode
BuckeyeTrafficMode.ADD_HAR = new BuckeyeTrafficMode('add_har');

// represents the edit har mode
BuckeyeTrafficMode.EDIT_HAR = new BuckeyeTrafficMode('edit_har');

// represents the delete har mode
BuckeyeTrafficMode.DELETE_HAR = new BuckeyeTrafficMode('delete_har');

// represents the manage har mode
BuckeyeTrafficMode.MANAGE_HAR = new BuckeyeTrafficMode('manage_har');

BuckeyeTrafficMode.prototype.getModeByString = function(name) {
    switch(name) {        
        case 'view': return BuckeyeTrafficMode.VIEW;
        case 'create_camera': return BuckeyeTrafficMode.CREATE_CAMERA;
        case 'edit_camera': return BuckeyeTrafficMode.EDIT_CAMERA;
        case 'delete_camera': return BuckeyeTrafficMode.DELETE_CAMERA;
        case 'control_camera': return BuckeyeTrafficMode.CONTROL_CAMERA;
        case 'camera_panel': return BuckeyeTrafficMode.CAMERA_PANEL;
        case 'camera_bank': return BuckeyeTrafficMode.CAMERA_BANK;
        case 'edit_camera_tours': return BuckeyeTrafficMode.EDIT_CAMERA_TOURS;
        case 'create_road_activity': return BuckeyeTrafficMode.CREATE_ROAD_ACTIVITY;
        case 'edit_road_activity': return BuckeyeTrafficMode.EDIT_ROAD_ACTIVITY;
        case 'delete_road_activity': return BuckeyeTrafficMode.DELETE_ROAD_ACTIVITY;
        case 'edit_winter_location': return BuckeyeTrafficMode.EDIT_WINTER_LOCATION;
        case 'add_message_sign': return BuckeyeTrafficMode.ADD_MESSAGE_SIGN;
        case 'edit_message_sign': return BuckeyeTrafficMode.EDIT_MESSAGE_SIGN;
        case 'delete_message_sign': return BuckeyeTrafficMode.DELETE_MESSAGE_SIGN;
        case 'manage_message_sign': return BuckeyeTrafficMode.MANAGE_MESSAGE_SIGN;
        case 'add_har': return BuckeyeTrafficMode.ADD_HAR;
        case 'edit_har': return BuckeyeTrafficMode.EDIT_HAR;
        case 'delete_har': return BuckeyeTrafficMode.DELETE_HAR;
        case 'manage_har': return BuckeyeTrafficMode.MANAGE_HAR;
        // we'll default to sending back the view state, however we should throw an exception or create an UNKNOWN_MODE obj
        default: return BuckeyeTrafficMode.VIEW;
    }
}

var openwindows = new Array();
function addWindow(w)
{
    openwindows[openwindows.length] = w;
}
function closeWindows()
{
    var i;
    for(i=0; i<openwindows.length; i++)
    {
        openwindows[i].close();
    }
}

//------------------------------------------------------------------------------------------------------------
window.onresize = function(){ doResizeElements(); }
//------------------------------------------------------------------------------------------------------------
var adminMode = "default";
var regionViewed = "State";
var map = null;
var mapContainerId = 'BuckeyeTrafficMap';
var control = null;
var reusableVEShape = null;
var reusableVEShapeLayer = null;
var reusableVEPixel = null;
var reusableVELatLong = null;
var clientH = null;
var clientW = null;
var currentMapZoomLevel = null;
var shapeLayersArr = new Array({"title":"Base Layer"},{"title":"Working Layer"});

var regionsAndCounties =[
{"Region":"NorthEast", "Positioning":{"minLat":"39.85", "maxLat":"41.7716723", "minLon":"-83.0", "maxLon":"-80.51937819", "centerLat":"40.82085644361064", "centerLon":"-81.759689095"}, "Counties":"ASD~ATB~BEL~CAR~COL~COS~CRA~CUY~ERI~GEA~GUE~HAS~HOL~HUR~JEF~KNO~LAK~LIC~LOR~MAH~MED~MRW~MUS~POR~RIC~STA~SUM~TRU~TUS~WAY"},
{"Region":"NorthWest", "Positioning":{"minLat":"39.85", "maxLat":"41.97716723", "minLon":"-84.81996775", "maxLon":"-82.5", "centerLat":"40.92596493951429", "centerLon":"-83.65814208984375"}, "Counties":"ALL~CHP~CLA~CRA~DAR~DEF~DEL~ERI~FRA~FUL~HAN~HAR~HEN~HUR~LOG~LUC~MAD~MAR~MER~MIA~MRW~OTT~PAU~PUT~SAN~SEN~SHE~UNI~VAN~WIL~WOO~WYA"},
{"Region":"SouthEast", "Positioning":{"minLat":"38.40221813", "maxLat":"40.15", "minLon":"-83.0", "maxLon":"-80.51937819", "centerLat":"39.28329386893849", "centerLon":"-81.75750732421875"}, "Counties":"ATH~BEL~FAI~GAL~GUE~HOC~JAC~LAW~LIC~MEG~MOE~MRG~MUS~NOB~PER~PIC~PIK~ROS~SCI~VIN~WAS"},
{"Region":"SouthWest", "Positioning":{"minLat":"38.40221813", "maxLat":"40.15", "minLon":"-84.81996775", "maxLon":"-82.5", "centerLat":"39.28329386893849", "centerLon":"-83.65814208984375"}, "Counties":"ADA~BRO~BUT~CLA~CLE~CLI~DAR~FAI~FAY~FRA~GRE~HAM~HIG~HOC~JAC~LAW~MAD~MIA~MOT~PIC~PIK~PRE~ROS~SCI~VIN~WAR"},
{"Region":"Central", "Positioning":{"minLat":"39.3", "maxLat":"40.6", "minLon":"-83.5", "maxLon":"-82.1", "centerLat":"39.95606977009003", "centerLon":"-82.80120849609376"}, "Counties":"ASD~CHP~CLA~COS~CRA~FAI~FAY~FRA~HAR~HOC~HOL~KNO~LIC~LOG~MAD~MAR~MRW~MUS~PER~RIC~ROS~UNI~WYA"},
{"Region":"State", "Positioning":{"minLat":"38.40221813", "maxLat":"41.97716723", "minLon":"-84.81996775", "maxLon":"-80.51937819", "centerLat":"40.18969268", "centerLon":"-82.66967297"}, "Counties":"ADA~ALL~ASD~ATB~ATH~AUG~BEL~BRO~BUT~CAR~CHP~CLA~CLE~CLI~COL~COS~CRA~CUY~DAR~DEF~DEL~ERI~FAI~FAY~FRA~FUL~GAL~GEA~GRE~GUE~HAM~HAN~HAR~HAS~HEN~HIG~HOC~HOL~HUR~JAC~JEF~KNO~LAK~LAW~LIC~LOG~LOR~LUC~MAD~MAH~MAR~MED~MEG~MER~MIA~MOE~MOT~MRG~MRW~MUS~NOB~OTT~PAU~PER~PIC~PIK~POR~PRE~PUT~RIC~ROS~SAN~SCI~SEN~SHE~STA~SUM~TRU~TUS~UNI~VAN~VIN~WAR~WAS~WAY~WIL~WOO~WYA"}
];

//JSON example
//alert(regionsAndCounties[4].Region+"\n\n\n"+regionsAndCounties[4].Positioning.minLat+"\n\n\n"+regionsAndCounties[4].Counties.split("~")[7]);
/*
 Represents a lat/long bounding box with appropriate lattitude and longitude values for
 the four corners of the box.
*/
function BoundingBox () {
   this.topLeftLat = 0;
   this.topLeftLong = 0;            
   this.bottomRightLat = 0;
   this.bottomRightLong = 0;   
}

BoundingBox.prototype.getXml = function () { 
  xml = '<bounding_box ' + 
         '  topLeftLat=\"' + this.topLeftLat + '\"' +
         '  topLeftLong=\"' + this.topLeftLong + '\"' +
         '  bottomRightLat=\"' + this.bottomRightLat + '\"' +
         '  bottomRightLong=\"' + this.bottomRightLong + '\"' +	 
	 '/>';	 
  return xml;
}


// the default mode is viewing
var currentBuckeyeTrafficMode = BuckeyeTrafficMode.VIEW;
/*---------------------------------------------------------------------
 * BuckeyeTrafficMarker Enum Type
 *
 * This type represents different types of markers.
 *--------------------------------------------------------------------*/
function BuckeyeTrafficMarker(name, iconUrl) {
    this._name = name;
    this._iconUrl = iconUrl;

    if (arguments.length > 2){
        this._divClass = arguments[2];
    }
}

BuckeyeTrafficMarker.prototype.name = function() {
    return this._name;
}

BuckeyeTrafficMarker.prototype.toString = function() {
    return this._name;
}

BuckeyeTrafficMarker.prototype.icon = function() {
    return this._iconUrl;
}

BuckeyeTrafficMarker.prototype.divClass = function() {
    return this._divClass;
}

// represents a camera site on the map
BuckeyeTrafficMarker.CAMERA = new BuckeyeTrafficMarker("Camera Site", "images/iconsAndPins/purple_camera_sq.gif");

// represents various RWIS sites on the map
BuckeyeTrafficMarker.RWIS_DRY = new BuckeyeTrafficMarker("RWIS Site - Dry", "images/iconsAndPins/green_triangle.gif", "pinRwisDry");
BuckeyeTrafficMarker.RWIS_WET = new BuckeyeTrafficMarker("RWIS Site - Wet", "images/iconsAndPins/aqua_triangle.gif", "pinRwisWet");
BuckeyeTrafficMarker.RWIS_SNOW = new BuckeyeTrafficMarker("RWIS Site - Snow", "images/iconsAndPins/yellow_triangle.gif", "pinRwisSnow");
BuckeyeTrafficMarker.RWIS_ICE = new BuckeyeTrafficMarker("RWIS Site - Ice", "images/iconsAndPins/red_triangle.gif", "pinRwisIce");
BuckeyeTrafficMarker.RWIS_OTHER = new BuckeyeTrafficMarker("RWIS Site - Other", "images/iconsAndPins/white_triangle.gif", "pinRwisOther");
BuckeyeTrafficMarker.RWIS_ERROR = new BuckeyeTrafficMarker("RWIS Site - Other", "images/iconsAndPins/brown_triangle.gif", "pinRwisError");
BuckeyeTrafficMarker.RWIS_OUTDATED = new BuckeyeTrafficMarker("RWIS Site - Outdated", "images/iconsAndPins/black_triangle.gif", "pinRwisNoData");
BuckeyeTrafficMarker.RWIS_PUBLIC = new BuckeyeTrafficMarker("RWIS Site", "images/iconsAndPins/purple_triangle.gif", "pinRwisPublic");

//Represents various wind direction sensor on the map
BuckeyeTrafficMarker.WIND_NORTH = new BuckeyeTrafficMarker("WIND Direction - North", "images/winddirection/windnorth.gif", "pinWindNorth");
BuckeyeTrafficMarker.WIND_NORTHEAST = new BuckeyeTrafficMarker("WIND Direction - Northeast", "images/winddirection/windnortheast.gif", "pinWindNortheast");
BuckeyeTrafficMarker.WIND_EAST = new BuckeyeTrafficMarker("WIND Direction - East", "images/winddirection/windeast.gif", "pinWindEast");
BuckeyeTrafficMarker.WIND_SOUTHEAST = new BuckeyeTrafficMarker("WIND Direction - Southeast", "images/winddirection/windsoutheast.gif", "pinWindSoutheast");
BuckeyeTrafficMarker.WIND_SOUTH = new BuckeyeTrafficMarker("WIND Direction - South", "images/winddirection/windsouth.gif", "pinWindSouth");
BuckeyeTrafficMarker.WIND_SOUTHWEST = new BuckeyeTrafficMarker("WIND Direction - Southwest", "images/winddirection/windsouthwest.gif", "pinWindSouthWest");
BuckeyeTrafficMarker.WIND_WEST = new BuckeyeTrafficMarker("WIND Direction - West", "images/winddirection/windwest.gif", "pinWindWest");
BuckeyeTrafficMarker.WIND_NORTHWEST = new BuckeyeTrafficMarker("WIND Direction - Northwest", "images/winddirection/windnorthwest.gif", "pinWindNorthwest");
BuckeyeTrafficMarker.WIND_NONFUNCTIONING = new BuckeyeTrafficMarker("WIND Direction - Non-Functioning", "images/winddirection/wind_non.gif", "pinWindNonFunctioning");

// represents various Road Activity sites (by Status) on the map
BuckeyeTrafficMarker.ACCIDENT_OPEN = new BuckeyeTrafficMarker("Accident - Open", "images/bigDiamonds/green_diamond_a.gif", "pinAccidentGreen");
BuckeyeTrafficMarker.ACCIDENT_CLOSED = new BuckeyeTrafficMarker("Accident - Closed", "images/bigDiamonds/yellow_diamond_a.gif", "pinAccidentRed");
BuckeyeTrafficMarker.ACCIDENT_RESTRICTED = new BuckeyeTrafficMarker("Accident - Restricted", "images/bigDiamonds/red_diamond_a.gif", "pinAccidentYellow");

BuckeyeTrafficMarker.ROADWORK_OPEN = new BuckeyeTrafficMarker("Road Work - Open", "images/bigDiamonds/green_diamond_r.gif", "pinRoadworkGreen");
BuckeyeTrafficMarker.ROADWORK_CLOSED = new BuckeyeTrafficMarker("Road Work - Closed", "images/bigDiamonds/red_diamond_r.gif", "pinRoadworkRed");
BuckeyeTrafficMarker.ROADWORK_RESTRICTED = new BuckeyeTrafficMarker("Road Work - Restricted", "images/bigDiamonds/yellow_diamond_r.gif", "pinRoadworkYellow");

BuckeyeTrafficMarker.FLOODING_OPEN = new BuckeyeTrafficMarker("Flooding - Open", "images/bigDiamonds/green_diamond_f.gif", "pinFloodingGreen");
BuckeyeTrafficMarker.FLOODING_CLOSED = new BuckeyeTrafficMarker("Flooding - Closed", "images/bigDiamonds/red_diamond_f.gif", "pinFloodingRed");
BuckeyeTrafficMarker.FLOODING_RESTRICTED = new BuckeyeTrafficMarker("Flooding - Restricted", "images/bigDiamonds/yellow_diamond_f.gif", "pinFloodingYellow");

BuckeyeTrafficMarker.DEBRIS_OPEN = new BuckeyeTrafficMarker("Debris - Open", "images/bigDiamonds/green_diamond_d.gif", "pinDebrisGreen");
BuckeyeTrafficMarker.DEBRIS_CLOSED = new BuckeyeTrafficMarker("Debris - Closed", "images/bigDiamonds/red_diamond_d.gif", "pinDebrisRed");
BuckeyeTrafficMarker.DEBRIS_RESTRICTED = new BuckeyeTrafficMarker("Debris - Restricted", "images/bigDiamonds/yellow_diamond_d.gif", "pinDebrisYellow");

BuckeyeTrafficMarker.DISABLEDVEHICLE_OPEN = new BuckeyeTrafficMarker("Disabled Vehicle - Open", "images/bigDiamonds/green_diamond_v.gif", "pinVehicleGreen");
BuckeyeTrafficMarker.DISABLEDVEHICLE_CLOSED = new BuckeyeTrafficMarker("Disabled Vehicle - Closed", "images/bigDiamonds/red_diamond_v.gif", "pinVehicleRed");
BuckeyeTrafficMarker.DISABLEDVEHICLE_RESTRICTED = new BuckeyeTrafficMarker("Disabled Vehicle - Restricted", "images/bigDiamonds/yellow_diamond_v.gif", "pinVehicleYellow");

BuckeyeTrafficMarker.OTHER_OPEN = new BuckeyeTrafficMarker("Other - Open", "images/bigDiamonds/green_diamond_o.gif", "pinOtherGreen");
BuckeyeTrafficMarker.OTHER_CLOSED = new BuckeyeTrafficMarker("Other - Closed", "images/bigDiamonds/red_diamond_o.gif", "pinOtherRed");
BuckeyeTrafficMarker.OTHER_RESTRICTED = new BuckeyeTrafficMarker("Other- Restricted", "images/bigDiamonds/yellow_diamond_o.gif", "pinOtherYellow");

BuckeyeTrafficMarker.UNUSUAL_OPEN = new BuckeyeTrafficMarker("Unusual Incident - Open", "images/bigDiamonds/green_diamond_x.gif", "pinUnusualGreen");
BuckeyeTrafficMarker.UNUSUAL_CLOSED = new BuckeyeTrafficMarker("Unusual Incident - Closed", "images/bigDiamonds/red_diamond_x.gif", "pinUnusualRed");
BuckeyeTrafficMarker.UNUSUAL_RESTRICTED = new BuckeyeTrafficMarker("Unusual Incident - Restricted", "images/bigDiamonds/yellow_diamond_x.gif", "pinUnusualYellow");

BuckeyeTrafficMarker.SNOWICE_OPEN = new BuckeyeTrafficMarker("Snow/Ice - Open", "images/bigDiamonds/green_diamond_s.gif", "pinSnowGreen");
BuckeyeTrafficMarker.SNOWICE_CLOSED = new BuckeyeTrafficMarker("Snow/Ice - Closed", "images/bigDiamonds/red_diamond_s.gif", "pinSnowRed");
BuckeyeTrafficMarker.SNOWICE_RESTRICTED = new BuckeyeTrafficMarker("Snow/Ice - Restricted", "images/bigDiamonds/yellow_diamond_s.gif", "pinSnowYellow");

// represents various Winter Route Conditions on the map
BuckeyeTrafficMarker.WINTER_NO_DATA = new BuckeyeTrafficMarker("Winter Condition - No Data", "images/iconsAndPins/white_circle.gif", "pinWinterNone");
BuckeyeTrafficMarker.WINTER_DRY = new BuckeyeTrafficMarker("Winter Condition - Dry", "images/iconsAndPins/green_circle.gif", "pinWinterDry");
BuckeyeTrafficMarker.WINTER_WET = new BuckeyeTrafficMarker("Winter Condition - Wet", "images/iconsAndPins/blue_circle.gif", "pinWinterWet");
BuckeyeTrafficMarker.WINTER_MODERATE = new BuckeyeTrafficMarker("Winter Condition - Moderate", "images/iconsAndPins/yellow_circle.gif", "pinWinterSnow");
BuckeyeTrafficMarker.WINTER_SEVERE = new BuckeyeTrafficMarker("Winter Condition - Severe", "images/iconsAndPins/red_circle.gif", "pinWinterIce");

// represents a variable message sign on the map
BuckeyeTrafficMarker.VMS = new BuckeyeTrafficMarker("Message Sign", "images/fmsicons/dms_map_icon.gif");

// represents a har device on the map
BuckeyeTrafficMarker.HAR = new BuckeyeTrafficMarker("Har", "images/fmsicons/har_map_icon.gif");
//------------------------------------------------------------------------------------------------------------
function initialize()
{
    $.blockUI.defaults.pageMessage = "<h3><img src='images/wheel.gif' /> &nbsp; &nbsp; Please wait...</h3>";
    $().ajaxStart($.blockUI).ajaxStop($.unblockUI);
    doInitializeMap();
    doResizeElements();
    doBindNavigationStructure();
    doBindTravelStatusLinks();
    doBindAdminLinks();
    User.loadCurrentUser(); 

    $("a", "#content_helpFaq").click(function(){ doHelpUser(this); });
}
//------------------------------------------------------------------------------------------------------------
function doInitializeMap()
{
    if (map!=null) { map.Dispose(); }

    map = new VEMap(mapContainerId);
    var opts = new VEMapOptions();
    opts.EnableBirdseye = false;
//    map.SetClientToken(tokenJSON.tokenStr);
    map.LoadMap(new VELatLong(regionsAndCounties[5].Positioning.centerLat, regionsAndCounties[5].Positioning.centerLon), 7, 'r' , false, VEMapMode.Mode2D, true, 0, opts);

    reusableVEShapeLayer = new VEShapeLayer();
    reusableVEShapeLayer.SetTitle("Working Layer");
    map.AddShapeLayer(reusableVEShapeLayer);

    currentMapZoomLevel = map.GetZoomLevel();

    map.AttachEvent("onclick", MouseHandler);
    map.AttachEvent("onmouseover", MouseHandler);
    map.AttachEvent("onmouseout", MouseHandler);
    map.AttachEvent("onmousemove", MouseHandler);
    map.AttachEvent("onkeydown", KeyboardHandler);
    map.AttachEvent("onendzoom", ZoomHandler);
//    map.AttachEvent("ontokenerror", TokenHandler);
//    map.AttachEvent("ontokenexpire", TokenHandler);            
}
//------------------------------------------------------------------------------------------------------------
function doBindNavigationStructure()
{
    $("#content_helpFaq").css({ "display": "none" });
    $("#content_legend").css({ "display": "none" });
    $("#content_travelAdvisories").css({ "display":"none" });
    $("#content_travelStatus").css({ "display":"block" });

    $("#menuToggler").click().toggle(function(){
            $("#siteNavBar").css({"width":"0px"});
            $(".menuTogglerGraphic").attr("src", "images/button_ArrowsRight.gif");
            $(this).css("left", "0px");
            doResizeElements();
        },function(){
            $("#siteNavBar").css({"width":"250px"});
            $(".menuTogglerGraphic").attr("src", "images/button_ArrowsLeft.gif");
            $(this).css("left", "250px");
            doResizeElements();
    });

    $("#header_helpFaq").click().toggle(function(){
            $("#content_helpFaq").css({"display":"block"});
            $("#img_helpFaq").attr("src", "images/button_ArrowsUp.gif");
        },function(){
            $("#content_helpFaq").css({"display":"none"});
            $("#img_helpFaq").attr("src", "images/button_ArrowsDown.gif");
    });

    $("#header_legend").click().toggle(function() {
            $("#content_legend").css({ "display": "block" });
            $("#img_legend").attr("src", "images/button_ArrowsUp.gif");
        }, function() {
            $("#content_legend").css({ "display": "none" });
            $("#img_legend").attr("src", "images/button_ArrowsDown.gif");
    });

    $("#header_travelAdvisories").click().toggle(function(){
            $("#content_travelAdvisories").css({"display":"block"});
            $("#img_travelAdvisories").attr("src", "images/button_ArrowsUp.gif");
        },function(){
            $("#content_travelAdvisories").css({"display":"none"});
            $("#img_travelAdvisories").attr("src", "images/button_ArrowsDown.gif");
    });

    $("#header_travelStatus").click().toggle(function(){
            $("#content_travelStatus").css({"display":"none"});
            $("#img_travelStatus").attr("src", "images/button_ArrowsDown.gif");
        },function(){
            $("#content_travelStatus").css({"display":"block"});
            $("#img_travelStatus").attr("src", "images/button_ArrowsUp.gif");
    });

    $("#header_options").click().toggle(function(){
            $("#content_options").css({"display":"block"});
            $("#img_options").attr("src", "images/button_ArrowsUp.gif");
        },function(){
            $("#content_options").css({"display":"none"});
            $("#img_options").attr("src", "images/button_ArrowsDown.gif");
    });

    $("#header_adminTools").click().toggle(function(){
            $("#content_adminTools").css({"display":"block"});
            $("#img_adminTools").attr("src", "images/button_ArrowsUp.gif");
        },function(){
            $("#content_adminTools").css({"display":"none"});
            $("#img_adminTools").attr("src", "images/button_ArrowsDown.gif");
    });

    $("#imgClosuresParent").click(function(){$("#tsLink_closures").trigger("click")});
    $("#imgActivityParent").click(function(){$("#tsLink_activity").trigger("click")});
    $("#imgWinterRoadsParent").click(function(){$("#tsLink_winter").trigger("click")});
    $("#imgWindParent").click(function() { $("#tsLink_wind").trigger("click") });
    $("#imgTrafficSpeedDisplay").click(function() { $("#tsLink_speed").trigger("click") });
    $("#imgTrafficDeviceDisplay").click(function() { $("#tsLink_device").trigger("click") });        
        
}
//------------------------------------------------------------------------------------------------------------
function doBindTravelStatusLinks()
{
    //This should be called only once in a page's lifetime.
    //All bindings are initially set for the "State" region view   
    
    //---------------------------------------------------------------------
    //Bind the RWIS links   -----------------------------------------------
    //---------------------------------------------------------------------
    $("#tsLink_rwis").unbind("click");
    $("#tsLink_rwis").click().toggle(function(){
            $("#tsList_rwis").css({ "display":"block" });
            $("#imgRwisParent").attr("src", "images/treeMinus.gif")
        },function(){
            $("#tsList_rwis").css({ "display":"none" });
            $("#imgRwisParent").attr("src", "images/treePlus.gif")
    });
    
    $(".rwis", "#tsList_rwis").click(function(){ doToggleRwisSites(this); });
    $("#tsRwisChk_ALL").click(function(){ doToggleRwisSites(this); });
    
    //---------------------------------------------------------------------
    //Bind the Wind Direction links   -----------------------------------------------
    //---------------------------------------------------------------------
    $("#tsLink_wind").unbind("click");
    $("#tsLink_wind").click().toggle(function(){
            $("#tsList_wind").css({ "display":"block" });
            $("#imgWindParent").attr("src", "images/treeMinus.gif")
        },function(){
            $("#tsList_wind").css({ "display":"none" });
            $("#imgWindParent").attr("src", "images/treePlus.gif")
    });
    
    $(".wind", "#tsList_wind").click(function(){ doToggleWindDirection(this); });
    $("#tsWindChk_ALL").click(function(){ doToggleWindDirection(this); });    
    
    //---------------------------------------------------------------------
    //Bind the Closure / Restriction links   ------------------------------
    //---------------------------------------------------------------------
    $("#tsLink_closures").unbind("click");
    $("#tsLink_closures").click().toggle(function(){
            $("#tsList_closures").css({ "display":"block" });
            $("#imgClosuresParent").attr("src", "images/treeMinus.gif")
        },function(){
            $("#tsList_closures").css({ "display":"none" });
            $("#imgClosuresParent").attr("src", "images/treePlus.gif")
    });
    
    $(".closures", "#tsList_closures").click(function(){ doToggleClosuresAndRestrictions(this); });
    $("#tsClosuresChk_ALL").click(function(){ doToggleClosuresAndRestrictions(this); });
    //---------------------------------------------------------------------
    //Web Cams link never does anything, so unbind it   -------------------
    //---------------------------------------------------------------------
    $("#tsLink_webCameras").unbind("click");
    $("#tsLink_webCameras").css("cursor", "default");
    $("#tsWebCamsChk_ALL").click(function(){ doToggleWebCams(this); });
    
    //---------------------------------------------------------------------
    //Bind the Traffic Speed Display link   --------------------------------------
    //---------------------------------------------------------------------    
    $("#tsLink_speed").unbind("click");
    $("#tsLink_speed").click().toggle(function(){
            $("#tsList_speed").css({ "display":"block" });
            $("#imgTrafficSpeedDisplay").attr("src", "images/treeMinus.gif")
        },function(){
            $("#tsList_speed").css({ "display":"none" });
            $("#imgTrafficSpeedDisplay").attr("src", "images/treePlus.gif")
        });
    $(".speedDisplay").click(function() { doToggleSpeedDisplay(this); });

    //---------------------------------------------------------------------
    //Bind the Traffic Device Display link   --------------------------------------
    //---------------------------------------------------------------------
    $("#tsLink_device").unbind("click");
    $("#tsLink_device").click().toggle(function() {
    $("#tsList_device").css({ "display": "block" });
    $("#imgTrafficDeviceDisplay").attr("src", "images/treeMinus.gif")
    }, function() {
    $("#tsList_device").css({ "display": "none" });
    $("#imgTrafficDeviceDisplay").attr("src", "images/treePlus.gif")
    });
    $(".deviceDisplay").click(function() { doToggleDeviceDisplay(this); });    
    
    //---------------------------------------------------------------------
    //Bind the Road Activity links   --------------------------------------
    //---------------------------------------------------------------------
    $("#tsLink_activity").unbind("click");
    $("#tsLink_activity").click().toggle(function(){
            $("#tsList_activity").css({ "display":"block" });
            $("#imgActivityParent").attr("src", "images/treeMinus.gif")
        },function(){
            $("#tsList_activity").css({ "display":"none" });
            $("#imgActivityParent").attr("src", "images/treePlus.gif")
    });

    $("#tsActivityChk_ALL").click(function(){ doToggleRoadActivitySites(this); });
    $(".activity", "#tsList_activity").click(function(){ doToggleRoadActivitySites(this); });
    
    //---------------------------------------------------------------------
    //Bind the Winter Condition links   --------------------------------------
    //---------------------------------------------------------------------
    $("#tsLink_winter").unbind("click");
    $("#tsLink_winter").click().toggle(function(){
            $("#tsList_winter").css({ "display":"block" });
            $("#imgWinterRoadsParent").attr("src", "images/treeMinus.gif")
        },function(){
            $("#tsList_winter").css({ "display":"none" });
            $("#imgWinterRoadsParent").attr("src", "images/treePlus.gif")
    });

    $("#tsWinterChk_ALL").click(function(){ doToggleWinterRoadConditions(this); });
    $(".winter", "#tsList_winter").click(function(){ doToggleWinterRoadConditions(this); });

    //---------------------------------------------------------------------
    //Bind the Message Signs link   ---------------------------------------
    //---------------------------------------------------------------------
    $("#tsMessageSignsChk_ALL").click(function(){ doToggleDMSSigns(this); });


    //Bind the apply filters button
    $("#applyFiltersBtn").click(function(){ doApplyTravelStatusFilters(); });    
}

//------------------------------------------------------------------------------------------------------------
function doBindAdminLinks()
{
    $('.adminFunction').each(function() {
        $(this).click(function() {
            // need to figure out a way how to access 'static' methods from a JS obj
            currentBuckeyeTrafficMode = BuckeyeTrafficMode.VIEW.getModeByString($(this).attr('id'));
             $('.selected', $('#content_adminTools')).removeClass('selected').addClass('available');
            
             // highlight this guy
             $(this).addClass('selected');
             $(this).removeClass('available');
        });
    });
    $("#edit_winter_location.unavailable").unbind("click");
    $("#edit_winter_location.available").click(function (){displayWinterReportingLocationPrompt()});
    
    $("#control_camera.unavailable").unbind("click");
    $("#control_camera.available").click(function (){loadControlCameraSelector()});
    $("#camera_panel.unavailable").unbind("click");
    $("#camera_panel.available").click(function (){loadCameraPanelSelector()});
    $("#camera_bank.unavailable").unbind("click");
    $("#camera_bank.available").click(function (){loadCameraBank()});
    $("#edit_camera_tours.unavailable").unbind("click");
    $("#edit_camera_tours.available").click(function (){loadEditCameraTours()});
    
    $("#view_multiple_message_signs.unavailable").unbind("click"); 
    $("#view_multiple_message_signs.available").click(function (){viewMultipleMessageSigns()});    
    $("#manage_traffic_speed_segments.unavailable").unbind("click");
    $("#manage_traffic_speed_segments.available").click(function (){loadTrafficSegmentEditor()});    
    $("#view_multiple_har.unavailable").unbind("click"); 
    $("#view_multiple_har.available").click(function (){viewMultipleHar()});
}



//////////////////////   Region Dropdown Box code   ///////////////////////
var lastRegionSelected = 0;
var fixingRegionBlur = false;
function doRegionChange() {
    if (document.getElementById('regionSelect').selectedIndex == -1 || fixingRegionBlur) return;

    var regionName = document.getElementById('regionSelect')[document.getElementById('regionSelect').selectedIndex].value;

    var position = null;
    var zoomLevel = (regionName === "State") ? 7 : 9;

    for (var regionCount = 0; regionCount < regionsAndCounties.length; regionCount++) {
        if (regionsAndCounties[regionCount].Region === regionName) {
            position = regionsAndCounties[regionCount].Positioning;
            break;
        }
    }

    map.SetCenterAndZoom(new VELatLong(position.centerLat, position.centerLon), zoomLevel);
    lastRegionSelected = document.getElementById('regionSelect').selectedIndex;
}
function setupRegionChange() {
    document.getElementById('regionSelect').selectedIndex = -1;
    fixingRegionBlur = false;
}
function setupRegionLeave() {
    if (document.getElementById('regionSelect').selectedIndex == -1) {
        document.getElementById('regionSelect').selectedIndex = lastRegionSelected;
        fixingRegionBlur = true;
    }
}

//////////////////////   FMS Dropdown Box code   ///////////////////////
var lastFmsSelected = 0;
var fixingFmsBlur = false;
function doFmsChange() {    
    if (document.getElementById('fmsSelect').selectedIndex == -1 || fixingFmsBlur) return;

    var code = document.getElementById('fmsSelect')[document.getElementById('fmsSelect').selectedIndex].value;

    var regionName = document.getElementById('regionSelect')[document.getElementById('regionSelect').selectedIndex].value;

    for (var i = 0; i < fmsRegions.length; i++) {
        var r = fmsRegions[i];
        if (code == r.code) 
        {
            map.SetCenterAndZoom(new VELatLong(r.centerLatitude, r.centerLongitude), r.zoomLevel);
        }
    }

    lastFmsSelected = document.getElementById('fmsSelect').selectedIndex;
}
function setupFmsChange() 
{
    document.getElementById('fmsSelect').selectedIndex = -1;
    fixingFmsBlur = false;
}
function setupFmsLeave() {
    if (document.getElementById('fmsSelect').selectedIndex == -1) {
        document.getElementById('fmsSelect').selectedIndex = lastFmsSelected;
        fixingFmsBlur = true;
    }
}
           

//------------------------------------------------------------------------------------------------------------
function doResizeElements()
{
    clientH = getH();
    clientW = getW();
    clientWNavBar = $("#siteNavBar").width();
    clientWMinusNav = (clientW - clientWNavBar);
    $("#siteNavBar").css("height", clientH+"px");

    $("#siteNavBodyContainer").css("height", (clientH - 170)+"px");
    $("#BuckeyeTrafficMap").css({ "height":(clientH - 60)+"px", "width":clientWMinusNav+"px", "top":"30px", "left":clientWNavBar+"px" });
    $("#menuToggler").css({ "top":((clientH / 2) - 52)+"px", "display":"block" });
    $("#siteFooter").css({ "top":(clientH - 30)+"px" });

    if (map) { map.Resize($("#BuckeyeTrafficMap").width(), $("#BuckeyeTrafficMap").height()); }

    var centerOfMapW = (parseFloat($("#BuckeyeTrafficMap").width() / 2) + parseFloat($("#siteNavBar").width()));
    $("#divLatLongCoords").css({ "left":(centerOfMapW - 250)+"px", "width":"500px" });
}
//------------------------------------------------------------------------------------------------------------
function ZoomHandler(e)
{
    //Need to redisplay the traffic senser display if zoom level changes
    deviceLayerZoomHandler();
}
//------------------------------------------------------------------------------------------------------------
function KeyboardHandler(e)
{
    if (e.keyCode == 38)/*up arrow*/{
        map.ZoomIn();
    }
    else if (e.keyCode == 40)/*down arrow*/{
        map.ZoomOut();
    }
    else if ((e.keyCode == 37) || (e.keyCode == 39)) /*left & right arrows*/{
        return true;
    }
}
//------------------------------------------------------------------------------------------------------------
function MouseHandler(e)
{
  try{
    if (e.eventName == "onclick")
    {
        if (e.rightMouseButton)
        {                                
            var tmpMapX = e.mapX;
            var tmpMapY = e.mapY;
            reusableVEPixel = new VEPixel(e.mapX, e.mapY);
            reusableVELatLong = map.PixelToLatLong(reusableVEPixel);
            
            reusableVEShape = map.GetShapeByID(e.elementID);

            var tmpElemId = e.elementID;
//            if ((currentBuckeyeTrafficMode === BuckeyeTrafficMode.VIEW) && (e.elementID == null))
//            {
//                reusableVEShapeLayer = map.GetShapeLayerByIndex(1);
//                var shapeCount = reusableVEShapeLayer.GetShapeCount();

//                reusableVEShape = new VEShape(VEShapeType.Pushpin, reusableVELatLong);
//                reusableVEShape.SetTitle("Temporary Marker");
//                reusableVEShape.SetDescription("Temporary Marker");
//                reusableVEShape.SetCustomIcon("<div class='pinStyleTemp'></div>");
//                reusableVEShapeLayer.AddShape(reusableVEShape);
//                tmpElemId = reusableVEShape.GetID();

//                doDisplayPanelContext(tmpMapX, tmpMapY, tmpElemId);
//                reusableVEPixel = null;
//                reusableVELatLong = null;
//            }

            if (reusableVEShape != null)
            {
                // edit road activity
                if(reusableVEShape.isRoadActivity && currentBuckeyeTrafficMode === BuckeyeTrafficMode.EDIT_ROAD_ACTIVITY) {
                    editRoadActivity(reusableVEShape.RoadActivityId, reusableVEShape.Category);
                    return;
                } 

                // delete road activity
                if(reusableVEShape.isRoadActivity && currentBuckeyeTrafficMode === BuckeyeTrafficMode.DELETE_ROAD_ACTIVITY) {
                    deleteRoadActivity(reusableVEShape.RoadActivityId, reusableVEShape.Category);
                    return;
                }

                // edit camera
                if(reusableVEShape.BuckeyeTrafficMarkerType === BuckeyeTrafficMarker.CAMERA && currentBuckeyeTrafficMode === BuckeyeTrafficMode.EDIT_CAMERA) {
                    editCamera(reusableVEShape.CameraId);
                    return;
                }

                // delete camera
                if(reusableVEShape.BuckeyeTrafficMarkerType === BuckeyeTrafficMarker.CAMERA && currentBuckeyeTrafficMode === BuckeyeTrafficMode.DELETE_CAMERA) {
                    deleteCamera(reusableVEShape.CameraId);
                    return;
                }

                // edit sign
                if(reusableVEShape.isVmsSite && currentBuckeyeTrafficMode === BuckeyeTrafficMode.EDIT_MESSAGE_SIGN) {
                    editMessageSign(reusableVEShape.SignId, reusableVEShape.SignLocation);
                    return;
                }

                // delete sign
                if(reusableVEShape.isVmsSite && currentBuckeyeTrafficMode === BuckeyeTrafficMode.DELETE_MESSAGE_SIGN) {
                    deleteMessageSign(reusableVEShape.SignId, reusableVEShape.SignLocation);
                    return;
                }

                // manage sign
                if(reusableVEShape.isVmsSite && currentBuckeyeTrafficMode === BuckeyeTrafficMode.MANAGE_MESSAGE_SIGN) {
                    manageMessageSign(reusableVEShape.SignId, reusableVEShape.SignLocation);
                    return;
                }
                
                // edit har
                if(reusableVEShape.isHarSite && currentBuckeyeTrafficMode === BuckeyeTrafficMode.EDIT_HAR) {
                    editHar(reusableVEShape.RadioId, reusableVEShape.RadioLocation);
                    return;
                }

                // delete har
                if(reusableVEShape.isHarSite && currentBuckeyeTrafficMode === BuckeyeTrafficMode.DELETE_HAR) {
                    deleteHar(reusableVEShape.RadioId, reusableVEShape.RadioLocation);
                    return;
                }

                // manage har
                if(reusableVEShape.isHarSite && currentBuckeyeTrafficMode === BuckeyeTrafficMode.MANAGE_HAR) {
                    manageHar(reusableVEShape.RadioId, reusableVEShape.RadioLocation);
                    return;
                }
            }
            else
            {
                // create camera
                if(currentBuckeyeTrafficMode === BuckeyeTrafficMode.CREATE_CAMERA) {
                    createCamera(reusableVELatLong.Latitude, reusableVELatLong.Longitude);
                    return;
                }

                // create road activity
                if(currentBuckeyeTrafficMode === BuckeyeTrafficMode.CREATE_ROAD_ACTIVITY) {
                    createRoadActivityStepOne(reusableVELatLong.Latitude, reusableVELatLong.Longitude);
                    return;
                }

                // create sign
                if(currentBuckeyeTrafficMode === BuckeyeTrafficMode.ADD_MESSAGE_SIGN) {
                    createMessageSign(reusableVELatLong.Latitude, reusableVELatLong.Longitude);
                    return;
                }
                
                // create har
                if(currentBuckeyeTrafficMode === BuckeyeTrafficMode.ADD_HAR) {
                    createHar(reusableVELatLong.Latitude, reusableVELatLong.Longitude);
                    return;
                }
            }
        }
        else    //leftClick
        {
            if (e.elementID == null)
            {
                reusableVELatLong = map.GetCenter();
            }
            else
            {
                reusableVEShape = map.GetShapeByID(e.elementID);

                
                if(reusableVEShape.BuckeyeTrafficMarkerType === BuckeyeTrafficMarker.CAMERA && currentBuckeyeTrafficMode === BuckeyeTrafficMode.VIEW) {
                    displayCamera(reusableVEShape.CameraId, reusableVEShape.CameraLocation);
                    return;
                }

                if(currentBuckeyeTrafficMode === BuckeyeTrafficMode.VIEW && reusableVEShape.isRoadActivity === true) {
                    displayRoadActivity(reusableVEShape.RoadActivityId);
                }
            
                if ((currentBuckeyeTrafficMode === BuckeyeTrafficMode.VIEW) && (
                    (reusableVEShape.BuckeyeTrafficMarkerType === BuckeyeTrafficMarker.RWIS_DRY) ||
                    (reusableVEShape.BuckeyeTrafficMarkerType === BuckeyeTrafficMarker.RWIS_WET) ||
                    (reusableVEShape.BuckeyeTrafficMarkerType === BuckeyeTrafficMarker.RWIS_SNOW) ||
                    (reusableVEShape.BuckeyeTrafficMarkerType === BuckeyeTrafficMarker.RWIS_ICE) ||
                    (reusableVEShape.BuckeyeTrafficMarkerType === BuckeyeTrafficMarker.RWIS_OTHER) ||
                    (reusableVEShape.BuckeyeTrafficMarkerType === BuckeyeTrafficMarker.RWIS_ERROR) ||
                    (reusableVEShape.BuckeyeTrafficMarkerType === BuckeyeTrafficMarker.RWIS_PUBLIC) ||                                
                    (reusableVEShape.BuckeyeTrafficMarkerType === BuckeyeTrafficMarker.RWIS_OUTDATED)
                )){
                    var rwisSendParams = null;
                    switch (reusableVEShape.siteOfType){
                        case "DRY": { rwisSendParams = { "bgColor":"006600", "color":"FFFFFF", "id":reusableVEShape.SiteId, "name":reusableVEShape.Name }; break; }
                        case "WET": { rwisSendParams = { "bgColor":"0000FF", "color":"FFFFFF", "id":reusableVEShape.SiteId, "name":reusableVEShape.Name }; break; }
                        case "SNOW": { rwisSendParams = { "bgColor":"FFFF00", "color":"000000", "id":reusableVEShape.SiteId, "name":reusableVEShape.Name }; break; }
                        case "ICE": { rwisSendParams = { "bgColor":"990000", "color":"FFFFFF", "id":reusableVEShape.SiteId, "name":reusableVEShape.Name }; break; }
                        case "OTHER": { rwisSendParams = { "bgColor":"FFFFFF", "color":"000000", "id":reusableVEShape.SiteId, "name":reusableVEShape.Name }; break; }
                        case "ERROR": { rwisSendParams = { "bgColor":"996633", "color":"FFFFFF", "id":reusableVEShape.SiteId, "name":reusableVEShape.Name }; break; }
                        case "OUTDATED": { rwisSendParams = { "bgColor":"000000", "color":"FFFFFF", "id":reusableVEShape.SiteId, "name":reusableVEShape.Name }; break; }
                        case "PUBLIC": { rwisSendParams = { "bgColor":"000000", "color":"FFFFFF", "id":reusableVEShape.SiteId, "name":reusableVEShape.Name }; break; }                        
                        default: { rwisSendParams = { "bgColor":"006600", "color":"FFFFFF", "id":reusableVEShape.SiteId, "name":reusableVEShape.Name }; break; }
                    }
                    displayRwisSite(rwisSendParams);
                }
                
                //Click effect for wind direction. Essentially the same as for Rwis since the wind data is from Rwis site
                if ((currentBuckeyeTrafficMode === BuckeyeTrafficMode.VIEW) &&
                    (reusableVEShape.isWindIcon === true)){
                    var rwisSendParams = null;
                    switch (reusableVEShape.rwisSiteOfType){
                        case "DRY": { rwisSendParams = { "bgColor":"006600", "color":"FFFFFF", "id":reusableVEShape.SiteId, "name":reusableVEShape.Name }; break; }
                        case "WET": { rwisSendParams = { "bgColor":"0000FF", "color":"FFFFFF", "id":reusableVEShape.SiteId, "name":reusableVEShape.Name }; break; }
                        case "SNOW": { rwisSendParams = { "bgColor":"FFFF00", "color":"000000", "id":reusableVEShape.SiteId, "name":reusableVEShape.Name }; break; }
                        case "ICE": { rwisSendParams = { "bgColor":"990000", "color":"FFFFFF", "id":reusableVEShape.SiteId, "name":reusableVEShape.Name }; break; }
                        case "OTHER": { rwisSendParams = { "bgColor":"FFFFFF", "color":"000000", "id":reusableVEShape.SiteId, "name":reusableVEShape.Name }; break; }
                        case "ERROR": { rwisSendParams = { "bgColor":"996633", "color":"FFFFFF", "id":reusableVEShape.SiteId, "name":reusableVEShape.Name }; break; }
                        case "OUTDATED": { rwisSendParams = { "bgColor":"000000", "color":"FFFFFF", "id":reusableVEShape.SiteId, "name":reusableVEShape.Name }; break; }
                        case "PUBLIC": { rwisSendParams = { "bgColor":"000000", "color":"FFFFFF", "id":reusableVEShape.SiteId, "name":reusableVEShape.Name }; break; }                        
                        default: { rwisSendParams = { "bgColor":"006600", "color":"FFFFFF", "id":reusableVEShape.SiteId, "name":reusableVEShape.Name }; break; }
                    }
                    displayRwisSite(rwisSendParams);
                }                
                
                if(reusableVEShape.isVmsSite && currentBuckeyeTrafficMode === BuckeyeTrafficMode.VIEW) {
                    displayMessageSign(reusableVEShape.SignId, reusableVEShape.SignLocation);
                }
                

                if(reusableVEShape.isHarSite && currentBuckeyeTrafficMode === BuckeyeTrafficMode.VIEW) {
                    displayHar(reusableVEShape.RadioId, reusableVEShape.RadioLocation);
                }

                reusableVEShape = null;
            }
        }
    }
    else if (e.eventName == "onmouseover")
    {
        reusableVEShape = map.GetShapeByID(e.elementID);
        if (reusableVEShape.onMouseOver)
        {
            reusableVEShape.onMouseOver();
        }else if ((currentBuckeyeTrafficMode === BuckeyeTrafficMode.VIEW) && (
            (reusableVEShape.BuckeyeTrafficMarkerType === BuckeyeTrafficMarker.RWIS_DRY) ||
            (reusableVEShape.BuckeyeTrafficMarkerType === BuckeyeTrafficMarker.RWIS_WET) ||
            (reusableVEShape.BuckeyeTrafficMarkerType === BuckeyeTrafficMarker.RWIS_SNOW) ||
            (reusableVEShape.BuckeyeTrafficMarkerType === BuckeyeTrafficMarker.RWIS_ICE) ||
            (reusableVEShape.BuckeyeTrafficMarkerType === BuckeyeTrafficMarker.RWIS_OTHER) ||
            (reusableVEShape.BuckeyeTrafficMarkerType === BuckeyeTrafficMarker.RWIS_ERROR) ||
            (reusableVEShape.BuckeyeTrafficMarkerType === BuckeyeTrafficMarker.RWIS_PUBLIC) ||            
            (reusableVEShape.BuckeyeTrafficMarkerType === BuckeyeTrafficMarker.RWIS_OUTDATED)
            ))
        {
            reusableVEPixel = map.LatLongToPixel(reusableVEShape.GetIconAnchor());

            $("#divHoverInfo").html(reusableVEShape.GetTitle());
            $("#divHoverInfo").css("left", (reusableVEPixel.x + 175)+"px");
            $("#divHoverInfo").css("top", (reusableVEPixel.y - 62)+"px");

            switch (reusableVEShape.siteOfType){
                case "DRY": { $("#divHoverInfo").css( { "background-color":"#006600", "color":"#FFFFFF" } ); break; }
                case "WET": { $("#divHoverInfo").css( { "background-color":"#0000FF", "color":"#FFFFFF" } ); break; }
                case "SNOW": { $("#divHoverInfo").css( { "background-color":"#FFFF00", "color":"#000000" } ); break; }
                case "ICE": { $("#divHoverInfo").css( { "background-color":"#990000", "color":"#FFFFFF" } ); break; }
                case "OTHER": { $("#divHoverInfo").css( { "background-color":"#FFFFFF", "color":"#000000" } ); break; }
                case "ERROR": { $("#divHoverInfo").css( { "background-color":"#996633", "color":"#FFFFFF" } ); break; }
                case "OUTDATED": { $("#divHoverInfo").css( { "background-color":"#000000", "color":"#FFFFFF" } ); break; }
                case "PUBLIC": { $("#divHoverInfo").css( { "background-color":"#9933CC", "color":"#FFFFFF" } );   break; }                
                            
                default: { $("#divHoverInfo").css( { "background-color":"#006600", "color":"#FFFFFF" } ); break; }
            }

            $("#divHoverInfo").css("display", "block");

            reusableVEPixel = null;
        }else if ((currentBuckeyeTrafficMode === BuckeyeTrafficMode.VIEW) &&
                    (reusableVEShape.isWindIcon === true))
        {
            //wind direction hover effect
            reusableVEPixel = map.LatLongToPixel(reusableVEShape.GetIconAnchor());

            //wind hover settings. 
            //need to set the corrdinates of the popup
            //so that it displays above the current map icon. This involves adding
            //in the expected size of the popup and then adding the size of the icon
            //Note that if the popup ends up dispaying right underneath the mouse cursor then the
            //mouseoutevent will fire and your popup will disappear before it has a chance
            //to display (you will proably just see a screen flicker)
            
            $("#divHoverInfo").html(reusableVEShape.GetTitle());
            $("#divHoverInfo").css("left", (reusableVEPixel.x + 150)+"px");
            $("#divHoverInfo").css("top", (reusableVEPixel.y - 100)+"px");

            switch (reusableVEShape.rwisSiteOfType){
                case "DRY": { $("#divHoverInfo").css( { "background-color":"#006600", "color":"#FFFFFF" } ); break; }
                case "WET": { $("#divHoverInfo").css( { "background-color":"#0000FF", "color":"#FFFFFF" } ); break; }
                case "SNOW": { $("#divHoverInfo").css( { "background-color":"#FFFF00", "color":"#000000" } ); break; }
                case "ICE": { $("#divHoverInfo").css( { "background-color":"#990000", "color":"#FFFFFF" } ); break; }
                case "OTHER": { $("#divHoverInfo").css( { "background-color":"#FFFFFF", "color":"#000000" } ); break; }
                case "ERROR": { $("#divHoverInfo").css( { "background-color":"#996633", "color":"#FFFFFF" } ); break; }
                case "OUTDATED": { $("#divHoverInfo").css( { "background-color":"#000000", "color":"#FFFFFF" } ); break; }
                case "PUBLIC": { $("#divHoverInfo").css( { "background-color":"#9933CC", "color":"#FFFFFF" } );   break; }                
                            
                default: { $("#divHoverInfo").css( { "background-color":"#006600", "color":"#FFFFFF" } ); break; }
            }

            $("#divHoverInfo").css("display", "block");

            reusableVEPixel = null;
        }else if ((currentBuckeyeTrafficMode === BuckeyeTrafficMode.VIEW) && (        
            (reusableVEShape.BuckeyeTrafficMarkerType === BuckeyeTrafficMarker.ACCIDENT_OPEN) ||
            (reusableVEShape.BuckeyeTrafficMarkerType === BuckeyeTrafficMarker.ACCIDENT_RESTRICTED) ||
            (reusableVEShape.BuckeyeTrafficMarkerType === BuckeyeTrafficMarker.ACCIDENT_CLOSED) ||
            (reusableVEShape.BuckeyeTrafficMarkerType === BuckeyeTrafficMarker.ROADWORK_OPEN) ||
            (reusableVEShape.BuckeyeTrafficMarkerType === BuckeyeTrafficMarker.ROADWORK_CLOSED) ||
            (reusableVEShape.BuckeyeTrafficMarkerType === BuckeyeTrafficMarker.ROADWORK_RESTRICTED) ||
            (reusableVEShape.BuckeyeTrafficMarkerType === BuckeyeTrafficMarker.FLOODING_OPEN) ||
            (reusableVEShape.BuckeyeTrafficMarkerType === BuckeyeTrafficMarker.FLOODING_CLOSED) ||
            (reusableVEShape.BuckeyeTrafficMarkerType === BuckeyeTrafficMarker.FLOODING_RESTRICTED) ||
            (reusableVEShape.BuckeyeTrafficMarkerType === BuckeyeTrafficMarker.DEBRIS_OPEN) ||
            (reusableVEShape.BuckeyeTrafficMarkerType === BuckeyeTrafficMarker.DEBRIS_CLOSED) ||
            (reusableVEShape.BuckeyeTrafficMarkerType === BuckeyeTrafficMarker.DEBRIS_RESTRICTED) ||
            (reusableVEShape.BuckeyeTrafficMarkerType === BuckeyeTrafficMarker.DISABLEDVEHICLE_OPEN) ||
            (reusableVEShape.BuckeyeTrafficMarkerType === BuckeyeTrafficMarker.DISABLEDVEHICLE_CLOSED) ||
            (reusableVEShape.BuckeyeTrafficMarkerType === BuckeyeTrafficMarker.DISABLEDVEHICLE_RESTRICTED) ||
            (reusableVEShape.BuckeyeTrafficMarkerType === BuckeyeTrafficMarker.SNOWICE_OPEN) ||
            (reusableVEShape.BuckeyeTrafficMarkerType === BuckeyeTrafficMarker.SNOWICE_CLOSED) ||
            (reusableVEShape.BuckeyeTrafficMarkerType === BuckeyeTrafficMarker.SNOWICE_RESTRICTED) ||
            (reusableVEShape.BuckeyeTrafficMarkerType === BuckeyeTrafficMarker.UNUSUAL_OPEN) ||
            (reusableVEShape.BuckeyeTrafficMarkerType === BuckeyeTrafficMarker.UNUSUAL_CLOSED) ||
            (reusableVEShape.BuckeyeTrafficMarkerType === BuckeyeTrafficMarker.UNUSUAL_RESTRICTED) ||            
            (reusableVEShape.BuckeyeTrafficMarkerType === BuckeyeTrafficMarker.OTHER_OPEN) ||
            (reusableVEShape.BuckeyeTrafficMarkerType === BuckeyeTrafficMarker.OTHER_CLOSED) ||
            (reusableVEShape.BuckeyeTrafficMarkerType === BuckeyeTrafficMarker.OTHER_RESTRICTED)
            ))
        {
            reusableVEPixel = map.LatLongToPixel(reusableVEShape.GetIconAnchor());
            $("#divHoverInfo").html(reusableVEShape.GetTitle());
            $("#divHoverInfo").css("left", (reusableVEPixel.x + 175)+"px");
            $("#divHoverInfo").css("top", (reusableVEPixel.y - 80)+"px");

            switch (reusableVEShape.StatusText){
                case "OPEN": { $("#divHoverInfo").css( { "background-color":"#009900", "color":"#FFFFFF" } ); break; }
                case "RESTRICTED": { $("#divHoverInfo").css( { "background-color":"#FFFF00", "color":"#000000" } ); break; }
                case "CLOSED": { $("#divHoverInfo").css( { "background-color":"#990000", "color":"#FFFFFF" } ); break; }
                default: { $("#divHoverInfo").css( { "background-color":"#009900", "color":"#FFFFFF" } ); break; }
            }

            $("#divHoverInfo").css("display", "block");

            reusableVEPixel = null;
        }
        else if ((currentBuckeyeTrafficMode === BuckeyeTrafficMode.VIEW) && (reusableVEShape.BuckeyeTrafficMarkerType === BuckeyeTrafficMarker.CAMERA))
        {
        
            reusableVEPixel = map.LatLongToPixel(reusableVEShape.GetIconAnchor());
            $("#divHoverInfo").html(reusableVEShape.GetTitle());
            $("#divHoverInfo").css("left", (reusableVEPixel.x + 175)+"px");
            $("#divHoverInfo").css("top", (reusableVEPixel.y + 45)+"px");
            $("#divHoverInfo").css( { "background-color":"#9933CC", "color":"#FFFFFF" } );
            $("#divHoverInfo").css("display", "block");

            reusableVEPixel = null;
        }
        else if ((currentBuckeyeTrafficMode === BuckeyeTrafficMode.VIEW) && (reusableVEShape.isWinterPoint))
        {
            reusableVEPixel = map.LatLongToPixel(reusableVEShape.GetIconAnchor());
            $("#divHoverInfo").html(reusableVEShape.GetTitle());
            $("#divHoverInfo").css("left", (reusableVEPixel.x + 160)+"px");
            $("#divHoverInfo").css("top", (reusableVEPixel.y - 50)+"px");
	    
            switch (reusableVEShape.siteOfType){
                case "DRY": { $("#divHoverInfo").css( { "background-color":"#33FF00", "color":"#000000" } ); break; }
                case "WET": { $("#divHoverInfo").css( { "background-color":"#00CCFF", "color":"#000000" } ); break; }
                case "MODERATE": { $("#divHoverInfo").css( { "background-color":"#FFEF00", "color":"#000000" } ); break; }
                case "SEVERE": { $("#divHoverInfo").css( { "background-color":"#CC0000", "color":"#FFFFFF" } ); break; }
                default: { $("#divHoverInfo").css( { "background-color":"#FFFFFF", "color":"#000000" } ); break; }
            }

            $("#divHoverInfo").css("display", "block");

            reusableVEPixel = null;
        }
        else if ((currentBuckeyeTrafficMode === BuckeyeTrafficMode.VIEW) && (reusableVEShape.isVmsSite))
        {
        
            reusableVEPixel = map.LatLongToPixel(reusableVEShape.GetIconAnchor());
            $("#divHoverInfo").html(reusableVEShape.GetTitle());
            $("#divHoverInfo").css("left", (reusableVEPixel.x + 175)+"px");
            $("#divHoverInfo").css("top", (reusableVEPixel.y - 25)+"px");
            $("#divHoverInfo").css( { "background-color":"#000000", "color":"#FFFF00" } );
            $("#divHoverInfo").css("display", "block");

            reusableVEPixel = null;
        }
        else if ((currentBuckeyeTrafficMode === BuckeyeTrafficMode.VIEW) && (reusableVEShape.isHarSite)) {

            reusableVEPixel = map.LatLongToPixel(reusableVEShape.GetIconAnchor());
            $("#divHoverInfo").html(reusableVEShape.GetTitle());
            $("#divHoverInfo").css("left", (reusableVEPixel.x + 200) + "px");
            $("#divHoverInfo").css("top", (reusableVEPixel.y - 20) + "px");
            $("#divHoverInfo").css({ "background-color": "#3399FF", "color": "#FFFFFF" });
            $("#divHoverInfo").css("display", "block");

            reusableVEPixel = null;
        }
        reusableVEShape = null;
        return true;
    }
    else if (e.eventName == "onmouseout")
    {
        if (e.elementID != null) { $("#divHoverInfo").css("display", "none"); }
        else { return true; }
    }
    else if (e.eventName == "onmousemove")
    {
        var x = e.mapX;
        var y = e.mapY;
        reusableVEPixel = new VEPixel(x, y);
        var reusableVELatLong = map.PixelToLatLong(reusableVEPixel);
        $("#cellLatitude").text(reusableVELatLong.Latitude);
        $("#cellLongitude").text(reusableVELatLong.Longitude);
    } 
    else
    {
        return true;
    }
  }
  catch(e)
  {
  
  }
}
//------------------------------------------------------------------------------------------------------------
function getW()
{
	var w;
	if(document.innerWidth){ w=document.innerWidth; }
	else if(document.documentElement.clientWidth){ w=document.documentElement.clientWidth; }
	else if(document.body){ w=document.body.clientWidth; }
	return w;
}
//------------------------------------------------------------------------------------------------------------
function getH()
{
	var h;
	if(document.innerHeight){ h=document.innerHeight; }
	else if(document.documentElement.clientHeight){ h=document.documentElement.clientHeight; }
	else if(document.body){ h=document.body.clientHeight; }
	return h;
}
//------------------------------------------------------------------------------------------------------------
function doToggleRowHighlight(elem, strOverOut)
{
    if (strOverOut == "OVER") { elem.style.backgroundColor = "#333333"; }
    else if (strOverOut == "OUT") { elem.style.backgroundColor = "#000000"; }
}
//------------------------------------------------------------------------------------------------------------
function doHelpUser(element)
{
    var helpUrl = "";
    var helpTitle = "";

    switch (element.id.split("_")[1]){
        case "faq1": { helpUrl = "helpFaq/faq.aspx"; helpTitle = "About Buckeye Traffic"; break; }
        case "faq2": { helpUrl = "helpFaq/faq.aspx#faq"; helpTitle = "Frequently Asked Questions"; break; }
        case "howTo": { helpUrl = "helpFaq/howTo.htm"; helpTitle = "\"How To\" instructions"; break; }
        case "troubleshooting": { helpUrl = "helpFaq/troubleshooting.htm"; helpTitle = "Problems viewing the site"; break; }
        case "contactOdot": { helpUrl = "helpFaq/howTo.htm#howtocontactodot"; helpTitle = "Contact ODOT"; break; }
        case "trafficSpeedDisplay": { helpUrl = "helpFaq/faq.aspx#trafficspeedfaq"; helpTitle = "Traffic Speed Display"; break; }
        case "dynamicMessageSigns": { helpUrl = "helpFaq/faq.aspx#dmsfaq"; helpTitle = "Dynamic Message Signs"; break; }
    }

    // generate a unique ID for this dialog
    var id = Math.floor(Math.random() * 1000000);
    
    // single button, closes the dialog
    var okBtn = function() { $('#' + id).remove(); }
    
    var p = {
        "id":id,
        h: 400,
        w: 700,
        title: helpTitle,
        buttons:[{ "id":"btnOk", value: "Close", click: okBtn }],
        body:{type:"iframe", src:helpUrl }
    };
    
    var d = new DialogBox(p);
}
//------------------------------------------------------------------------------------------------------------
/*---------------------------------------------------------------------
 * Error Handling Fuctions
 *
 * These functions display errors to the user.  
 *--------------------------------------------------------------------*/
 
 function showErrorDialog(errors) {
    // generate a unique ID for this dialog
    var id = Math.floor(Math.random() * 1000000);
    
    // setup a single Ok button that "closes" this window
    var okBtn = function() { $("#" + id).remove(); }
    
    // format our errors into html
    
    var formatedErrors = "<ul>";
    for(var i = 0; i < errors.length; i++) {
        formatedErrors += "<li>" + errors[i].shortMsg + "</li>";
    }
    formatedErrors += "</ul>";
    
    var p = {
        "id": id,
        h: 300,
        w: 300,
        l: 100,
        t: 100,
        tite: "Error",
        buttons: [{"id": "btnSave", value: "Ok", "click": okBtn }],
        body: { type: "html", src: formatedErrors}
    };
    
    var errorBox = new DialogBox(p);
 }
//------------------------------------------------------------------------------------------------------------
 /*---------------------------------------------------------------------
 * Success Dialog
 *
 * These functions displays a success dialog and 'closes' the window
 * with the given dialogId.  
 *--------------------------------------------------------------------*/
 
 function showSuccessDialog(params) {
    // first remove create dialog
    $('#' + params.dialogId).remove();
 }
//------------------------------------------------------------------------------------------------------------
function resetAdminTools() {
   try{
    $('.selected', $('#content_adminTools')).addClass('available').removeClass('selected');
    $('#adminLink_default').addClass('selected').removeClass('available');
    }catch(e){}
    currentBuckeyeTrafficMode = BuckeyeTrafficMode.VIEW;
}
//------------------------------------------------------------------------------------------------------------
  function removeDialogAndRefreshFilter(params) {
    // first remove create dialog
    $('#' + params.dialogId).remove();
    $("#applyFiltersBtn").click();
 }
//------------------------------------------------------------------------------------------------------------
//------------------------------------------------------------------------------------------------------------
/*---------------------------------------------------------------------
 * Camera Dialog Functions
 *
 * These functions handle creating dialog boxes for the different camera
 * modes. 
 *--------------------------------------------------------------------*/
function createCamera(lat, lon) {
    currentBuckeyeTrafficMode = BuckeyeTrafficMode.VIEW;
    
    // generate a unique ID
    var id = Math.floor(Math.random() * 1000000);

    // generate our location with the latitude and longitude
    var location = "dialogs/cameras/CreateCamera.aspx?lat=" + lat + "&long=" + lon + "&dialogId=" + id;

    var frameName = "frame_" + id;
    var clickToSave = function() { window.frames[frameName].dispatchEvent('onSaveClicked'); resetAdminTools(); };
    var clickToAddFeed = function() { window.frames[frameName].dispatchEvent('onAddFeedClicked'); };
    var clickToCancel = function() { $("#" + id).remove(); resetAdminTools(); }
    
    //var clickToSave = function() { $.frameReady(function() { $(document).trigger('onSaveClicked') }, "frame_" + id); resetAdminTools(); }
    //var clickToAddFeed = function() { $.frameReady(function() { $(document).trigger('onAddFeedClicked') }, "frame_" + id); }

    var h = 400;
    var w = 400;
    var p = {
        "id":id,
        h: 600,
        w: 500,
        title: "Create Camera",
        buttons:[
            { "id":"btnSave", value: "Save", click: clickToSave },
            { "id":"btnCancel", value: "Cancel", click: clickToCancel },
            { "id":"btnAddFeed", value: "Add Feed", click: clickToAddFeed }
        ],
        body:{type: "iframe", src:location }
    };
    
    var d = new DialogBox(p);
}
//------------------------------------------------------------------------------------------------------------
function editCamera(id) {
    currentBuckeyeTrafficMode = BuckeyeTrafficMode.VIEW;
    
    var dialogId = Math.floor(Math.random() * 1000000);
    var url = "dialogs/cameras/EditCamera.aspx?id=" + id + "&dialogId=" + dialogId;
    
    var frameName = "frame_" + dialogId;
    var clickToSave = function() { window.frames[frameName].dispatchEvent('onSaveClicked'); resetAdminTools(); };
    var clickToAddFeed = function() { window.frames[frameName].dispatchEvent('onAddFeedClicked'); };
    var clickToCancel = function() { $("#" + dialogId).remove(); resetAdminTools(); }
    
    // var clickToSave = function() { $.frameReady(function() { $(document).trigger('onSaveClicked') }, "frame_" + dialogId); resetAdminTools(); }
    // var clickToCancel = function() { $("#" + dialogId).remove(); resetAdminTools(); }
    // var clickToAddFeed = function() { $.frameReady(function() { $(document).trigger('onAddFeedClicked') }, "frame_" + dialogId); }
    
    var p = {
        "id": dialogId,
        h: 600,
        w: 500,
        title: "Edit Camera",
        buttons:[
            { "id":"btnSave", value: "Save", click: clickToSave },
            { "id":"btnCancel", value: "Cancel", click: clickToCancel },
            { "id":"btnAddFeed", value: "Add Feed", click: clickToAddFeed }
        ],
        body: {type: "iframe", src: url}
    }
    
    var d = new DialogBox(p);
}
//------------------------------------------------------------------------------------------------------------
function displayCamera(id, title) {
       var url = "dialogs/cameras/ViewCamera.aspx?id=" + id;
    var dialogId = Math.floor(Math.random() * 1000000);
    
    var frameName = "frame_" + dialogId;
    var okBtn = function() { window.frames[frameName].dispatchEvent('onClose'); $('#' + dialogId).remove(); }


    var p = {
        "id":dialogId,
        h: 350,
        w: 760,
        title: title,
        buttons:[{ "id":"btnSave", value: "Close", click: okBtn }],
        body:{type: "iframe", src:url }
    };
    
    var d = new DialogBox(p);
}
//------------------------------------------------------------------------------------------------------------
function displayLargeCameraImage(imageOid, title) {
    var dialogId = Math.floor(Math.random() * 1000000);
    var okBtn = function() { $('#' + dialogId).remove(); }
    
    var p = {
        "id": dialogId,
        h: 530,
        w: 750,
        "title": title,
        buttons:[{"id":"btnOk", value: "Close", click: okBtn}],
        body: { type: "iframe", src: "dialogs/cameras/ViewCameraLarge.aspx?id="+imageOid } };
   
    var d = new DialogBox(p);
}
//------------------------------------------------------------------------------------------------------------
function deleteCamera(cameraId) {
    currentBuckeyeTrafficMode = BuckeyeTrafficMode.VIEW;

    var id = Math.floor(Math.random() * 1000000);
    var okBtn = function() {
        $.getJSON('ajax/cameras/DeleteCamera.aspx', {id: cameraId}, function(resp) {
            if(resp.isSuccess === "true") {
                showSuccessDialog({message: 'Camera Deleted.', dialogId: id});
            } else {
                showErrorDialog([{shortMsg: 'An error has occured.'}]);
                $('#' + id).remove();
            }
        });
        
        resetAdminTools();
    };
    var cancelBtn = function() { $('#' + id).remove(); resetAdminTools(); };
    
    var html = "<h2>Do you really want to delete this camera site?</h2>";
    var p = {
        "id": id,
        h: 200,
        w: 300,
        title: "Delete Camera",
        buttons: [{id: "OkBtn", value: "Delete", click: okBtn}, {id: "CancelBtn", value: "Cancel", click: cancelBtn}],
        body: { type: "html", src: html }};
    
    var d = new DialogBox(p);
}

/*---------------------------------------------------------------------
 * Road Activity Dialog Functions
 *
 * These functions handle creating dialog boxes for the different Road Activity
 *--------------------------------------------------------------------*/

function createRoadActivityStepOne(latitude, longitude) {
    currentBuckeyeTrafficMode = BuckeyeTrafficMode.VIEW;
    
    var dialogId = Math.floor(Math.random() * 23423);
    var dialog = '#' + dialogId;
    
    var iframeSrc = 'dialogs/road_activity/SelectRoadActivityLocation.aspx?lat=' + latitude + '&long=' + longitude + '&dialogId=' + dialogId;
    
    // once the user clicks the ok button an event on the page needs to be fired in order for the
    // next window to be created and their selected data be populated
    var frameName = "frame_" + dialogId;
    var okBtn = function() {
        window.frames[frameName].dispatchEvent('onOkClicked');
        // $.frameReady(function() { $(document).trigger('onOkClicked') }, "frame_" + dialogId);
    };
    
    var cancelBtn = function() {
        $(dialog).remove();
        resetAdminTools();
    };
    
    var params = {
        id: dialogId,
        h: 250,
        w: 350,
        title: 'Road Activity Location',
        buttons: [ {id: 'OkBtn', value: 'Ok', click: okBtn}, {id: 'CancelBtn', value: 'Cancel', click: cancelBtn} ],
        body: {type: 'iframe', src: iframeSrc}};
    
    var d = new DialogBox(params);
}

function createRoadActivityStepTwo(params) {
    // remove the location box
    $(params.dialog).remove();

    var dialogId = Math.floor(Math.random() * 23421);
    var dialog = '#' + dialogId;
    
    var iframeSrc = 'dialogs/road_activity/CreateRoadActivity.aspx?lat=' + params.latitude + '&long=' + params.longitude + '&dialogId=' + dialogId + '&btrsLinkNbr=' + params.btrsLinkNbr;
    
    // trigger the save event
    var frameName = "frame_" + dialogId;
    var saveBtn = function() {
        window.frames[frameName].dispatchEvent('onSaveClicked');
        // $.frameReady(function() { $(document).trigger('onSaveClicked'); }, "frame_" + dialogId);
    }
    
    var cancelBtn = function() {
        $(dialog).remove();
        resetAdminTools();
    }
    
    // trigger a reset event
    var resetBtn = function() {
        $.frameReady(function() { $(document).trigger('onResetClicked'); }, "frame_" + dialogId);
    }
    
    var params = {
        id: dialogId,
        h: 450,
        w: 750,
        title: 'Road Activity Details',
        buttons: [ {id: 'saveBtn', value: 'Save', click: saveBtn}, {id: 'cancelBtn', value: 'Cancel', click: cancelBtn}, 
            {id: 'resetBtn', value: 'Reset', click: resetBtn}],
        body: {type: 'iframe', src: iframeSrc}
    };
    
    var d = new DialogBox(params);
    $(window.frames[frameName]).focus();
}

function editRoadActivity(id, category) {
    if (!checkEditDeleteAccess(category)) return;
    currentBuckeyeTrafficMode = BuckeyeTrafficMode.VIEW;
    var dialogId = Math.floor(Math.random() * 23421);
    var dialog = '#' + dialogId;
    
    var iframeSrc = 'dialogs/road_activity/EditRoadActivity.aspx?id=' + id + '&dialogId=' + dialogId;
    
    // trigger the save event
    var frameName = "frame_" + dialogId;
    var saveBtn = function() {
        window.frames[frameName].dispatchEvent('onSaveClicked');
        // $.frameReady(function() { $(document).trigger('onSaveClicked'); resetAdminTools(); }, "frame_" + dialogId);
    }
    
    var cancelBtn = function() {
        $(dialog).remove();
        resetAdminTools();
    }

    var params = {
        id: dialogId,
        h: 600,
        w: 750,
        title: 'Road Activity Details',
        buttons: [ {id: 'saveBtn', value: 'Save', click: saveBtn}, {id: 'cancelBtn', value: 'Cancel', click: cancelBtn}],
        body: {type: 'iframe', src: iframeSrc}
    };
    
    var d = new DialogBox(params);
}


function deleteRoadActivity(activityId, category) {
    if (!checkEditDeleteAccess(category)) return;
    currentBuckeyeTrafficMode = BuckeyeTrafficMode.VIEW;

    var id = Math.floor(Math.random() * 1000000);
    var okBtn = function() {
        $.getJSON('ajax/road_activity/DeleteRoadActivity.aspx', {id: activityId}, function(resp) {
            if(resp.isSuccess === true) {
                showSuccessDialog({message: 'Road Activity Deleted.', dialogId: id});
            } else {
                showErrorDialog([{shortMsg: 'An error has occured.'}]);
                $('#' + id).remove();
            }
        });
        
        resetAdminTools();
    };
    var cancelBtn = function() { $('#' + id).remove(); resetAdminTools(); };
    
    var html = "<h2>Do you really want to delete this road activity?</h2>";
    var p = {
        "id": id,
        h: 200,
        w: 300,
        title: "Delete Road Activity",
        buttons: [{id: "OkBtn", value: "Delete", click: okBtn}, {id: "CancelBtn", value: "Cancel", click: cancelBtn}],
        body: { type: "html", src: html }};
    
    var d = new DialogBox(p);
}

function checkEditDeleteAccess(category)
{
    //For road activities of type "Unusual Incident" the user must
    //be an "Unusual Incident Editor" to edit or delete
    if (("Unusual Incident" == category) && (!User.isInRole("APP-BUC-Unusual Incident Editor")))
    {
        alert("You do not have permission to edit or delete \"Unusual Incident\" road activities");
        return false;
    }
    return true;
}

function displayRoadActivity(roadActivityId) {
    var id = Math.floor(Math.random() * 2341324);
    var okBtnAction = function() {$('#' + id).remove();};
    
    var url = 'dialogs/road_activity/ViewRoadActivity.aspx?id=' + roadActivityId;
    
    var params = {
        id: id,
        h: 500,
        w: 650,
        title: "View Road Activity",
        buttons: [{id: 'okBtn', value: 'Ok', click: okBtnAction}], body: {type: 'iframe', src: url}};
    
    var dialog = new DialogBox(params);
}
//------------------------------------------------------------------------------------------------------------






/*---------------------------------------------------------------------
 * Variable Message Sign Dialog Functions
 *
 * These functions handle creating dialog boxes for the different sign
 * modes. 
 *--------------------------------------------------------------------*/
function createMessageSign(lat, lon) {
    currentBuckeyeTrafficMode = BuckeyeTrafficMode.VIEW;
    
    // generate a unique ID
    var dialogId = Math.floor(Math.random() * 1000000);

    // generate our location with the latitude and longitude
    var location = "dialogs/messageSigns/CreateSign.aspx?lat=" + lat + "&long=" + lon + "&dialogId=" + dialogId;

    var frameName = "frame_" + dialogId;
    var clickToSave = function() { window.frames[frameName].dispatchEvent('onSaveClicked'); resetAdminTools(); };
    var clickToReset = function() { window.frames[frameName].dispatchEvent('onResetClicked'); resetAdminTools(); };
    var clickToCancel = function() { $("#" + dialogId).remove(); resetAdminTools(); };
    
    var p = {
        "id":dialogId,
        h: 325,
        w: 400,
        title: "Create Message Sign",
        buttons:[
            { "id":"btnSave", value: "Save", click: clickToSave },
            { "id":"btnReset", value: "Reset", click: clickToReset },
            { "id":"btnCancel", value: "Cancel", click: clickToCancel }
        ],
        body:{type: "iframe", src:location }
    };
    
    var d = new DialogBox(p);
}
//------------------------------------------------------------------------------------------------------------
function editMessageSign(id, title) {
    currentBuckeyeTrafficMode = BuckeyeTrafficMode.VIEW;
    
    var dialogId = Math.floor(Math.random() * 1000000);
    var url = EDIT_SIGN_URL + "?id=" + id + "&dialogId=" + dialogId + "&name=" + title;
    
    var frameName = "frame_" + dialogId;
    var clickToCancel = function() { $("#" + dialogId).remove(); resetAdminTools(); };
    
    var p = {
        "id": dialogId,
        h: 535,
        w: 700,
        title: title,
        buttons:[
            { "id":"btnCancel", value: "Close", click: clickToCancel }
        ],
        body: {type: "iframe", src: url}
    }
    
    var d = new DialogBox(p);
}
//------------------------------------------------------------------------------------------------------------
function displayMessageSign(id, title) {
    var dialogId = Math.floor(Math.random() * 1000000);
    var url = "dialogs/messageSigns/ViewSign.aspx?id=" + id + "&dialogId=" + dialogId;
    
    var frameName = "frame_" + dialogId;
    var okBtn = function() { $('#' + dialogId).remove(); };

    var p = {
        "id":dialogId,
        h: 350,
        w: 300,
        title: title,
        buttons:[{ "id":"btnOk", value: "Close", click: okBtn }],
        body:{type: "iframe", src:url }
    };
    
    var d = new DialogBox(p);
}
//------------------------------------------------------------------------------------------------------------
function deleteMessageSign(signId, title) {
    currentBuckeyeTrafficMode = BuckeyeTrafficMode.VIEW;

    var dialogId = Math.floor(Math.random() * 1000000);

    var clickToSave = function() {
        $.getJSON('ajax/messageSigns/RemoveSign.aspx', {id: signId}, function(resp) {
            if(resp.isSuccess === true) {  }
            else { showErrorDialog([{shortMsg: 'An error has occured.'}]); }
        });

        $('#' + dialogId).remove();
        resetAdminTools();
        $("#applyFiltersBtn").click();
    };
    var clickToCancel = function() { $("#" + dialogId).remove(); resetAdminTools(); };
    
    var html = "<p><br/><br/><br/></p><p><span style='font:700 14px verdana, tahoma, san-serif; '>Do you really want to delete this message sign?</span></p>";
    var p = {
        "id": dialogId,
        h: 200,
        w: 300,
        title: title,
        buttons: [{id: "OkBtn", value: "Delete", click: clickToSave}, {id: "CancelBtn", value: "Cancel", click: clickToCancel}],
        body: { type: "html", src: html }};
    
    var d = new DialogBox(p);
}
//------------------------------------------------------------------------------------------------------------
function manageMessageSign(id, title) {
    var dialogId = Math.floor(Math.random() * 1000000);
    var url = MANAGE_SIGN_URL + "?id=" + id + "&dialogId=" + dialogId;
    
    var frameName = "frame_" + dialogId;
    var clickToCancel = function() { $("#" + dialogId).remove(); resetAdminTools(); };

    var p = {
        "id": dialogId,
        h: 565,
        w: 700,
        title: title,
        buttons:[
            { "id":"btnCancel", value: "Close", click: clickToCancel }
        ],
        body: {type: "iframe", src: url}
    }
    
    var d = new DialogBox(p);
}
//------------------------------------------------------------------------------------------------------------
function viewMultipleMessageSigns() 
{
    openwindows[openwindows.length] = window.open("dialogs/messageSigns/ViewMultipleSigns.aspx", "", "width=900, height=600,resizable=1,scrollbars=1,left=50,top=50");  
    resetAdminTools();
}




/*---------------------------------------------------------------------
 * Highway Advisory Radio Dialog Functions
 *
 * These functions handle creating dialog boxes for the different radio
 * modes. 
 *--------------------------------------------------------------------*/
function createHar(lat, lon) {
    currentBuckeyeTrafficMode = BuckeyeTrafficMode.VIEW;
    
    // generate a unique ID
    var dialogId = Math.floor(Math.random() * 1000000);

    // generate our location with the latitude an                                                                                       d longitude
    var location = "dialogs/har/CreateHar.aspx?lat=" + lat + "&long=" + lon + "&dialogId=" + dialogId;

    var frameName = "frame_" + dialogId;
    var clickToSave = function() { window.frames[frameName].dispatchEvent('onSaveClicked'); resetAdminTools(); };
    var clickToReset = function() { window.frames[frameName].dispatchEvent('onResetClicked'); resetAdminTools(); };
    var clickToCancel = function() { $("#" + dialogId).remove(); resetAdminTools(); };
    
    var p = {
        "id":dialogId,
        h: 325,
        w: 400,
        title: "Create HAR",
        buttons:[
            { "id":"btnSave", value: "Save", click: clickToSave },
            { "id":"btnReset", value: "Reset", click: clickToReset },
            { "id":"btnCancel", value: "Cancel", click: clickToCancel }
        ],
        body:{type: "iframe", src:location }
    };
    
    var d = new DialogBox(p);
}
//------------------------------------------------------------------------------------------------------------
function editHar(id, title) {
    currentBuckeyeTrafficMode = BuckeyeTrafficMode.VIEW;
    var dialogId = Math.floor(Math.random() * 1000000);
    var url = EDIT_HAR_URL + "?id=" + id + "&dialogId=" + dialogId + "&name=" + title;
    
    var frameName = "frame_" + dialogId;
    var clickToCancel = function() { $("#" + dialogId).remove(); resetAdminTools(); };
    
    var p = {
        "id": dialogId,
        h: 590,
        w: 700,
        title: title,
        buttons:[
            { "id":"btnCancel", value: "Close", click: clickToCancel }
        ],
        body: {type: "iframe", src: url}
    }
    
    var d = new DialogBox(p);
}
//------------------------------------------------------------------------------------------------------------
function displayHar(id, title) {
    var dialogId = Math.floor(Math.random() * 1000000);
    var url = "dialogs/har/ViewHar.aspx?id=" + id + "&dialogId=" + dialogId;
    
    var frameName = "frame_" + dialogId;
    var okBtn = function() { $('#' + dialogId).remove(); };

    var p = {
        "id":dialogId,
        h: 500,
        w: 550,
        title: title,
        buttons:[{ "id":"btnOk", value: "Close", click: okBtn }],
        body:{type: "iframe", src:url }
    };
    
    var d = new DialogBox(p);
}
//------------------------------------------------------------------------------------------------------------
function deleteHar(radioId, title) {
    currentBuckeyeTrafficMode = BuckeyeTrafficMode.VIEW;

    var dialogId = Math.floor(Math.random() * 1000000);

    var clickToSave = function() {
        $.getJSON('ajax/har/RemoveRadio.aspx', {id: radioId}, function(resp) {
            if(resp.isSuccess === true) {  }
            else { showErrorDialog([{shortMsg: 'An error has occured.'}]); }
        });

        $('#' + dialogId).remove();
        resetAdminTools();
        $("#applyFiltersBtn").click();
    };
    var clickToCancel = function() { $("#" + dialogId).remove(); resetAdminTools(); };
    
    var html = "<p><br/><br/><br/></p><p><span style='font:700 14px verdana, tahoma, san-serif; '>Do you really want to delete this HAR?</span></p>";
    var p = {
        "id": dialogId,
        h: 200,
        w: 300,
        title: title,
        buttons: [{id: "OkBtn", value: "Delete", click: clickToSave}, {id: "CancelBtn", value: "Cancel", click: clickToCancel}],
        body: { type: "html", src: html }};
    
    var d = new DialogBox(p);
}
//------------------------------------------------------------------------------------------------------------
function manageHar(id, title) {
    var dialogId = Math.floor(Math.random() * 1000000);
    var url = MANAGE_HAR_URL + "?id=" + id + "&dialogId=" + dialogId;
    
    var frameName = "frame_" + dialogId;
    var clickToCancel = function() { $("#" + dialogId).remove(); resetAdminTools(); };

    var p = {
        "id": dialogId,
        h: 565,
        w: 700,
        title: title,
        buttons:[
            { "id":"btnCancel", value: "Close", click: clickToCancel }
        ],
        body: {type: "iframe", src: url}
    }
    
    var d = new DialogBox(p);
}

//------------------------------------------------------------------------------------------------------------
function viewMultipleHar() 
{
    openwindows[openwindows.length] = window.open("dialogs/har/ViewMultipleHar.aspx", "", "width=900, height=600,resizable=1,scrollbars=1,left=50,top=50");      
    resetAdminTools();
}


//------------------------------------------------------------------------------------------------------------
function doToggleRwisSites(elem)
{
    var elemName = elem.id.split("_")[0];
    var sitesOfType = elem.id.split("_")[1];
    var chkElemChecked = $("#tsRwisChk_"+sitesOfType).attr("checked");

    //If by link, toggle to opposite of current display (based on checked
    //attribute of the corresponding checkbox).  Otherwise, base display
    //on checked attribute of the selected checkbox.
    if (chkElemChecked === undefined) { chkElemChecked = false; }
    if (elemName === "tsRwisLink") { chkElemChecked = !chkElemChecked; }

    if ((sitesOfType === "ALL") && (chkElemChecked)) { doShowAllRwisSitesSummaryList(); }
    else if ((sitesOfType === "ALL") && (!chkElemChecked)) { doHideAllRwisSitesSummaryList(); }
    else if ((sitesOfType != "ALL") && (chkElemChecked)) { doShowRwisSitesSummaryList(sitesOfType, false); }
    else if ((sitesOfType != "ALL") && (!chkElemChecked)) { doHideRwisSites(sitesOfType); }
}
//------------------------------------------------------------------------------------------------------------
function doShowRwisSitesSummaryList(sitesOfType, allChecked)
{
	var thisShapeLayerTitle = "RWIS - " + sitesOfType;
	
	var layer = getOrCreateNamedLayer(thisShapeLayerTitle);
	layer.Show();	
	
	var checkElem = $("#tsRwisChk_"+sitesOfType);
	$(checkElem).attr("checked", "checked");
	
	if (allChecked)
	{
		$("#tsRwisChk_ALL").attr("checked", "checked");
	}
}
//------------------------------------------------------------------------------------------------------------
function doHideRwisSites(sitesOfType)
{
    var thisShapeLayerTitle = "RWIS - " + sitesOfType;

	var layer = getOrCreateNamedLayer(thisShapeLayerTitle);
	layer.Hide();

    $("#tsRwisChk_"+sitesOfType).removeAttr("checked");
    $("#tsRwisChk_ALL").removeAttr("checked");
}
//------------------------------------------------------------------------------------------------------------
function doShowAllRwisSitesSummaryList(){
    doShowRwisSitesSummaryList("DRY", true);
    doShowRwisSitesSummaryList("WET", true);
    doShowRwisSitesSummaryList("SNOW", true);
    doShowRwisSitesSummaryList("ICE", true);
    doShowRwisSitesSummaryList("ERROR", true);
    doShowRwisSitesSummaryList("OTHER", true);
    doShowRwisSitesSummaryList("OUTDATED", true);
    
    //Include public view layer in show all if it exists
    doShowRwisSitesSummaryList("PUBLIC", true);    
    

    $("#tsRwisChk_ALL").attr("checked", "checked");
}
//------------------------------------------------------------------------------------------------------------
function doHideAllRwisSitesSummaryList(){
    doHideRwisSites("DRY");
    doHideRwisSites("WET");
    doHideRwisSites("SNOW");
    doHideRwisSites("ICE");
    doHideRwisSites("ERROR");
    doHideRwisSites("OTHER");
    doHideRwisSites("OUTDATED");
    
    //Include public view layer in hide all if it exists
    doHideRwisSites("PUBLIC", true);        
}


//------------------------------------------------------------------------------------------------------------
function doToggleWindDirection(elem)
{
    var elemName = elem.id.split("_")[0];
    var sitesOfType = elem.id.split("_")[1];
    var chkElemChecked = $("#tsWindChk_"+sitesOfType).attr("checked");

    //If by link, toggle to opposite of current display (based on checked
    //attribute of the corresponding checkbox).  Otherwise, base display
    //on checked attribute of the selected checkbox.
    if (chkElemChecked === undefined) { chkElemChecked = false; }
    if (elemName === "tsWindLink") { chkElemChecked = !chkElemChecked; }

    if ((sitesOfType === "ALL") && (chkElemChecked)) { doShowAllWindDirectionSummaryList(); }
    else if ((sitesOfType === "ALL") && (!chkElemChecked)) { doHideAllWindDirectionSummaryList(); }
    else if ((sitesOfType != "ALL") && (chkElemChecked)) { doShowWindDirectionSummaryList(sitesOfType, false); }
    else if ((sitesOfType != "ALL") && (!chkElemChecked)) { doHideWindDirection(sitesOfType); }
}
//------------------------------------------------------------------------------------------------------------
function doShowWindDirectionSummaryList(sitesOfType, allChecked)
{    
	var thisShapeLayerTitle = "WIND - " + sitesOfType;	
	var layer = getOrCreateNamedLayer(thisShapeLayerTitle);
	layer.Show();	
	
	var checkElem = $("#tsWindChk_"+sitesOfType);
	$(checkElem).attr("checked", "checked");
	
	if (allChecked)
	{
		$("#tsWindChk_ALL").attr("checked", "checked");
	}
}
//------------------------------------------------------------------------------------------------------------
function doHideWindDirection(sitesOfType)
{
    var thisShapeLayerTitle = "WIND - " + sitesOfType;
	var layer = getOrCreateNamedLayer(thisShapeLayerTitle);
	layer.Hide();

    $("#tsWindChk_"+sitesOfType).removeAttr("checked");
    $("#tsWindChk_ALL").removeAttr("checked");
}
//------------------------------------------------------------------------------------------------------------
function doShowAllWindDirectionSummaryList(){
    doShowWindDirectionSummaryList("FUNCTIONING", true);
    doShowWindDirectionSummaryList("NONFUNCTIONING", true);

    $("#tsWindChk_ALL").attr("checked", "checked");
}
//------------------------------------------------------------------------------------------------------------
function doHideAllWindDirectionSummaryList(){
    doHideWindDirection("FUNCTIONING");
    doHideWindDirection("NONFUNCTIONING");
}

//------------------------------------------------------------------------------------------------------------
//function displayRwisSite(nbr, name){
function displayRwisSite(paramsList){
    var bgColor = paramsList.bgColor;
    var txtColor = paramsList.color;
    var name = paramsList.name;
    var nbr = paramsList.id;
//    var url = "dialogs/rwis/ViewSite.aspx?id=" + nbr;
    var url = "dialogs/rwis/ViewSite.aspx?id=" + nbr + "&bg=" + bgColor + "&c=" + txtColor;
    var dialogId = Math.floor(Math.random() * 1000000);
    var okBtn = function() { $('#' + dialogId).remove(); }

    var p = {
        "id":dialogId,
        h: 400,
        w: 415,
        title: name,
        buttons:[{ "id":"btnOk", value: "Close", click: okBtn }],
        body:{type: "iframe", src:url }
    };
    
    var d = new DialogBox(p);
}
//------------------------------------------------------------------------------------------------------------
function doStoreMapPrefs(){
    alert("in doStoreMapPrefs()...");
}
//------------------------------------------------------------------------------------------------------------
function doToggleClosuresAndRestrictions(elem)
{
    var elemName = elem.id.split("_")[0];
    var sitesOfType = elem.id.split("_")[1];
    var chkElemChecked = $("#tsClosuresChk_"+sitesOfType).attr("checked");

    //If by link, toggle to opposite of current display (based on checked
    //attribute of the corresponding checkbox).  Otherwise, base display
    //on checked attribute of the selected checkbox.
    if (chkElemChecked === undefined) { chkElemChecked = false; }
    if (elemName === "tsClosuresLink") { chkElemChecked = !chkElemChecked; }

    if ((sitesOfType === "ALL") && (chkElemChecked)) { doShowAllClosuresAndRestrictionsSummaryList(sitesOfType); }
    else if ((sitesOfType === "ALL") && (!chkElemChecked)) { doHideAllClosuresAndRestrictionsSummaryList(sitesOfType); }
    else if ((sitesOfType != "ALL") && (chkElemChecked)) { doShowClosuresAndRestrictionsSummaryList(sitesOfType, false); }
    else if ((sitesOfType != "ALL") && (!chkElemChecked)) { doHideClosuresAndRestrictions(sitesOfType); }
}
//------------------------------------------------------------------------------------------------------------
function doShowClosuresAndRestrictionsSummaryList(sitesOfType, allChecked)
{
	var thisShapeLayerTitle = "CLOSURES AND RESTRICTIONS - " + sitesOfType;
	var layer = getOrCreateNamedLayer(thisShapeLayerTitle);
	layer.Show();    
	
	var checkElem = $("#tsClosuresChk_"+sitesOfType);
	$(checkElem).attr("checked", "checked");
	
	if (allChecked)
	{
	    $("#tsClosuresChk_ALL").attr("checked", "checked");
	}
}
//------------------------------------------------------------------------------------------------------------
function doHideClosuresAndRestrictions(sitesOfType)
{
	var thisShapeLayerTitle = "CLOSURES AND RESTRICTIONS - " + sitesOfType;
	
	var layer = getOrCreateNamedLayer(thisShapeLayerTitle);
	layer.Hide();
	
	$("#tsClosuresChk_"+sitesOfType).removeAttr("checked");
	$("#tsClosuresChk_ALL").removeAttr("checked");
}
//------------------------------------------------------------------------------------------------------------
function doShowAllClosuresAndRestrictionsSummaryList(sitesOfType)
{
    doShowClosuresAndRestrictionsSummaryList("CLOSURES",true);

    doShowClosuresAndRestrictionsSummaryList("RESTRICTIONS", true);

    $("#tsClosuresChk_ALL").attr("checked", "checked");
}
//------------------------------------------------------------------------------------------------------------
function doHideAllClosuresAndRestrictionsSummaryList(sitesOfType)
{
    doHideClosuresAndRestrictions("CLOSURES");
    doHideClosuresAndRestrictions("RESTRICTIONS");
}
//------------------------------------------------------------------------------------------------------------
function doToggleWebCams(elem)
{
    var chkElemChecked = $("#"+elem.id).attr("checked");

    if (chkElemChecked) { doShowWebCameras(); }
    else { doHideWebCams(); }
}
//------------------------------------------------------------------------------------------------------------
function doShowWebCameras(){
	var thisShapeLayerTitle = "WEB CAMERAS";
	var layer = getOrCreateNamedLayer(thisShapeLayerTitle);
	layer.Show();
	$("#tsWebCamsChk_ALL").attr("checked", "checked");
}
//------------------------------------------------------------------------------------------------------------
function doHideWebCams(sitesOfType)
{
	var thisShapeLayerTitle = "WEB CAMERAS";
	var layer = getOrCreateNamedLayer(thisShapeLayerTitle);
	layer.Hide();
	$("#tsWebCamsChk_ALL").removeAttr("checked");
}
//------------------------------------------------------------------------------------------------------------
function doShowMessageSigns(){
	var thisShapeLayerTitle = "MESSAGE SIGNS";
	var layer = getOrCreateNamedLayer(thisShapeLayerTitle);
	layer.Show();
	$("#tsMessageSignsChk_ALL").attr("checked", "checked");
}
//------------------------------------------------------------------------------------------------------------
function doHideMessageSigns()
{
	var thisShapeLayerTitle = "MESSAGE SIGNS";
	var layer = getOrCreateNamedLayer(thisShapeLayerTitle);
	layer.Hide();
	$("#tsMessageSignsChk_ALL").removeAttr("checked");
}
//------------------------------------------------------------------------------------------------------------
function doToggleRoadActivitySites(elem)
{
    var elemName = elem.id.split("_")[0];
    var sitesOfType = elem.id.split("_")[1];
    var elem = $("#tsActivityChk_"+sitesOfType);
    var chkElemChecked = $("#tsActivityChk_"+sitesOfType).attr("checked");

    //If by link, toggle to opposite of current display (based on checked
    //attribute of the corresponding checkbox).  Otherwise, base display
    //on checked attribute of the selected checkbox.
    if (chkElemChecked === undefined) { chkElemChecked = false; }
    if (elemName === "tsActivityLink") { chkElemChecked = !chkElemChecked; }

    if ((sitesOfType === "ALL") && (chkElemChecked)) { doShowAllRoadActivitySitesSummaryList(); }
    else if ((sitesOfType === "ALL") && (!chkElemChecked)) { doHideAllRoadActivitySitesSummaryList(); }
    else if ((sitesOfType != "ALL") && (chkElemChecked)) { doShowRoadActivitySitesSummaryList(sitesOfType, false); }
    else if ((sitesOfType != "ALL") && (!chkElemChecked)) { doHideRoadActivitySites(sitesOfType); }
}
//------------------------------------------------------------------------------------------------------------
function doShowRoadActivitySitesSummaryList(sitesOfType, allChecked)
{
	var thisShapeLayerTitle = "ROAD ACTIVITY - " + sitesOfType;   
	var layer = getOrCreateNamedLayer(thisShapeLayerTitle);
	layer.Show();

        var checkElem = $("#tsActivityChk_"+sitesOfType);
        $(checkElem).attr("checked", "checked");

        if (allChecked)
        {
            $("#tsActivityChk_ALL").attr("checked", "checked");
        }           
}
//------------------------------------------------------------------------------------------------------------
function doHideRoadActivitySites(sitesOfType)
{
	var thisShapeLayerTitle = "ROAD ACTIVITY - " + sitesOfType;
	var layer = getOrCreateNamedLayer(thisShapeLayerTitle);
	layer.Hide();
	
	$("#tsActivityChk_"+sitesOfType).removeAttr("checked");
	$("#tsActivityChk_ALL").removeAttr("checked");
}
//------------------------------------------------------------------------------------------------------------
function doShowAllRoadActivitySitesSummaryList(){
    doShowRoadActivitySitesSummaryList("ACCIDENT", true);
    doShowRoadActivitySitesSummaryList("DEBRIS", true);
    doShowRoadActivitySitesSummaryList("DISABLEDVEHICLE", true);
    doShowRoadActivitySitesSummaryList("FLOODING", true);
    doShowRoadActivitySitesSummaryList("ROADWORK", true);
    doShowRoadActivitySitesSummaryList("SNOWICE", true);
    doShowRoadActivitySitesSummaryList("UNUSUAL", true);    
    doShowRoadActivitySitesSummaryList("OTHER", true);

    $("#tsActivityChk_ALL").attr("checked", "checked");
}
//------------------------------------------------------------------------------------------------------------
function doHideAllRoadActivitySitesSummaryList(){
    doHideRoadActivitySites("ACCIDENT");
    doHideRoadActivitySites("DEBRIS");
    doHideRoadActivitySites("DISABLEDVEHICLE");
    doHideRoadActivitySites("FLOODING");
    doHideRoadActivitySites("ROADWORK");
    doHideRoadActivitySites("SNOWICE");
    doHideRoadActivitySites("UNUSUAL");    
    doHideRoadActivitySites("OTHER");
}
//------------------------------------------------------------------------------------------------------------
function doToggleWinterRoadConditions(elem)
{
    var s = elem.id.split("_");
    var elemName = s[0];
    var sitesOfType = s[1];
    if (s.length > 2)
    {
      sitesOfType += "_" + s[2];
    }
    var elem = $("#tsWinterChk_"+sitesOfType);
    var chkElemChecked = $("#tsWinterChk_"+sitesOfType).attr("checked");

    //If by link, toggle to opposite of current display (based on checked
    //attribute of the corresponding checkbox).  Otherwise, base display
    //on checked attribute of the selected checkbox.
    if (chkElemChecked === undefined) { chkElemChecked = false; }
    if (elemName === "tsWinterLink") { chkElemChecked = !chkElemChecked; }

    if ((sitesOfType === "ALL") && (chkElemChecked)) { doShowAllWinterRoadConditions(); }
    else if ((sitesOfType === "ALL") && (!chkElemChecked)) { doHideAllWinterRoadConditions(); }
    else if ((sitesOfType != "ALL") && (chkElemChecked)) { doShowWinterRoadConditions(sitesOfType, false); }
    else if ((sitesOfType != "ALL") && (!chkElemChecked)) { doHideWinterRoadConditions(sitesOfType); }
}
//------------------------------------------------------------------------------------------------------------
function doShowWinterRoadConditions(sitesOfType, allChecked)
{
	sitesOfType = sitesOfType.toUpperCase();
	var thisShapeLayerTitle = "WINTER CONDITIONS - " + sitesOfType;
	var layer = getOrCreateNamedLayer(thisShapeLayerTitle);
	layer.Show();

        var checkElem = $("#tsWinterChk_"+sitesOfType);
        $(checkElem).attr("checked", "checked");

        if (allChecked)
        {
            $("#tsWinterChk_ALL").attr("checked", "checked");
        }           
}
//------------------------------------------------------------------------------------------------------------
function doHideWinterRoadConditions(sitesOfType)
{	
	sitesOfType = sitesOfType.toUpperCase();
	var thisShapeLayerTitle = "WINTER CONDITIONS - " + sitesOfType;	
	var layer = getOrCreateNamedLayer(thisShapeLayerTitle);
	layer.Hide();
	
	$("#tsWinterChk_"+sitesOfType).removeAttr("checked");
	$("#tsWinterChk_ALL").removeAttr("checked");
}

//------------------------------------------------------------------------------------------------------------
function doShowAllWinterRoadConditions() {
    doShowWinterRoadConditions("DRY", true);
    doShowWinterRoadConditions("WET", true);
    doShowWinterRoadConditions("MODERATE", true);
    doShowWinterRoadConditions("SEVERE", true);
    doShowWinterRoadConditions("NO_DATA", true);    
    $("#tsWinterChk_ALL").attr("checked", "checked");
}

//------------------------------------------------------------------------------------------------------------
function doHideAllWinterRoadConditions() {
    doHideWinterRoadConditions("DRY");
    doHideWinterRoadConditions("WET");
    doHideWinterRoadConditions("MODERATE");
    doHideWinterRoadConditions("SEVERE");
    doHideWinterRoadConditions("NO_DATA");    
}

//------------------------------------------------------------------------------------------------------------
function displayWinterReportingLocationPrompt() {
    currentBuckeyeTrafficMode = BuckeyeTrafficMode.VIEW;

    var dialogId = Math.floor(Math.random() * 1000000);
    var dialog = '#' + dialogId;
    var name = "Select Reporting Location"
    var url = "dialogs/winter/SelectReportLocation.aspx?dialogId="+dialogId;

    var cancelBtn = function() {
        $(dialog).remove();
        resetAdminTools();
    }

    // once the user clicks the ok button an event on the page needs to be fired in order for the
    // next window to be created and their selected data be populated
    var frameName = "frame_" + dialogId;
    var okBtn = function() {
        window.frames[frameName].dispatchEvent('onOkClicked');
        // $.frameReady(function() { $(document).trigger('onOkClicked') }, "frame_" + dialogId);
    };

    var p = {
        "id":dialogId,
        h: 100,
        w: 325,
        title: name,
        buttons:[{ "id":"btnOk", "value":"OK", "click":okBtn }, { "id":"btnCancel", "value":"Cancel", "click":cancelBtn }],
        body:{type: "iframe", src:url }
    };
    
    var d = new DialogBox(p);
}
//------------------------------------------------------------------------------------------------------------
function doEditWinterCondition(params) {
    // remove the location box
    $(params.dialog).remove();

    var locArr = params.location.split("~");
    var locOid = locArr[0];
    var locDesc = locArr[1];
    var dialogId = Math.floor(Math.random() * 1000000);
    var dialog = '#' + dialogId;
    var name = "Current Conditions - " + locDesc;
    var url = "dialogs/winter/ReportingLocationConditions.aspx?dialogId="+dialogId+"&locOid="+locOid;

    // once the user clicks a button an event on the page
    // needs to be fired to perform the desired function.
    var frameName = "frame_" + dialogId;
    var saveBtn = function() {
        window.frames[frameName].dispatchEvent('onSaveClicked');
        // $.frameReady(function() { $(document).trigger('onSaveClicked') }, "frame_" + dialogId);
	    resetAdminTools();
    };

    var cancelBtn = function() {
        $(dialog).remove();
        resetAdminTools();
    };

    var resetBtn = function() {
        window.frames[frameName].dispatchEvent('onResetClicked');
        // $.frameReady(function() { $(document).trigger('onResetClicked') }, "frame_" + dialogId);
    };

    var p = {
        "id":dialogId,
        h: 350,
        w: 700,
        title: name,
        buttons:[{ "id":"btnSave", "value":"Save", "click":saveBtn }, { "id":"btnCancel", "value":"Cancel", "click":cancelBtn }, { "id":"btnReset", "value":"Reset", "click":resetBtn }],
        body:{type: "iframe", src:url }
    };
    
    var d = new DialogBox(p);
}
//------------------------------------------------------------------------------------------------------------
/*
When called this function calculates the current maps bounding box lat/long values and 
locates all the currently selected travel status filters and builds an xml
structure that it send this data to the server via a post request. The JSON objects
that return are then plotted on the VEMap.
*/
function doApplyTravelStatusFilters() {

   //Get ve bounding box uses global variables map and mapContainerId
   var bb = getMapBounds(map,mapContainerId);
   //Create the filter xml
   var xml = '<travel_status_filters>';   
   //Add the bounding box
   xml += bb.getXml();
   //For each checked input box add the correct filter tag. The filter
   //is created from the input id. The input id format is 
   // ts<filter category tag name>Chk_<filter type>
   // Ex: tsActivityChk_ACCIDENT results in 
   //a category of 'Activity' and type = 'ACCIDENT'
   //Note that the xml will force both of these values to be all lowercase to
   //make parsing of the xml file consistent on the server
   $("input:checked").each(function() {
      var filterRegEx = RegExp(/ts(.*)?Chk_(.*)?/); 
      var m = filterRegEx.exec(this.id);
      if ((m != null) && (m.length == 3)) {
	      var category = m[1].toLowerCase();
	      var filterType = m[2].toLowerCase();
	      xml += '<' + category +  '  type=\"' + filterType + '\" />';
      }
   } );
   xml += '</travel_status_filters>';   
   
   //Delete all existing layer shapes
   map.DeleteAllShapes();
   
   
   //Do JSON post to server and process response
	$.post('ajax/filter/LoadPointsOfInterest.aspx', {filterXml: xml}, function(resp) {
       if (resp.poi.errorMessage && resp.poi.errorMessage.length >0) {
	     alert(resp.poi.errorMessage);
	   }
	   else
	   {
		   populateCameraLayers(resp);
		   populateRwisLayers(resp);
           populateWindDirectionLayers(resp);
		   populateWinterLayers(resp);
		   populateRoadActivityLayers(resp);
		   populateClosureRestrictionLayers(resp);		   
		   populateMessageSignLayers(resp);
		   populateHarLayers(resp);
	   }
	    //Update traffic speed display if necessary
	    displaySpeedInfoForUser();	   	    
    }, "json");		
}


function populateCameraLayers(resp)
{
	try {
	var thisShapeLayerTitle = "WEB CAMERAS";
	var layer = getOrCreateNamedLayer(thisShapeLayerTitle);	

        for(var i=0; i < resp.poi.cameras.length; i++) {
            var camera = resp.poi.cameras[i];
          
            var latLong = new VELatLong(parseFloat(camera.Latitude), parseFloat(camera.Longitude));
            var shape = new VEShape(VEShapeType.Pushpin, latLong);
            var title = "<center><b>WEB CAMERA - "+camera.Location+"</b></center>";

            if ((camera.Feeds != "undefined") && (camera.Feeds != null))
            {
                for (var j = 0; j < camera.Feeds.length; j++)
                {
                    title += "<br/ >&nbsp;&nbsp;&#149;&nbsp;" + camera.Feeds[j];
                }
            }

            shape.SetTitle(title);
            shape.SetCustomIcon(BuckeyeTrafficMarker.CAMERA.icon());
            shape.BuckeyeTrafficMarkerType = BuckeyeTrafficMarker.CAMERA;
            shape.isWebCameraSite = true;
            shape.CameraId = camera.Id;
            shape.CameraLocation = camera.Location;

            layer.AddShape(shape);
            shape = null;
        }
	}catch(e) {
	   var msg = "Unknown";
	   if (e instanceof String) {
	   }else if (e.message) {
              msg = e.message;
	   }
	   throw "Unable to populateCameraLayers. Reason - > \n" + msg
	}	
}

function populateRwisLayers(resp)
{	
	try {
	  if (resp.poi.rwis) {
		for(var i=0; i < resp.poi.rwis.length; i++) {
		    var site = resp.poi.rwis[i];		    
		    var sitesOfType = site.filterCode.toUpperCase();
		    //If there is no valid logged in user then the 
		    //site type is always public
		    if (!User.valid()){
		      sitesOfType = "PUBLIC";
		    }
		    var btMarkerType = "BuckeyeTrafficMarker.RWIS_"+sitesOfType;		    
		    var thisShapeLayerTitle =  "RWIS - " + sitesOfType;
		    var layer = getOrCreateNamedLayer(thisShapeLayerTitle);	
		    var latLong = new VELatLong(parseFloat(site.latitude), parseFloat(site.longitude));
		    var title = "";
		    title += "<center><b>Road / Weather Sensor</b></center><br/>";
		    title += "<b>Site:</b> "+site.name+"<br/>";
		    title += "<b>Status:</b> "+site.worstCondition+"<br/>";
		    title += "<b>Temperature:</b> "+site.airTemp+"<br/>";
		    title += "<b>Updated:</b> "+site.lastUpdatedDateTime;
	
		    reusableVEShape = new VEShape(VEShapeType.Pushpin, latLong);
		    reusableVEShape.SetTitle(title);
		    reusableVEShape.SetCustomIcon("<div class=\""+eval(btMarkerType+".divClass()")+"\"></div>");
		    reusableVEShape.siteOfType = sitesOfType.toUpperCase();
		    reusableVEShape.BuckeyeTrafficMarkerType = eval(btMarkerType);
		    reusableVEShape.isRwisSite = true;
		    reusableVEShape.SiteId = site.id;
		    reusableVEShape.Name = site.name;
		    layer.AddShape(reusableVEShape);
		    reusableVEShape = null;
		}
	  }
	}catch(e) {
	   var msg = "Unknown";
	   if (e instanceof String) {
	   }else if (e.message) {
              msg = e.message;
	   }
	   throw "Unable to populateRwisLayers. Reason - > \n" + msg
	}	
}

function populateWindDirectionLayers(resp)
{	
	try {
	  if (resp.poi.wind) {
		for(var i=0; i < resp.poi.wind.length; i++) {
		    var site = resp.poi.wind[i];		    
		    var sitesOfType = site.windFilterCode.toUpperCase();
		    var btMarkerType = "BuckeyeTrafficMarker.WIND_";
		    var thisShapeLayerTitle = "WIND - ";
		    var popupTitle = "WIND Direction - ";		    
		    if (site.isFunctioning === true) {
		        //Use the wind blowing direction so that the wind icon
		        //is pointing in the direction the wind is blowing
		        btMarkerType += site.windBlowingDirectionFullText.toUpperCase();
		        thisShapeLayerTitle += "FUNCTIONING";
		        popupTitle += site.windDirectionFullText;
		    } else {
		        btMarkerType += "NONFUNCTIONING"
		        thisShapeLayerTitle += "NONFUNCTIONING";
		        popupTitle += "Non-Functioning";                
		    }
		    //Eval the marker type
		    var markerTypeObj = eval(btMarkerType);		    
		    
		    var layer = getOrCreateNamedLayer(thisShapeLayerTitle);	
		    var latLong = new VELatLong(parseFloat(site.latitude), parseFloat(site.longitude));
		    var title = "";
		    title += "<center><b>" + popupTitle + "</b></center><br/>";
		    title += "<b>Site:</b> "+site.name+"<br/>";
		    title += "<b>Status:</b> "+site.worstCondition+"<br/>";
		    title += "<b>Temperature:</b> "+site.airTemp+"<br/>";
		    title += "<b>Avg Wind Speed:</b> "+site.windSpeedAvg+"<br/>";		    
		    title += "<b>Max Wind Speed:</b> "+site.windSpeedMax+"<br/>";		    		    
		    title += "<b>Wind Direction:</b> "+site.windDirectionFullText+"<br/>";		    		    		    
		    title += "<b>Updated:</b> "+site.lastUpdatedDateTime;
	
		    reusableVEShape = new VEShape(VEShapeType.Pushpin, latLong);
		    reusableVEShape.SetTitle(title);
		    if (site.isFunctioning === true)
		    {
                if ($.browser.mozilla)
                {
                   //For some reason VE adds an extra <a> tag around the wind speed text
                   //in FireFox if we use <div> tags but not if we use <span> tags??
		            reusableVEShape.SetCustomIcon(
                    "<span style=\"position:relative;z-index:1;\">" +
                     "<img src=\"" + markerTypeObj.icon() + "\" border=\"0\"/></span>" +
                     "<span class=\"" + markerTypeObj.divClass() + "\">" + site.windSpeedAvgNum + "</span>"
		            );                                                      
                }else {
		            reusableVEShape.SetCustomIcon(
                    "<div style=\"position:relative;z-index:1;\">" +
                     "<img src=\"" + markerTypeObj.icon() + "\" border=\"0\"/></div>" +
                     "<span class=\"" + markerTypeObj.divClass() + "\">" + site.windSpeedAvgNum + "</span>"
		            );                                   
                }
		    }else {
              reusableVEShape.SetCustomIcon(markerTypeObj.icon());		    
		    }
		    reusableVEShape.siteOfType = sitesOfType.toUpperCase();
		    reusableVEShape.BuckeyeTrafficMarkerType = markerTypeObj;		    
		    reusableVEShape.rwisSiteOfType = site.worstCondition.toUpperCase();
		    //If there is no valid logged in user then the 
		    //rwis site type is always public
		    if (!User.valid()){
		      reusableVEShape.rwisSiteOfType = "PUBLIC";
		    }
		    reusableVEShape.isRwisSite = true;
		    reusableVEShape.isWindIcon = true;		    
		    reusableVEShape.SiteId = site.id;
		    reusableVEShape.Name = site.name;
		    layer.AddShape(reusableVEShape);
		    reusableVEShape = null;
		}
	  }
	}catch(e) {
	   var msg = "Unknown";
	   if (e instanceof String) {
	   }else if (e.message) {
              msg = e.message;
	   }
	   throw "Unable to populateWindDirectionLayers. Reason - > \n" + msg
	}	
}

function populateRoadActivityLayers(resp)
{
	try {	
        if (resp.poi.addRoadActivity !== "true") return;		
        for(var i=0; i < resp.poi.roadActivities.length; i++) {
            var ra = resp.poi.roadActivities[i]; 
	    var sitesOfType = ra.filterCode.toUpperCase();
	    var thisShapeLayerTitle = "ROAD ACTIVITY - " + sitesOfType;	    
	    var layer = getOrCreateNamedLayer(thisShapeLayerTitle);
	    var reusableVEShape = createRoadActivityShape(ra);
            layer.AddShape(reusableVEShape);
            reusableVEShape = null;
        }		
	}catch(e) {
	   var msg = "Unknown";
	   if (e instanceof String) {
	   }else if (e.message) {
              msg = e.message;
	   }
	   throw "Unable to populateRoadActivityLayers. Reason - > \n" + msg
	}	
}

function populateClosureRestrictionLayers(resp)
{
	try {			
        if (resp.poi.addClosures !== "true") return;		
        for(var i=0; i < resp.poi.roadActivities.length; i++) {
            var ra = resp.poi.roadActivities[i]; 
	    var sitesOfType = ra.closureFilterCode.toUpperCase();
	    if (sitesOfType.length == 0) continue;
	    var thisShapeLayerTitle = "CLOSURES AND RESTRICTIONS - " + sitesOfType;	    
	    var layer = getOrCreateNamedLayer(thisShapeLayerTitle);
	    var reusableVEShape = createRoadActivityShape(ra);
            layer.AddShape(reusableVEShape);
            reusableVEShape = null;
        }		
	}catch(e) {
	   var msg = "Unknown";
	   if (e instanceof String) {
	   }else if (e.message) {
              msg = e.message;
	   }
	   throw "Unable to populateClosureRestrictionLayers. Reason - > \n" + msg
	}	
}

function createRoadActivityShape(ra)
{
	    var sitesOfType = ra.filterCode.toUpperCase();
            var latLong = new VELatLong(parseFloat(ra.Latitude), parseFloat(ra.Longitude));
            var descTxt = ra.DescriptionText;
            
            if (descTxt.length > 45)
            {
                descTxt = jsLeft(descTxt, 42) + "...";
            }
            
            var title = "";
            title += "<center><b>ROAD ACTIVITY - "+ra.Category.toUpperCase()+"</b></center><br/>";
            title += "<b>Route Name:</b> "+ra.RouteName+"<br/>";
            title += "<b>Road Status:</b> "+ra.StatusText+"<br/>";
            title += "<b>Description:</b> "+descTxt+"<br/>";
            title += "<b>Estimated Start:</b> "+ra.StartTime+"<br/>";
            title += "<b>Estimated End:</b> "+ra.EndTime;

            var btMarkerType = "BuckeyeTrafficMarker."+sitesOfType.toUpperCase()+"_"+ra.StatusText.toUpperCase();

            reusableVEShape = new VEShape(VEShapeType.Pushpin, latLong);
            reusableVEShape.SetTitle(title);
            reusableVEShape.SetCustomIcon("<div class=\""+eval(btMarkerType+".divClass()")+"\"></div>");
            reusableVEShape.BuckeyeTrafficMarkerType = eval(btMarkerType);
            reusableVEShape.siteOfType = sitesOfType.toUpperCase();
            reusableVEShape.Status = ra.Status.toUpperCase();
            reusableVEShape.StatusText = ra.StatusText.toUpperCase();
            reusableVEShape.RoadActivityId = ra.Id;
            reusableVEShape.Category = ra.Category;
            reusableVEShape.isRoadActivity = true;	
	    return reusableVEShape;
}

function populateWinterLayers(resp)
{
	try {		
	    var layers = [];	
		var btMarkerType = "BuckeyeTrafficMarker.WINTER_"; 		
		for(var i=0; i < resp.poi.winter.length; i++) {
			var winterRoute = resp.poi.winter[i];
			var siteOfType = winterRoute.filterCode.toUpperCase();
			var thisShapeLayerTitle = "WINTER CONDITIONS - " + siteOfType;			
			var layer = getOrCreateNamedLayer(thisShapeLayerTitle);

			for(var k=0; k < winterRoute.routePoints.length; k++) {				
			    var point = winterRoute.routePoints[k];			    
			    var latLong = new VELatLong(parseFloat(point.latitude), parseFloat(point.longitude));    
			    var condition = winterRoute.winterLevel;
			    var title = "";
			    title += "<center><b>"+winterRoute.localRouteName+" " + winterRoute.stateRoutename + "</b></center><br/>";
			    title += "<b>Condition:</b> "+winterRoute.winterCode+" ("+condition+")<br/>";
			    title += "<b>Last Updated:</b> "+winterRoute.lastModified+"<br/>";
			    title += "<b>Updated By:</b> "+winterRoute.reportedBy;
			    var reusableVEShape = new VEShape(VEShapeType.Pushpin, latLong);
			    reusableVEShape.SetTitle(title);			    
			    reusableVEShape.SetCustomIcon("<div class=\""+eval(btMarkerType + siteOfType.toUpperCase() + ".divClass()")+"\"></div>");				    
			    reusableVEShape.siteOfType = siteOfType;
			    reusableVEShape.isWinterPoint = true;			    
			    reusableVEShape.BuckeyeTrafficMarkerType = eval(btMarkerType + siteOfType.toUpperCase());			    
			    layer.AddShape(reusableVEShape);			    			    
			    reusableVEShape = null;
			}
		}
	}catch(e) {
	   var msg = "Unknown";
	   if (e instanceof String) {
	   }else if (e.message) {
              msg = e.message;
	   }
	   throw "Unable to populateWinterLayers. Reason - > \n" + msg
	}	
}

function populateMessageSignLayers(resp)
{
    if ( ! resp.poi.messageSigns) { return; }

	try {
	var thisShapeLayerTitle = "MESSAGE SIGNS";
	var layer = getOrCreateNamedLayer(thisShapeLayerTitle);	

        for(var i=0; i < resp.poi.messageSigns.length; i++) {
            var sign = resp.poi.messageSigns[i];
          
            var latLong = new VELatLong(parseFloat(sign.Latitude), parseFloat(sign.Longitude));
            var shape = new VEShape(VEShapeType.Pushpin, latLong);
            var title = "<center><b>MESSAGE SIGN - "+sign.SignName+"</b></center><br/>";

            shape.SetTitle(title);
            shape.SetCustomIcon(BuckeyeTrafficMarker.VMS.icon());
            shape.BuckeyeTrafficMarkerType = BuckeyeTrafficMarker.VMS;
            shape.isVmsSite = true;
            shape.SignId = sign.SignId;
            shape.SignLocation = sign.SignName;

            layer.AddShape(shape);
            shape = null;
        }
	}catch(e) {
	   var msg = "Unknown";
	   if (e instanceof String) {
	   }else if (e.message) {
              msg = e.message;
	   }
	   throw "Unable to populate Message Sign Layers. Reason - > \n" + msg
	}	
}


function populateHarLayers(resp)
{
    if ( ! resp.poi.har) { return; }

	try {
	var thisShapeLayerTitle = "HAR";
	var layer = getOrCreateNamedLayer(thisShapeLayerTitle);	

        for(var i=0; i < resp.poi.har.length; i++) {
            var radio = resp.poi.har[i];
                        
            var latLong = new VELatLong(parseFloat(radio.Latitude), parseFloat(radio.Longitude));
            var shape = new VEShape(VEShapeType.Pushpin, latLong);
            var title = "<center><b>"+radio.Name+"</b></center><br/>";

            shape.SetTitle(title);
            shape.SetCustomIcon(BuckeyeTrafficMarker.HAR.icon());
            shape.BuckeyeTrafficMarkerType = BuckeyeTrafficMarker.HAR;
            shape.isHarSite = true;
            shape.RadioId = radio.Id;
            shape.RadioLocation = radio.Name;

            layer.AddShape(shape);
            shape = null;
        }
	}catch(e) {
	   var msg = "Unknown";
	   if (e instanceof String) {
	   }else if (e.message) {
              msg = e.message;
	   }
	   throw "Unable to populate Radio Layer. Reason - > \n" + msg
	}	
}

//------------------------------------------------------------------------------------------------------------
/*
This function locates a VEShapeLayer with then given name if it does not exist it
creates an empty layer with that name. This method should always return
a non-null VEShapeLayer.
*/
function getOrCreateNamedLayer(thisShapeLayerTitle) {
    var thisShapeLayerExists = false;
    var thisShapeLayerIndex = shapeLayersArr.length;

    for (var shapeLayerCounter=0;shapeLayerCounter<shapeLayersArr.length;shapeLayerCounter++){
        if (shapeLayersArr[shapeLayerCounter].title === thisShapeLayerTitle){
            thisShapeLayerExists = true;
            thisShapeLayerIndex = shapeLayerCounter;
            reusableVEShapeLayer = map.GetShapeLayerByIndex(thisShapeLayerIndex);
            break;
        }
    }

    //If the layer does not exist then create an empty one with this
    //name
    if (!thisShapeLayerExists){
        var tmp = new Object();
        tmp.title = thisShapeLayerTitle;
        shapeLayersArr[shapeLayersArr.length] = tmp;
        tmp = null;
        reusableVEShapeLayer = new VEShapeLayer();
        reusableVEShapeLayer.SetTitle(thisShapeLayerTitle);
        map.AddShapeLayer(reusableVEShapeLayer);
    }
    return reusableVEShapeLayer;
}

//------------------------------------------------------------------------------------------------------------
/*
Gets the current VEMap bounding box.
*/
function getMapBounds(map, mapContainerId) {
	try {
		var bb = new BoundingBox();
		var containerSelector = "#"+mapContainerId;
		var mapDiv = $(containerSelector);
		if (mapDiv ==  null) throw "Unable to locate map container using id " + mapContainerId;
		
		//Width and height of map should be based on width and height of container 
		var mapWidth = mapDiv.width();		
		var mapHeight = mapDiv.height();	
		
		//Top left is always 0,0
		var topLeft = map.PixelToLatLong(new VEPixel(0,0));
		if (topLeft) {
		   bb.topLeftLat = topLeft.Latitude;
		   bb.topLeftLong = topLeft.Longitude;
		}
						
		//Bottom right is based on widht and height of map
		var bottomRight = map.PixelToLatLong(new VEPixel(mapWidth,mapHeight));
		if (bottomRight) {
		   bb.bottomRightLat = bottomRight.Latitude;
		   bb.bottomRightLong = bottomRight.Longitude;
		}	
		return bb;	
	}catch(e) {
	   var msg = "Unknown";
	   if (e instanceof String) {
	   }else if (e.message) {
              msg = e.message;
	   }
	   throw "Unable to get bounding box for VeMap. Reason - > \n" + msg
	}
}
//------------------------------------------------------------------------------------------------------------


function loadControlCameraSelector()
{
    openwindows[openwindows.length] = window.open("dialogs/cameras/SelectCamera.aspx?type=control&useTours=false", "", "width=880,height=500,left=50,top=50");  
    resetAdminTools();
}

function loadCameraPanelSelector()
{
    openwindows[openwindows.length] = window.open("dialogs/cameras/SelectCamera.aspx?type=panel", "", "width=880,height=500,left=50,top=50");  
    resetAdminTools();
}

function loadCameraBank()
{
    openwindows[openwindows.length] = window.open("dialogs/cameras/CameraBank.aspx", "", "width=800, height=600,resizable=1,left=50,top=50");  
    resetAdminTools();
}

function loadEditCameraTours()
{
    openwindows[openwindows.length] = window.open("dialogs/cameras/EditCameraTours.aspx", "", "width=600, height=600,left=50,top=50");  
    resetAdminTools();
}

//------------------------------------------------------------------------------------------------------------
var deviceLayer = null;
function deviceLayerZoomHandler() {

    displayDevices();
}
function removeDeviceLayer()
{
    if (deviceLayer){
        //Virtual Earth throws exception if layer
        //does not exists so just ignore exception
        try {
            map.DeleteShapeLayer(deviceLayer);            
        }catch(e){}
        deviceLayer = null;
    }
}

function populateDeviceLayer(resp) {
    try {    
        var devices = resp.devices;
        if (!deviceLayer){
            deviceLayer = new VEShapeLayer();                 
            map.AddShapeLayer(deviceLayer);            
        }        
        deviceLayer.DeleteAllShapes();
        if (devices) {        
            for(var i=0; i<devices.length; i++){
                var d = devices[i];
                var latLong = new VELatLong(d.Latitude, d.Longitude);
                var shape = new VEShape(VEShapeType.Pushpin, latLong);
                var title = "<center><b> Device ID: "+d.DeviceId+"</b></center><br/>";
                title += "<b>Road Name:</b> "+d.RoadName+"<br/>";
                title += "<b>Road Direction:</b> "+d.RoadDirection+"<br/>";
                title += "<b>Mile Post:</b> "+d.MilePost+"<br/>";            
                title += "<b>Last Updated:</b> "+d.DeviceUpdateTime+"<br/>";
                title += "<b>Status:</b> "+d.DeviceStatus+"<br/>";                                
                title += "<b>Speed:</b> "+d.Speed+"<br/>";                                                
                shape.SetTitle(title);
                shape.SetCustomIcon("images/fmsicons/traffic_sensor_icon.gif");
                shape.isSpeedInfoIcon = true;
                shape.deviceId = d.DeviceId;
                shape.onMouseOver = function(){
                    var pixel = map.LatLongToPixel(this);
                    $("#divHoverInfo").html(this.GetTitle());
                    $("#divHoverInfo").css("left", (pixel.x + 175)+"px");
                    $("#divHoverInfo").css("top", (pixel.y - 25)+"px");
                    $("#divHoverInfo").css( { "background-color":"#9933CC", "color":"#FFFFFF" } );
                    $("#divHoverInfo").css("display", "block");
                }
                deviceLayer.AddShape(shape);
                shape = null;
            }    
        }
    }catch(e) {
       var msg = "Unknown";
       if (e instanceof String) {
       }else if (e.message) {
              msg = e.message;
       }
       alert("Unable to populate speed info display. Reason - > \n" + msg);
    }        	           
}

function displayDevices() {
    var regionsToLoad = getSelectedTrafficDeviceCoverageAreas();        
    if(regionsToLoad != null && regionsToLoad != ""){       
        //Do Ajax query to fetch devices
        var successHandler = function(resp) {
         if ((!resp) || (resp.success != true)) {
            var msg = 'The server was unable to process your request at this time.'
            if (resp.errorMsg){
               msg+= 'Reason ->\n' + resp.errorMsg;
            }
            alert('Error!\n' + msg);	                
         } else {
            populateDeviceLayer(resp);
         }
        };        
        
        var errorHandler = function(xhr) {
            alert('Error: ' + xhr.status + '\nThe server was unable to process your request at this time.');
        };

        var level = map.GetZoomLevel();
        $.ajax({
		type: "POST",
		url: 'ajax/traffic_speed/DisplayTrafficSpeedDevices.aspx',
		data: {zoomLevel: level, regions: regionsToLoad},
		success: successHandler,
		error: errorHandler,
		dataType: "json"
	    });            
	 } else {	 
	    removeDeviceLayer();
	 }
}        

var displaySpeedInfoTimer = null;
function doDisplaySpeedInfoWithTimer()
{
    if (displaySpeedInfoTimer) window.clearInterval(displaySpeedInfoTimer);
    //Do the initial display now
    doDisplaySpeedInfo();
    //Set the update timer
    //TODO: Make this interval configurable. For now refresh display every 2 minutes
    //window.setInterval("doDisplaySpeedInfo()",120000);            
    displaySpeedInfoTimer = window.setInterval("doDisplaySpeedInfo()", 120000);
}

function doDisplaySpeedInfo()
{
    try {
		var regions = getSelectedTrafficSpeedCoverageAreas();
        if (!TrafficSpeedDisplay.isInitialized()){
           TrafficSpeedDisplay.init(map, regions);
        } else {
            TrafficSpeedDisplay.reloadSpeedTileLayer(regions);
        }
    }catch(e) {
       var msg = "Unknown";
       if (e instanceof String) {
       }else if (e.message) {
              msg = e.message;
       }
       alert("Unable to populate speed info display. Reason - > \n" + msg);
    }
}

function displaySpeedInfoForUser() {
    if (User.isInRole("APP-BUC-Traffic Speed Viewer")) {
        doDisplaySpeedInfoWithTimer();
    } else {
        doDisplaySpeedInfo(); 
    }
}

function loadTrafficSegmentEditor()
{
    resetAdminTools();
}


function doToggleSpeedDisplay(elem){	
    var elemName = elem.id.split("_")[0];
    var sitesOfType = elem.id.split("_")[1];
    var chkBoxId = "#tsSpeedInfoChk_" + sitesOfType;    
    var elem = $(chkBoxId);
	var chkBox = elem.get(0);
	var allChkBox = $("#tsSpeedInfoChk_ALL").get(0);	
    var chkElemChecked = chkBox.checked;	

    //If by link, toggle to opposite of current display (based on checked
    //attribute of the corresponding checkbox).  Otherwise, base display
    //on checked attribute of the selected checkbox.
    if (elemName === "tsSpeedInfoLink") { chkElemChecked = !chkElemChecked; };
	
    /* 
	First make sure all the check box states are correct based on the following rules
	
    BR.1) If ALL parent node is checked then ALL immediate child nodes of that parent are checked
    BR.2) If the ALL parent node is being cleared then ALL immediate child nodes of the parent are cleared.
    BR.3) If the last cleared child node for a given ALL parent node becomes checked, mark that parent node as checked.
    BR.4) If a child node is cleared and the ALL parent node is checked then the parent should be cleared
	*/
	if (sitesOfType === "ALL") {
		if (chkElemChecked) {
			//Mark all checkboxes as checked
			$('input[type=checkbox][id^=tsSpeedInfo]').each(function() {
				this.checked = true;		
			});			
		} else {
			//Mark all checkboxes as cleared
			$('input[type=checkbox][id^=tsSpeedInfo]').each(function() {
				this.checked = false;		
			});			
		}
	} else {
		if (chkBox) {
			if (chkElemChecked) {
				//Check this checkbox
				chkBox.checked = true;			
			} else {
				//Clear this checkbox
				chkBox.checked = false;
				//Make sure the ALL category is cleared
				allChkBox.checked = false;
			}
		}		
	}

	displaySpeedInfoForUser();
}

function doToggleDeviceDisplay(elem){	
    var elemName = elem.id.split("_")[0];
    var sitesOfType = elem.id.split("_")[1];
    var chkBoxId = "#tsTrafficDeviceChk_" + sitesOfType;
    var elem = $(chkBoxId);
    var chkBox = elem.get(0);
    var allChkBoxId = "#tsTrafficDeviceChk_ALL";
	var allChkBox = $(allChkBoxId).get(0);
    var chkElemChecked = chkBox.checked;	

    //If by link, toggle to opposite of current display (based on checked
    //attribute of the corresponding checkbox).  Otherwise, base display
    //on checked attribute of the selected checkbox.
    if (elemName === "tsTrafficDeviceLink") { chkElemChecked = !chkElemChecked; };
	
    /* 
	First make sure all the check box states are correct based on the following rules
	
    BR.1) If ALL parent node is checked then ALL immediate child nodes of that parent are checked
    BR.2) If the ALL parent node is being cleared then ALL immediate child nodes of the parent are cleared.
    BR.3) If the last cleared child node for a given ALL parent node becomes checked, mark that parent node as checked.
    BR.4) If a child node is cleared and the ALL parent node is checked then the parent should be cleared
	*/
	if (sitesOfType === "ALL") {
		if (chkElemChecked) {
			//Mark all checkboxes as checked
			$('input[type=checkbox][id^=tsTrafficDevice]').each(function() {
				this.checked = true;		
			});			
		} else {
			//Mark all checkboxes as cleared
			$('input[type=checkbox][id^=tsTrafficDevice]').each(function() {
				this.checked = false;		
			});			
		}
    } else {
        if (chkBox) {
            if (chkElemChecked) {
                //Check this checkbox
                chkBox.checked = true;
            } else {
                //Clear this checkbox
                chkBox.checked = false;
                //Make sure the ALL category is cleared
                allChkBox.checked = false;
            }
        }
    }
    
    window.setTimeout('displayDevices()',300);		
}

//Returns selected traffic speed coverage area codes as comma seperated list
function getSelectedTrafficSpeedCoverageAreas() {
	var buf = [];
	$('input[type=checkbox][id^=tsSpeedInfo]').each(function() {
			if (this.checked) {
			  buf[buf.length] = this.id.split("_")[1];				
			}
	});
	return buf.join(',');	
}

//Returns selected traffic device coverage area codes as comma seperated list
function getSelectedTrafficDeviceCoverageAreas() {
	var buf = [];
	$('input[type=checkbox][id^=tsTrafficDevice]').each(function() {
			if (this.checked) {
			  buf[buf.length] = this.id.split("_")[1];				
			}
	});
	return buf.join(',');	
}

//------------------------------------------------------------------------------------------------------------
function doToggleDMSSigns(elem)
{
    var chkElemChecked = $("#"+elem.id).attr("checked");

    if (chkElemChecked) { doShowMessageSigns(); }
    else { doHideMessageSigns(); }
}
//------------------------------------------------------------------------------------------------------------
//function TokenHandler(e)
//{
//    try { doReInitializeMap(); }
//    catch(e) {  }
//}
//------------------------------------------------------------------------------------------------------------
//function doReInitializeMap()
//{
//    var mapMode = null;
//    var mapStyle = null;

//    var successHandler = function(resp) {
//        if ((!resp) || (resp.success != true))
//        {
//            alert("An unexpected error has occurred.  BuckeyeTraffic needs to reload.");
//            location = location;
//        }
//        else
//        {
//            tokenJSON = resp.tokenInfo;

//            var opts = new VEMapOptions();
//            opts.EnableBirdseye = false;
//            map.SetClientToken(tokenJSON.tokenStr);
//            map.LoadMap(reusableVELatLong, currentMapZoomLevel, mapStyle, false, mapMode, true, 0, opts);

//            reusableVEShapeLayer = new VEShapeLayer();
//            reusableVEShapeLayer.SetTitle("Working Layer");
//            map.AddShapeLayer(reusableVEShapeLayer);

//            map.AttachEvent("onclick", MouseHandler);
//            map.AttachEvent("onmouseover", MouseHandler);
//            map.AttachEvent("onmouseout", MouseHandler);
//            map.AttachEvent("onmousemove", MouseHandler);
//            map.AttachEvent("onkeydown", KeyboardHandler);
//            map.AttachEvent("onendzoom", ZoomHandler);
//            map.AttachEvent("ontokenerror", TokenHandler);
//            map.AttachEvent("ontokenexpire", TokenHandler);
//            
//            doApplyTravelStatusFilters();
//            
//            if (($("#tsSpeedInfoChk_ALL").attr("checked") != null) && ($("#tsSpeedInfoChk_ALL").attr("checked") != "undefined"))
//            {
//                try
//                {
//                    TrafficSpeedDisplay.init(map);
//                    if (displaySpeedInfoTimer) { window.clearInterval(displaySpeedInfoTimer); }
//                    displaySpeedInfoTimer = window.setInterval("doDisplaySpeedInfo()",120000);
//                }
//                catch(e)
//                {
//                    var msg = "Unknown";
//                    if (e instanceof String) { }
//                    else if (e.message) { msg = e.message; }

//                    alert("Unable to populate speed info display. Reason - > \n" + msg);
//                }
//            }
//        }
//    };        
//        
//    var errorHandler = function(resp) {
//        alert("An unexpected error has occurred.  BuckeyeTraffic needs to reload.");
//        location = location;
//    };

//    if (map != null)
//    {
//        currentMapZoomLevel = map.GetZoomLevel();
//        reusableVELatLong = map.GetCenter();
//        mapMode = map.GetMapMode();
//        mapStyle = map.GetMapStyle();
//        map.DeleteAllShapeLayers();
//        map.DetachEvent("onclick", MouseHandler);
//        map.DetachEvent("onmouseover", MouseHandler);
//        map.DetachEvent("onmouseout", MouseHandler);
//        map.DetachEvent("onmousemove", MouseHandler);
//        map.DetachEvent("onkeydown", KeyboardHandler);
//        map.DetachEvent("onendzoom", ZoomHandler);
//        map.DetachEvent("ontokenerror", TokenHandler);
//        map.DetachEvent("ontokenexpire", TokenHandler);
//        map.Dispose();

//        shapeLayersArr = new Array({"title":"Base Layer"},{"title":"Working Layer"});
//        map = new VEMap(mapContainerId);
//    }

//   //Do JSON post to server and process response
//    $.ajax({
//		type: "POST",
//		url: 'ajax/ve_token/obtainToken.aspx',
//		data: { },
//		success: successHandler,
//		error: errorHandler,
//		dataType: "json"
//    });            
//}
//------------------------------------------------------------------------------------------------------------
