﻿// JScript File
// This javascript file should be used when the page has the interactive map
// and the filter bar and grid.

/*******************************************************************************/
// Global properties
    
    // ids for filters used for Bus Routes such as Region, Exchange, Type
    var BusRouteRegionSelectName = "BusRoute_ddlRegion";
    var BusRouteExchangeSelectName = "BusRoute_ddlExchange";
    var BusRouteTypeSelectName = "BusRoute_ddlType";
    
    // ids of the tabs that represent the bottom datagrids section
    var AdvisoriesTabId = "AdvisoriesTab";
    var CameraGroupsTabId = "GroupTab";
    var CamerasTabId = "CameraTab";
    var BusRoutesTabId = "BusRoutesTab";

    var DataGridTabCookieName = 'DataGridTabCookieName';
    
    
/*******************************************************************************/
/* Functions */


//*******************************************************************************
// Function:     LoadGridData
// Author:       michael.chu@cgi.com
// Project:      iMove Build - 0.7
// Date:         Nov 09, 2006
//
// Description:  The following function loads or reloads advisories, 
//               camera groups, cameras and bus routes data on the grid
//               based on the current tab it is on.
//
//               When panning/zooming the map, advisories and cameras grids
//               will need to be reloaded based on what is shown on the map, 
//               but not for the camera groups or bus routes grids.
//
// Parameters:   isPanAndZoom - true to indicate that this function is called
//                              when it is being panned or zoomed
// Returns:      
// Calls:        
// Called By:    First load or pan/zoom events or filter criteria change event
//
// Revision History:
//
//   Name        Date        Description
//  ------       ------      ------------------------------------------------
//  Michael Chu  Nov 9, 2006 Modify to account for bus routes
//*******************************************************************************    
function LoadGridData( isPanAndZoom ) {
    
    //special cases for initializing grid data for firefox
    if ( moz || op ) {

        fireFoxGridCount = fireFoxGridCount + 1;
        //alert("yo load grid data, FF grid count is:" + fireFoxGridCount);

        if ( (fireFoxGridCount == 2) && (fireFoxGridHasLoaded == false) ) {
            
            //alert("exit function");
            fireFoxGridHasLoaded = true;                        
            fireFoxGridCount = 0;
        
        } else {
            
            //alert("load firefox grid normally, FF grid count is:" + fireFoxGridCount);            
            LoadGridDataCode( isPanAndZoom );
        }

    } else {
    
        //alert("load grid normally for IE");

        LoadGridDataCode( isPanAndZoom );
    }

	
} // end function


function LoadGridDataCode( isPanAndZoom ) {

// Debug variable (set to 1 to debug)
var debug = 0;

if (debug)
{
    // Retrieve active tab cookie
    var activeTab = Get_Cookie( 'activeTab' );
    var defaultTab = Get_Cookie( 'defaultTab' );

    var reloadGridWithOldBusRoutes = 0;


    alert('LoadGridData - Beginning()\n' + 
	  'active tab: ' + activeTab + '\n' +
	  'default tab: ' + defaultTab + '\n');
}

if (debug)	
    alert('LoadGridData');


	// Load/re-load the grid with advisories and cameras based on filtered criteria.
	var tabSelectedId = GridTabSelected();        

	// Retrieved filtered criteria query strings
	filteredAdvisories = filterAdvisories();


	filteredCameras = filterCameras();
	filteredCameraGroups = filterCameraGroups();
	filteredBusRoutes = filterBusRoutes();
	filteredBusRoutesMap = filterBusRoutesMap();

if (debug)	
{
    alert('filteredAdvisories:' + filteredAdvisories);
    alert('filteredCameraGroups:' + filteredCameraGroups);
    alert('filteredCameras:' + filteredCameras);
    alert('filteredBusRoutes:' + filteredBusRoutes);
}

	// This only happens on initial Load, set it to load advisories tab.
	if (tabSelectedId == "")
	{
if (debug)	
    alert('Initial Load: Set bottom tab to select advisories so the grid can be loaded');

	    tabSelectedId = AdvisoriesTabId;
	}

if (debugPerformance)
    PrintElapseTime("Start LoadGridContentBasedOnXMLData");

	if (tabSelectedId == AdvisoriesTabId)
	{
	    // When panning/zooming map, reload grid for advisories

	   // alert("clear grid data");

	    // Clear existing grid content
	ClearGridContentForTab(tabSelectedId);

	//alert("filterd are: " + filteredAdvisories);

	var advisoriesTab = document.getElementById(AdvisoriesTabId);
	LoadGridContentBasedOnXMLData('Events', filteredAdvisories, advisoriesTab); 
    advisoriesTab = null;
	//alert("load grid data 2");


    }
    else if (tabSelectedId == CameraGroupsTabId)
	{
	    // When panning/zooming map, don't reload grid for camera groups
	    if (isPanAndZoom != true)
	    {
		// Clear existing grid content
	    ClearGridContentForTab(tabSelectedId);

	    var cameraGroupsTab = document.getElementById(CameraGroupsTabId);
	    LoadGridContentBasedOnXMLData('CameraGroups', filteredCameraGroups, cameraGroupsTab);
	    cameraGroupsTab = null;
	}
    }
    else if (tabSelectedId == CamerasTabId)
	{
	    // When panning/zooming map, reload grid for cameras

	    // Clear existing grid content
	ClearGridContentForTab(tabSelectedId);

	var camerasTab = document.getElementById(CamerasTabId);
	LoadGridContentBasedOnXMLData('Cameras', filteredCameras, camerasTab);
	camerasTab = null;
    }
    else if (tabSelectedId == BusRoutesTabId)
	{

	    //check to see if the fullscreen map flag cookie has been switched
	    var fullScreenBusRoutesFlagCookie = Get_Cookie( FullScreenBusRoutesFlagCookie );
	    if (fullScreenBusRoutesFlagCookie != null){

		    if ( isFullScreenMap == false ){ 

			//alert("delete the fullscreen map cookies for good luck");

			//we are back on regular map , delete the fullscreen map bus routes cookie for good luck
			Delete_Cookie( FSactiveBusRoutesCookieName, '/', '' );
			Delete_Cookie( FShighlightBusRouteCookieName, '/', '' );
			Delete_Cookie( FSactiveBusRoutesStopsCookieName, '/', '' );

			Delete_Cookie( FullScreenBusRoutesFlagCookie, '/', '' );

		     }                           

	    } else {

	    }


	    // When panning/zooming map, don't reload grid for bus routes
	    if (isPanAndZoom != true)
	    {
		// When loading bus route grids, show loading message.
		// Loading message will be turned off in state_change event when grid HTML 
		// information has been downloaded and set to the div element.
		showLoadingGrid();


	       if ( isFullScreenMap == true ){

		    //alert("refilter the bus routes fullscreen");
		    filteredBusRoutes = filterBusRoutes();
		    filteredBusRoutesMap = filterBusRoutesMap();

		    var busRoutesTab = document.getElementById(BusRoutesTabId);
		    LoadGridContentBasedOnXMLData('BusRoutes', filteredBusRoutes, busRoutesTab);

		    //alert("load fullscreen grid, bus routes are:" + filteredBusRoutes);

		    LoadGridContentBasedOnXMLData('BusRoutesMap', filteredBusRoutesMap, busRoutesTab);
            busRoutesTab = null;
	       } else {

		//***BRIAN TO DO: ADD CODE FOR FULLSCREEN MAP ACTIVE ROUTES COOKIE HERE ***

		    //alert("refilter the bus routes reg map");
		    filteredBusRoutes = filterBusRoutes();
		    filteredBusRoutesMap = filterBusRoutesMap();                            

		    var busRoutesTab = document.getElementById(BusRoutesTabId);                            
		    //alert("load normal grid1, bus routes are:" + filteredBusRoutes);

		    LoadGridContentBasedOnXMLData('BusRoutes', filteredBusRoutes, busRoutesTab);                            
		    //alert("load normal grid2, bus routes are:" + filteredBusRoutes);

		    LoadGridContentBasedOnXMLData('BusRoutesMap', filteredBusRoutesMap, busRoutesTab);
            busRoutesTab = null;
	       }


	}
 }

if (debugPerformance)
    PrintElapseTime("LoadGridData");

}


//*******************************************************************************
// Function:     FilterHandler
// Author:       michael.chu@cgi.com
// Project:      iMove Build - 0.3
// Date:         Sep 11, 2006
//
// Description:  The following function load or reloads advisories or cameras data.
//               It performs the following two actions:
//               1. If region is selected, pan/zoom to the region
//                  otherwise, keep default region and zoom level.
//               2. Load the map with advisories or cameras based on filtered criteria.
//                  If map consists of advisories or cameras data, it will remove data 
//                  and overlays, and re-add the data and overlays based 
//                  any filtered criteria.
//               3. Load the grid with advisories or cameras based on filtered criteria.
//
// Parameters:   isFilterRegion - indicates whether region is being filtered
// Returns:      
// Calls:        PanAndZoomToRegion(), LoadMapData(), LoadGridData()
// Called By:    Advisories or Cameras "Filter By" criteria change event
//
// Revision History:
//
//   Name        Date        Description
//  ------       ------      ------------------------------------------------
//
//*******************************************************************************    
function FilterHandler(isFilterRegion) {

// Debug variable (set to 1 to debug)
var debug = 0;

if (debug)	
    alert('FilterHandler(): isFilterRegion - ' + isFilterRegion);

    PanAndZoomToRegion(isFilterRegion);
    
    // The following code has been omitted because it will be called 
    // by PanAndZoomHandler, thus, no need to call twice.
    // This commented out code is leave here for future reference.
    
//    LoadMapData();
//    LoadGridData();

}

//*******************************************************************************
// Function:     PanAndZoomHandler
// Author:       michael.chu@cgi.com
// Project:      iMove Build - 0.1
// Date:         Sep 01, 2006
//
// Description:  Load the map with advisories and cameras based on filtered criteria.
//               If map consists of advisories and cameras data, it will remove data 
//               and overlays, and re-add the data and overlays based 
//               any filtered criteria.
//
// Parameters:   
// Returns:      
// Calls:        LoadMapData(), LoadGridData()
// Called By:    Pan/Zoom event of the map
//
// Revision History:
//
//   Name        Date        Description
//  ------       ------      ------------------------------------------------
//
//*******************************************************************************    
function PanAndZoomHandler() {
    
    LoadMapData();
    
    // Pass in with first parameter indicating it is called by PanAndZoomHandler
    LoadGridData(true);
    
}

//*******************************************************************************
// Event:        BottomTabChangedHandler
// Author:       michael.chu@cgi.com
// Project:      iMove Build - 0.3
// Date:         Sep 11, 2006
//
// Description:  Reload the grid with advisories, camera groups, cameras or
//               bus routes based on default criteria. This event is caused 
//               by the selection of a different tab.
//
// Parameters:   
// Returns:      
// Calls:        
// Called By:    Advisories/Camera Groups/Cameras tab onclick event
//
// Revision History:
//
//   Name        Date        Description
//  ------       ------      ------------------------------------------------
//  Michael Chu  Nov 09      Add bus routes.
//*******************************************************************************    
function BottomTabChangedHandler()
{    
    
    // Remove existing grid related cookies in order to reload the grid content
    ClearGridRelatedCookiesForTab();
    
    // Retrieve active tab cookie
    var activeTab = Get_Cookie( 'activeTab' );

    // Retrieve the tab it is currently on
    var tabSelectedId = GridTabSelected();
                
    //SPECIAL CASE: Only initialize default bus routes
    //when it is on the bus route tab
        switch( activeTab )     
        {                
            case "Transit" : {
            
            
                //Brian commented out the following lines below:  Feb 14 2007

            //    if (tabSelect.edId == BusRoutesTabId) {
                    
                    // Remove existing grid related cookies in order to reload the grid content
              //      ClearGridRelatedCookiesForTab();

                    // toggle on three bus routes as default layers for the 
                    // Transit tab, they are Route Numbers: 97, 98, and 99. 
                   // ToggleDefaultBusRoutesOnMap();
                //}
                
                break; 
            }
            default: {
            
                break;
            }
        }
    
    // need to refresh advisories/cameras data once user switch to another tab
    LoadMapData(); 
    
    LoadGridData();
}

//*******************************************************************************
// Function:     PanAndZoomToRegion
// Author:       michael.chu@cgi.com
// Project:      iMove Build - 0.1
// Date:         Sep 01, 2006
//
// Description:  If region is selected on the advisories Filter By criteria, 
//               the function will pan/zoom to the region,
//               otherwise, nothing happens and it will keep 
//               default region and zoom level.
//
//
// Parameters:   isFilterRegion - indicates whether region is being filtered
// Returns:      
// Calls:        
// Called By:    FilterAdvisoriesHandler(Advisories "Filter By" criteria change event)
//
// Revision History:
//
//   Name        Date        Description
//  ------       ------      ------------------------------------------------
//
//*******************************************************************************    
function PanAndZoomToRegion(isFilterRegion){

// Debug variable (set to 1 to debug)
var debug = 0;


    // if region is not being filtered, then skip pan/zoom to region
    if (isFilterRegion == false)
    {
        // Since map is not re-positioned to center based on region,
        // the PanAndZoomHandler event will not be raised and hence
        // the functions LoadMapData() and LoadGridData() will not be called.
        // We need to call this here.
        
if (debug)
    alert("region is not selected as filter");
        
        LoadMapData();
        LoadGridData();
        
        return;
    }
    
    // if region is being filtered, then pan/zoom to region or default map view
    
    // Get filtered region xml response path
    var filteredRegion = filterRegion();
        
    var index = filteredRegion.indexOf("?");
    var lastIndex = filteredRegion.length;
    var region = filteredRegion.substring(index+1, lastIndex);
        
        
if (debug)
    alert("region being filtered: " + region);
    
if (debug)        
    alert('filteredRegion: ' + filteredRegion);

    // If a region is selected, then pan/zoom to region        
    if (region != "")
    {
        // 1. If region is selected, pan/zoom to the region
        //    otherwise, keep default region and zoom level.
        // Get region center coordinate and zoom level
	    GDownloadUrl(filteredRegion, function(data, responseCode) {
	      var xml = GXml.parse(data);
    	  
	      var region = xml.documentElement.getElementsByTagName("region");
	      if (region == null)
	        return;
          
	      var centerPoint = region[0].getElementsByTagName("point");
	      if (centerPoint == null)
	        return 0;
    	 
            var center = new GLatLng(parseFloat(centerPoint[0].getAttribute("lat")),
	                                parseFloat(centerPoint[0].getAttribute("long")));
    	   
            var zooms = region[0].getElementsByTagName("zoomLevel");

if (debug)	            
    alert('zooms length:' + zooms.length);
            
            if (zooms == null)
	            return 0;
    	    
            var zoom = parseInt(zooms.item(0).firstChild.nodeValue);
if (debug)	
    alert('zoomLevel:' + zoom);
            
            // Pan/zoom to the region
            map.setCenter(center, zoom);

if (debug)            
    alert('pan/zoom map to region (center['+ center.lat() + ',' + center.lng() + '], zoom[' + zoom + '])'); 
    	          
	});
	
	}
	else
	{
	    // If default "All" region is selected, then set map to default view
        SetDefaultMapCenterAndZoomLevel();
	}
	
    // manually call load grid data for special cases        
    LoadGridDataWhenNotPanAndZoom();

}

//*******************************************************************************
// Function:     filterCameraGroups
// Author:       michael.chu@cgi.com
// Project:      iMove Build - 0.3
// Date:         Sep 12, 2006
//
// Description:  The following function returns the filtered camera groups path 
//               with query string. 
//               This function depends on hardcoded dropdownlist ids to find
//               selected values. 
//
// Parameters:   
// Returns:      Returns the filtered camera groups path with query string in order 
//               to retrieve XML response data.
// Calls:        
// Called By:    LoadGridData()
//
// Revision History:
//
//   Name        Date        Description
//  ------       ------      ------------------------------------------------
//
//*******************************************************************************    
function filterCameraGroups() {

// Debug variable (set to 1 to debug)
var debug = 0;

if (debug)
    alert("filterCameraGroups()");
        
        // return the path including query string 
        // for retrieving the filtered response
        return CameraGroupsXmlResponsePath + "?" + filterCameraGroupsQueryString();
}// end function

//*******************************************************************************
// Function:     filterCameraGroupsQueryString
// Author:       michael.chu@cgi.com
// Project:      iMove Build - 0.3
// Date:         Sep 12, 2006
//
// Description:  The following function returns the filtered camera groups path 
//               with query string. 
//               This function depends on hardcoded dropdownlist ids to find
//               selected values. 
//
// Parameters:   
// Returns:      Returns the filtered camera groups path with query string in order 
//               to retrieve XML response data.
// Calls:        
// Called By:    LoadGridData()
//
// Revision History:
//
//   Name        Date        Description
//  ------       ------      ------------------------------------------------
//
//*******************************************************************************    
function filterCameraGroupsQueryString() {

// Debug variable (set to 1 to debug)
var debug = 0;

if (debug)
    alert("filterCameraGroups()");
        
        // Retrieve filter criteria selected text values
        var ddlCameraGroupName = document.getElementById(CameraGroupNameSelectName);
        if (ddlCameraGroupName != null)
            cameraGroupName = ddlCameraGroupName.options[ddlCameraGroupName.selectedIndex].text;
        else
            cameraGroupName = "All";
            
        var ddlCameraGroupDescription = document.getElementById(CameraGroupDescriptionSelectName);
        if (ddlCameraGroupDescription != null)
            cameraGroupDescription = ddlCameraGroupDescription.options[ddlCameraGroupDescription.selectedIndex].text;
        else
            cameraGroupDescription = "All";
            
        var ddlCameraGroupRegion = document.getElementById(CameraGroupRegionSelectName);
        if (ddlCameraGroupRegion != null)
            cameraGroupRegion = ddlCameraGroupRegion.options[ddlCameraGroupRegion.selectedIndex].text;
        else
            cameraGroupRegion = "All";

if (debug)
{
    alert("cameraGroupName: " + cameraGroupName);
    alert("cameraGroupDescription: " + cameraGroupDescription);
    alert("cameraGroupRegion: " + cameraGroupRegion);
}
        // URL encode string
        cameraGroupName = URLEncode(cameraGroupName);
        cameraGroupDescription = URLEncode(cameraGroupDescription);
        cameraGroupRegion = URLEncode(cameraGroupRegion);
            
        // Build individual query string
        nameQS = "";
        if (cameraGroupName != "All")
            nameQS = "name=" + cameraGroupName;

        descriptionQS = "";
        if (cameraGroupDescription != "All")
            descriptionQS = "description=" + cameraGroupDescription;

        regionQS = "";
        if (cameraGroupRegion != "All")
            regionQS = "region=" + cameraGroupRegion;

        // Build query string
        queryString = "";

        if (nameQS != "")
        {
            if (queryString != "")
                queryString += "&" + nameQS;
            else
                queryString = nameQS;
        }
        if (descriptionQS != "")
        {
            if (queryString != "")
                queryString += "&" + descriptionQS;
            else
                queryString = descriptionQS;
        }
        if (regionQS != "")
        {
            if (queryString != "")
                queryString += "&" + regionQS;
            else
                queryString = regionQS;
        }
        
        // Since camera groups are not shown on map,
        // camera groups will not be filtered by map boundaries and zoom level,
        // hence the following code is commented out for reference.
//        // Include filter for map boundaries and zoom level
//        if (queryString != null && queryString != "")
//            queryString += "&" + filterMapBoundariesAndZoomLevel();
//        else
//            queryString += filterMapBoundariesAndZoomLevel();
            
            
        ddlCameraGroupName = null;
        ddlCameraGroupRegion = null;
        ddlCameraGroupDescription = null;
        // return the query string for retrieving the filtered response
        return queryString;
}// end function

//*******************************************************************************
// Function:     filterBusRoutes
// Author:       michael.chu@cgi.com
// Project:      iMove Build - 0.7
// Date:         Nov 09, 2006
//
// Description:  The following function returns the filtered bus routes path with
//               query string. 
//               This function depends on hardcoded dropdownlist ids to find
//               selected values.
//              
//               Only data within map boundaries and satisfaction of specified 
//               zoom level are shown.
//
// Parameters:   
// Returns:      Returns the filtered bus routes path with query string in order 
//               to retrieve XML response data.
// Calls:        
// Called By:    LoadMapData(), LoadGridData()
//
// Revision History:
//
//   Name        Date        Description
//  ------       ------      ------------------------------------------------
//
//*******************************************************************************    
function filterBusRoutes() {

// Debug variable (set to 1 to debug)
var debug = 0;

if (debug)
    alert("filterBusRoutes()");
    
        // return the path including query string 
        // for retrieving the filtered response
        return BusRoutesGridXmlResponsePath + "?"+ filterBusRoutesQueryString();
}// end function

//*******************************************************************************
// Function:     filterBusRoutesQueryString
// Author:       michael.chu@cgi.com
// Project:      iMove Build - 0.7
// Date:         Nov 09, 2006
//
// Description:  The following function returns the filtered bus routes path with
//               query string. 
//               This function depends on hardcoded dropdownlist ids to find
//               selected values.
//              
//               Only data within map boundaries and satisfaction of specified 
//               zoom level are shown.
//
// Parameters:   
// Returns:      Returns the filtered bus routes path with query string in order 
//               to retrieve XML response data.
// Calls:        
// Called By:    LoadMapData(), LoadGridData()
//
// Revision History:
//
//   Name        Date        Description
//  ------       ------      ------------------------------------------------
//
//*******************************************************************************    
function filterBusRoutesQueryString() {

// Debug variable (set to 1 to debug)
var debug = 0;

if (debug)
    alert("filterBusRoutesQueryString()");
    
        // Retrieve filter criteria selected text values
        var ddlBusRouteRegion = document.getElementById(BusRouteRegionSelectName);
        if (ddlBusRouteRegion != null)
            busRouteRegion = ddlBusRouteRegion.options[ddlBusRouteRegion.selectedIndex].text;
        else
            busRouteRegion = "All";
            
            // Criterion Type has been taken out of Business requirement.
            // Keep here for future reference
//        var ddlBusRouteType = document.getElementById(BusRouteTypeSelectName);
//        if (ddlBusRouteType != null)
//            busRouteType = ddlBusRouteType.options[ddlBusRouteType.selectedIndex].text;
//        else
//            busRouteType = "All";
            
        var ddlBusRouteExchange = document.getElementById(BusRouteExchangeSelectName);
        if (ddlBusRouteExchange != null)
            busRouteExchange = ddlBusRouteExchange.options[ddlBusRouteExchange.selectedIndex].text;
        else
            busRouteExchange = "All";
            
        // URL encode string
        busRouteRegion = URLEncode(busRouteRegion);
        busRouteExchange = URLEncode(busRouteExchange);
        
        // Criterion Type has been taken out of Business requirement.
        // Keep here for future reference
//        busRouteType = URLEncode(busRouteType);
        
            
        // Build individual query string
        regionQS = "";
        if (busRouteRegion != "All")
            regionQS = "region=" + busRouteRegion;

        exchangeQS = "";
        if (busRouteExchange != "All")
            exchangeQS = "exchange=" + busRouteExchange;
            
        // Criterion Type has been taken out of Business requirement.
        // Keep here for future reference
//        typeQS = "";
//        if (busRouteType != "All")
//            typeQS = "type=" + busRouteType;
            
        // Build query string
        queryString = "";

        if (regionQS != "")
        {
            if (queryString != "")
                queryString += "&" + regionQS;
            else
                queryString = regionQS;
        }
        if (exchangeQS != "")
        {
            if (queryString != "")
                queryString += "&" + exchangeQS;
            else
                queryString = exchangeQS;
        }
        
        // Criterion Type has been taken out of Business requirement.
        // Keep here for future reference
//        if (typeQS != "")
//        {
//            if (queryString != "")
//                queryString += "&" + typeQS;
//            else
//                queryString = typeQS;
//        }
        
        // Include filter for active bus routes
        var actives = GetActiveBusRoutesOnMap();
        if (actives != null)
        {
            if (queryString != null && queryString != "")
                queryString += "&" + actives;
            else
                queryString += actives;
        }

//        // Include filter for map boundaries and zoom level
//        if (queryString != null && queryString != "")
//            queryString += "&" + filterMapBoundariesAndZoomLevel();
//        else
//            queryString += filterMapBoundariesAndZoomLevel();
        busRouteRegion = null;
        busRouteExchange = null;
        // return the query string for retrieving the filtered response
        return queryString;
}// end function

//*******************************************************************************
// Function:     filterBusRoutesMap
// Author:       michael.chu@cgi.com
// Project:      iMove Build - 0.7
// Date:         Nov 09, 2006
//
// Description:  The following function returns the filtered bus routes path with
//               query string. 
//               This function depends on hardcoded dropdownlist ids to find
//               selected values.
//              
//               Only data within map boundaries and satisfaction of specified 
//               zoom level are shown.
//
// Parameters:   
// Returns:      Returns the filtered bus routes path with query string in order 
//               to retrieve XML response data.
// Calls:        
// Called By:    LoadMapData(), LoadGridData()
//
// Revision History:
//
//   Name        Date        Description
//  ------       ------      ------------------------------------------------
//
//*******************************************************************************    
function filterBusRoutesMap() {

// Debug variable (set to 1 to debug)
var debug = 0;

if (debug)
    alert("filterBusRoutesMap()");
            
        // return the path including query string 
        // for retrieving the filtered response
        return BusRoutesGridXmlResponsePath + "?"+ filterBusRoutesMapQueryString();
}// end function

//*******************************************************************************
// Function:     filterBusRoutesMapQueryString
// Author:       michael.chu@cgi.com
// Project:      iMove Build - 0.7
// Date:         Nov 09, 2006
//
// Description:  The following function returns the filtered bus routes path with
//               query string. 
//               This function depends on hardcoded dropdownlist ids to find
//               selected values.
//              
//               Only data within map boundaries and satisfaction of specified 
//               zoom level are shown.
//
// Parameters:   
// Returns:      Returns the filtered bus routes path with query string in order 
//               to retrieve XML response data.
// Calls:        
// Called By:    LoadMapData(), LoadGridData()
//
// Revision History:
//
//   Name        Date        Description
//  ------       ------      ------------------------------------------------
//
//*******************************************************************************    
function filterBusRoutesMapQueryString() {

// Debug variable (set to 1 to debug)
var debug = 0;

if (debug)
    alert("filterBusRoutesMapQueryString()");
    
        // Build query string
        var queryString = "";

        // Include filter for map boundaries and zoom level
        var actives = GetActiveBusRoutesOnMap();
        if (actives != null)
        {
            if (queryString != null && queryString != "")
                queryString += "&" + actives;
            else
                queryString += actives;
        }
        
        // Include filter for highlight bus routes
        var highlight = GetHighlightBusRoutesOnMap();
        if (highlight != null)
        {
            if (queryString != null && queryString != "")
                queryString += "&" + highlight;
            else
                queryString += highlight;
        }
        
        // Include filter for bus routes stops
        var routeStops = GetActiveBusRoutesStopsOnMap();
        if (routeStops != null)
        {
            if (queryString != null && queryString != "")
                queryString += "&" + routeStops;
            else
                queryString += routeStops;
        }

//        // Include filter for map boundaries and zoom level
//        if (queryString != null && queryString != "")
//            queryString += "&" + filterMapBoundariesAndZoomLevel();
//        else
//            queryString += filterMapBoundariesAndZoomLevel();
            
        // return the query string for retrieving the filtered response
        return queryString;
}// end function

//*******************************************************************************
// Function:     GetQSActiveBusRoutesOnMap
// Author:       michael.chu@cgi.com
// Project:      iMove Build - 0.8
// Date:         Nov 16, 2006
//
// Description:  The following function retrieves the query string for 
//               all the active bus routes
//               shown on map and returns a comma separated list of bus route ids.
//
// Parameters:   
// Returns:      Query string with a comma separated list of bus route ids.
// Calls:        
// Called By:    BusRoutes.aspx.cs
//
// Revision History:
//
//   Name        Date        Description
//  ------       ------      ------------------------------------------------
//
//*******************************************************************************    
function GetQSActiveBusRoutesOnMap() {

    var actives;
    
    actives = GetActiveBusRoutesOnMap();
		
    if (actives != null)
        return "&" + actives;
    else
        return "";
}

//*******************************************************************************
// Function:     GetActiveBusRoutesOnMap
// Author:       michael.chu@cgi.com
// Project:      iMove Build - 0.8
// Date:         Nov 16, 2006
//
// Description:  The following function retrieves all the active bus routes
//               shown on map and returns a comma separated list of bus route ids.
//
// Parameters:   
// Returns:      A comma separated list of bus route ids.
// Calls:        
// Called By:    
//
// Revision History:
//
//   Name        Date        Description
//  ------       ------      ------------------------------------------------
//
//*******************************************************************************    
function GetActiveBusRoutesOnMap() {

    var actives;
    
    //retrieve the appropriate cookie based on which map view you are working on
    if ( isFullScreenMap == true){
        //alert("fullscreen map = true, return FS cookie")
        actives = Get_Cookie( FSactiveBusRoutesCookieName );
        
    } else {
        //alert("fullscreen map = false, return reg cookie")
        actives = Get_Cookie( activeBusRoutesCookieName );        
    }
    
     //alert("inside actives, routes are:'" + actives + "'");
		
    if (actives != null)
        return "actives=" + actives;
    else
        return null;
}

//*******************************************************************************
// Function:     GetHighlightBusRoutesOnMap
// Author:       michael.chu@cgi.com
// Project:      iMove Build - 0.8
// Date:         Nov 16, 2006
//
// Description:  The following function retrieves all the highlight bus routes
//               shown on map and returns a comma separated list of bus route ids.
//
// Parameters:   
// Returns:      A comma separated list of bus route ids.
// Calls:        
// Called By:    
//
// Revision History:
//
//   Name        Date        Description
//  ------       ------      ------------------------------------------------
//
//*******************************************************************************    
function GetHighlightBusRoutesOnMap() {

    var highlight;

    if ( isFullScreenMap == true){
        highlight = Get_Cookie( FShighlightBusRouteCookieName );
    } else {
        highlight = Get_Cookie( highlightBusRouteCookieName );
    }
		
    if (highlight != null)
        return "highlight=" + highlight;
    else
        return null;
}

//*******************************************************************************
// Function:     GetActiveBusRoutesStopsOnMap
// Author:       michael.chu@cgi.com
// Project:      iMove Build - 2_0
// Date:         Jan 19, 2007
//
// Description:  The following function retrieves all the active bus routes with stops
//               shown on map and returns a comma separated list of bus route ids.
//
// Parameters:   
// Returns:      A comma separated list of bus route ids.
// Calls:        
// Called By:    
//
// Revision History:
//
//   Name        Date        Description
//  ------       ------      ------------------------------------------------
//
//*******************************************************************************    
function GetActiveBusRoutesStopsOnMap() {

    var actives;

    if ( isFullScreenMap == true){
        //alert("fullscreen map = true, return FS cookie")
        actives = Get_Cookie( FSactiveBusRoutesStopsCookieName );        
    } else {
        actives = Get_Cookie( activeBusRoutesStopsCookieName );
        //alert("fullscreen map = false, return reg cookie")
    }

    if (actives != null)
        return "activesStops=" + actives;
    else
        return null;
}

//*******************************************************************************
// Function:     LoadMapData
// Author:       michael.chu@cgi.com
// Project:      iMove Build - 0.1
// Date:         Sep 01, 2006
//
// Description:  The following function loads or reloads advisories and cameras 
//               layers on the map.
//               If map already consists of advisories and cameras data, 
//               it will remove data and overlays, and re-add the data and overlays
//               based any filtered criteria.
//
//               Remarks: One has to be careful when calling this function.
//               This function does asynchronous call to download XML data
//               to be used for the map layers. The call might not finish
//               for each download before executing the next line of code.
//               The LoadGridData function is usually called after this function.
//               Hence, as an example, code in LoadGridData will be executed,
//               before code in LoadMapData finishes.
//
// Parameters:   
// Returns:      
// Calls:        
// Called By:    First load or pan/zoom events or filter criteria change event
//
// Revision History:
//
//   Name        Date        Description
//  ------       ------      ------------------------------------------------
//  Michael Chu  Nov 8, 2006 Modifed function to toggle specific layers
//                           based on event types and camera types.
//*******************************************************************************    
function LoadMapData() {

// Debug variable (set to 1 to debug)
var debug = 0;

if (debug)	
    alert('LoadMapData');
        
        // Control map menu checkboxes and layers for events and cameras
        // based on event type and camera type filtered respectively.
        TurnOnOffCheckboxesAndLayersBasedOnEventType();
        TurnOnOffCheckboxesAndLayersBasedOnCameraType();


if (debugPerformance)
    PrintElapseTime("LoadMapData");
	
} // end function

//*******************************************************************************
// Function:     TurnOnOffCheckboxesAndLayersBasedOnEventType
// Author:       michael.chu@cgi.com
// Project:      iMove Build - 0.7
// Date:         Nov 7 2006
//
// Description:  This function will go through each event checkbox on map menu
//               and toggle on or off layer based on whether each checkbox is 
//               checked.
//
// Parameters:   
// Returns:
// Calls:        
// Called By:    
//
// Revision History:
//
//   Name        Date        Description
//  ------       ------      ------------------------------------------------
//
//*******************************************************************************
function TurnOnOffCheckboxesAndLayersBasedOnEventType(){

    // Retrieved filtered criteria query strings
    filteredAdvisoriesPath = filterAdvisories( false );

    // Depending what type of event is being filtered,
    // each checkbox and layer on the map will be turned on and off correspondingly.
    var cbx = document.getElementById( "chk_EV_CurInc" );
    if ( cbx.checked == true ) 
    {
        // Build type query string
        var filterPath = filteredAdvisoriesPath + "&type=Incident";
        
        // Toggle on checkbox and layer on map
        cbx.checked = true;
        toggleLayer( cbx , null, filterPath);
    }
    else
    {
        cbx.checked = false;
        toggleLayer( cbx );
    }
    
    cbx = document.getElementById( "chk_EV_CurCon" );
    if ( cbx.checked == true ) 
    {
        // Build type query string
        var filterPath = filteredAdvisoriesPath + "&type=Construction";
        
        // Toggle on checkbox and layer on map
        cbx.checked = true;
        toggleLayer( cbx , null, filterPath);
    }
    else
    {
        cbx.checked = false;
        toggleLayer( cbx );
    }
    
    cbx = document.getElementById( "chk_EV_CurEv" );
    if ( cbx.checked == true ) 
    {
        // Build type query string
        var filterPath = filteredAdvisoriesPath + "&type=Event";
        
        // Toggle on checkbox and layer on map
        cbx.checked = true;
        toggleLayer( cbx , null, filterPath);
    }
    else
    {
        cbx.checked = false;
        toggleLayer( cbx );
    }
    
    cbx = document.getElementById( "chk_EV_FutCon" );
    if ( cbx.checked == true ) 
    {
        // Build type query string
        var filterPath = filteredAdvisoriesPath + "&type=" + URLEncode("Future Construction");
        
        // Toggle on checkbox and layer on map
        cbx.checked = true;
        toggleLayer( cbx , null, filterPath);
    }
    else
    {
        cbx.checked = false;
        toggleLayer( cbx );
    }    
    
    cbx = document.getElementById( "chk_EV_FutEv" );
    if ( cbx.checked == true ) 
    {
        // Build type query string
        var filterPath = filteredAdvisoriesPath + "&type=" + URLEncode("Future Event");
        
        // Toggle on checkbox and layer on map
        cbx.checked = true;
        toggleLayer( cbx , null, filterPath);
    }
    else
    {
        cbx.checked = false;
        toggleLayer( cbx );
    }
    
    cbx = document.getElementById( "chk_EV_FutSrvc" );
    if ( cbx.checked == true ) 
    {
        // Build type query string
        var filterPath = filteredAdvisoriesPath + "&type=" + URLEncode("Future Service");
        
        // Toggle on checkbox and layer on map
        cbx.checked = true;
        toggleLayer( cbx , null, filterPath);
    }
    else
    {
        cbx.checked = false;
        toggleLayer( cbx );
    }
    cbx = null;
}

//*******************************************************************************
// Function:     TurnOnOffCheckboxesAndLayersBasedOnCameraType
// Author:       michael.chu@cgi.com
// Project:      iMove Build - 0.7
// Date:         Nov 7 2006
//
// Description:  Determines the type of event being filtered.
//               If it is All, then all checkboxes and layers of events will be 
//               turned on, otherwise, only the specific checkbox and layer will 
//               be turned on and all else off.
//
// Parameters:   
// Returns:
// Calls:        
// Called By:    
//
// Revision History:
//
//   Name        Date        Description
//  ------       ------      ------------------------------------------------
//
//*******************************************************************************
function TurnOnOffCheckboxesAndLayersBasedOnCameraType(){


    // Retrieved filtered criteria query strings
    filteredCamerasPath = filterCameras( false );

    // Depending what type of event is being filtered,
    // each checkbox and layer on the map will be turned on and off correspondingly.
    var cbx = document.getElementById( "chk_CAM_Border" );
    if ( cbx.checked == true ) 
    {
        // Build type query string
        var filterPath = filteredCamerasPath + "&type=" + URLEncode("Border");
        
        // Toggle on checkbox and layer on map
        cbx.checked = true;
        toggleLayer( cbx , null, filterPath);
    }
    else
    {
        cbx.checked = false;
        toggleLayer( cbx );
    }
    
    cbx = document.getElementById( "chk_CAM_TrafficInt" );
    if ( cbx.checked == true ) 
    {
        // Build type query string
        var filterPath = filteredCamerasPath + "&type=" + URLEncode("Intersection");
        
        // Toggle on checkbox and layer on map
        cbx.checked = true;
        toggleLayer( cbx , null, filterPath);
    }
    else
    {
        cbx.checked = false;
        toggleLayer( cbx );
    }
    
    cbx = document.getElementById( "chk_CAM_TrafficHigh" );
    if ( cbx.checked == true ) 
    {
        // Build type query string
        var filterPath = filteredCamerasPath + "&type=" + URLEncode("Highway");
        
        // Toggle on checkbox and layer on map
        cbx.checked = true;
        toggleLayer( cbx , null, filterPath);
    }
    else
    {
        cbx.checked = false;
        toggleLayer( cbx );
    }
    
    cbx = document.getElementById( "chk_CAM_Port" );
    if ( cbx.checked == true ) 
    {
        // Build type query string
        var filterPath = filteredCamerasPath + "&type=" + URLEncode("Port");
        
        // Toggle on checkbox and layer on map
        cbx.checked = true;
        toggleLayer( cbx , null, filterPath);
    }
    else
    {
        cbx.checked = false;
        toggleLayer( cbx );
    }
    cbx = null;
}

//*******************************************************************************
// Function:     TurnOffAllExistingBusRouteLayers
// Author:       michael.chu@cgi.com
// Project:      iMove Build - 0.8
// Date:         Nov 17 2006
//
// Description:  Turns off all existing bus route layers based on what is
//               stored in cookie.
//
// Parameters:   
// Returns:
// Calls:        
// Called By:    
//
// Revision History:
//
//   Name        Date        Description
//  ------       ------      ------------------------------------------------
//
//*******************************************************************************
function TurnOffAllExistingBusRouteLayers(){


    if (isFullScreenMap == true){

            // Retrieve the fullscreen active bus route cookie
            var FSactives = Get_Cookie( FSactiveBusRoutesCookieName );
            if (FSactives != null)
            {
                var partialCookieArr = FSactives.split( "," );
                for( var i=0; i<partialCookieArr.length; i++ ) 
                {
                    var FSrouteId = partialCookieArr[i];
                    if (FSrouteId != "")
                    {
                        // remove these overlays from the map
                        toggleGroup( "layer_TRA_Public_Marker_" + FSrouteId, false );
                        toggleGroup( "layer_TRA_Public_Polyline_" + FSrouteId, false );
                    }
                }
            }
               
    } else {

            // Retrieve active bus route cookie
            var actives = Get_Cookie( activeBusRoutesCookieName );
            if (actives != null)
            {
                var partialCookieArr = actives.split( "," );
                for( var i=0; i<partialCookieArr.length; i++ ) 
                {
                    var routeId = partialCookieArr[i];
                    if (routeId != "")
                    {
                        // remove these overlays from the map
                        toggleGroup( "layer_TRA_Public_Marker_" + routeId, false );
                        toggleGroup( "layer_TRA_Public_Polyline_" + routeId, false );
                    }
                }
            }
    }
    
    // Retrieve highlight bus route cookie
    var highlight = Get_Cookie( highlightBusRouteCookieName );
    
    if (highlight != null)
    {
        if (highlight != "")
        {
            // remove these overlays from the map
            toggleGroup( "layer_TRA_Highlight_Public_Polyline_" + highlight, false );
        }
    }
    
}



//*******************************************************************************
// Function:     SelectBusRoute
// Author:       michael.chu@cgi.com
// Project:      iMove Build - 0.8
// Date:         Nov 16, 2006
//
// Description:  The following function adds or removes the routeId 
//               from the map and grid based on
//               whether the checkbox is checked or not respectively.
//
// Parameters:   control - checkbox control used to toggle on/off bus route
//               routeId - id of the bus route
// Returns:      
// Calls:        
// Called By:    
//
// Revision History:
//
//   Name        Date        Description
//  ------       ------      ------------------------------------------------
//
//*******************************************************************************    
function SelectBusRoute(control, routeId) {

//alert("in select bus route, fullscreen :" +  isFullScreenMap );

// Debug variable (set to 1 to debug)
var debug = 0;

if (debug)
    PrintElapseTime("SelectBusRoute(): start select bus route");

    // set global variable so it will recenter map
    isRecenterBusRouteOnMap = true;

    // check box name 
    var checkBoxName = control.id;

	// store the indication of whether checkbox is checked.
    var checked = control.checked;
    
//     alert("checkBoxName is " + checkBoxName + " - checked is " + checked);
    
	// Figure out if we are selecting polylines or markers
	var indexPolyline = checkBoxName.indexOf('chk_TRA_Public_Polyline');
	var indexMarker = checkBoxName.indexOf('chk_TRA_Public_Marker');
	
	// Add or remove partial cookie value for selected polyline
	if (indexPolyline != -1){
	    
        //***BRIAN TO DO: ADD CODE FOR FULLSCREEN MAP ACTIVE ROUTES COOKIE HERE ***        
        if (isFullScreenMap == true){
            //add the route for the regular map
            AddOrRemovePartialCookieValue(FSactiveBusRoutesCookieName, routeId, checked);        
        } else {
            //add the route for the regular map
            AddOrRemovePartialCookieValue(activeBusRoutesCookieName, routeId, checked);
        }
	    
	 }   

    // Add or remove partial cookie value for selected polyline
	if (indexMarker != -1){

        if (isFullScreenMap == true){
            //add the route for the regular map
            AddOrRemovePartialCookieValue(FSactiveBusRoutesStopsCookieName, routeId, checked);
        } else {
            //add the route for the regular map
            AddOrRemovePartialCookieValue(activeBusRoutesStopsCookieName, routeId, checked);
        }

	 }   

if (debug)
    PrintElapseTime("SelectBusRoute(): start toggle bus route");
    
    toggleLayer( control, routeId);


if (debug)
    PrintElapseTime("SelectBusRoute(): end toggle bus route");
    
    // If the polyline is turned off, turn off highlight and markers layers
    // for the bus route as well
    if ((indexPolyline != -1) && (checked==false))
    {

        // Hide highlight bus route's map layer if bus route is toggled off
        var cbxHighlight = document.getElementById("chk_TRA_Highlight_Public_" + routeId);
        if (cbxHighlight != null)
        {
            if (cbxHighlight.checked == true)
            {
                cbxHighlight.checked = false; // uncheck checkbox so highlight layer can be removed
                toggleLayer(cbxHighlight, routeId); // remove highlight layer

                if (isFullScreenMap == true){
                    //add the route for the regular map
                    Delete_Cookie( FShighlightBusRouteCookieName, '/', '' ); // remove highlight bus route cookie
                } else {
                    //add the route for the regular map
                    Delete_Cookie( highlightBusRouteCookieName, '/', '' ); // remove highlight bus route cookie
                }

            }
        }
        
        // Hide highlight bus route's map layer if bus route is toggled off
        var cbxMarkers = document.getElementById("chk_TRA_Public_Marker_" + routeId);
        if (cbxMarkers != null)
        {
            if (cbxMarkers.checked == true)
            {
                cbxMarkers.checked = false; // uncheck checkbox so markers layer can be removed
                toggleLayer(cbxMarkers, routeId); // remove markers layer

        //***BRIAN TO DO: ADD CODE FOR FULLSCREEN MAP ACTIVE ROUTES COOKIE HERE ***
                if (isFullScreenMap == true){
                    //add the route for the regular map
                    AddOrRemovePartialCookieValue(FSactiveBusRoutesStopsCookieName, routeId, false); // remove active bus route stops cookie
                } else {
                    //add the route for the regular map
                    AddOrRemovePartialCookieValue(activeBusRoutesStopsCookieName, routeId, false); // remove active bus route stops cookie
                }

            }
        }
        cbxHighlight = null;
        cbxMarkers = null;
    }
    
if (debug)
    PrintElapseTime("SelectBusRoute(): start Load BusRoutesMap Grid");
    
    // After the cookie is stored, need to regenerate the second grid (active bus routes)
    
    showLoadingGrid();
    
         
    // Clear existing grid2 content    
    var divGridContent2 = document.getElementById(divGridContentName2);
    divGridContent2.innerHTML = "";

    // Retrieve highlight bus route cookie
    //var actRoutes = Get_Cookie( activeBusRoutesCookieName );
    //alert("act routes are:" + actRoutes );
    

//***BRIAN TO DO: ADD CODE FOR FULLSCREEN MAP ACTIVE ROUTES COOKIE HERE ***
    var filteredBusRoutesMap = filterBusRoutesMap();  
    //alert(filteredBusRoutesMap);         

//***BRIAN TO DO: ADD CODE FOR FULLSCREEN MAP ACTIVE ROUTES COOKIE HERE ***
//***BRIAN TO DO: ADD CODE FOR FULLSCREEN MAP ACTIVE ROUTES COOKIE HERE ***

    //this is the default
    var busRoutesTab = document.getElementById(BusRoutesTabId);        
    LoadGridContentBasedOnXMLData('BusRoutesMap', filteredBusRoutesMap, busRoutesTab);
    
if (debug)
    PrintElapseTime("SelectBusRoute(): end Load BusRoutesMap Grid");

if (debug)
    PrintElapseTime("SelectBusRoute() end select bus route");

    
        
    // Indeed there is a problem here since the checkbox on the grid 
    // might take longer to load on the grid so calling ToggleLayer on the control
    // might think that the checkbox does not exist yet. The solution is to do
    // a wait loop to wait for the control to come back and return as checked.

    // if checkbox is checked, add bus route to map after reloading grid
//    if (checked == true)
//    {
//        toggleLayer( control, routeId);// add bus route
//    
////        var cbxName = "chk_TRA_Public_" + routeId;
////        delayToggleBusRouteLayer(cbxName, routeId);
//        
////        var i = 100000;
////        var x = 0;
////        var cbxControl = document.getElementById(cbxName);
////        while (x < i && (cbxControl == null || cbxControl.checked == false))
////        {
////            cbxControl = document.getElementById(cbxName);
////            x++;
////        }
////        if (cbxControl == null || cbxControl.checked == false)
////            alert('There is a problem with turning on bus route '+routeId+' onto map');
////        toggleLayer( cbxControl, routeId);// add bus route
//    }
    busRoutesTab = null;
    divGridContent2 = null;
}


//*******************************************************************************
// Function:     ToggleBusRouteOnMap
// Author:       michael.chu@cgi.com
// Project:      iMove Build - 1.6
// Date:         Jan 10, 2007
//
// Description:  The following function adds the specified bus route
//               onto the map.
//
// Parameters:   routeId - id of the bus route
//               
// Returns:      
// Calls:        
// Called By:    
//
// Revision History:
//
//   Name        Date        Description
//  ------       ------      ------------------------------------------------
//
//*******************************************************************************    
function ToggleBusRouteOnMap(routeId) {

    // set check to true to toggle on bus route on map
    var checked = true;

    // Add or remove partial cookie value
    if (isFullScreenMap == true){
        
        //alert("fullscreen map, add cookie to FS active routes cookie");
        
        //add the route for the regular map
        AddOrRemovePartialCookieValue(FSactiveBusRoutesCookieName, routeId, checked);
    } else {
        
        //alert("regular map, add cookie to active routes cookie");
        
        //add the route for the regular map
        AddOrRemovePartialCookieValue(activeBusRoutesCookieName, routeId, checked);
    }

    // Create a checkbox control to simulate one on the UI
    if ( moz || op ) {
        //alert("firefox test 1");
        //create the control in Firefox
        var control = document.createElement('input');    
        control.setAttribute('type', 'checkbox');
        control.setAttribute('checked', 'checked');
        control.setAttribute('id', 'chk_TRA_Public_Polyline_' + routeId + '_Simulated');
    }
    else {
        //alert("IE");
       //create the control in IE
        var control = document.createElement("<input type='checkbox' id='chk_TRA_Public_Polyline_" + routeId + "_Simulated' checked='checked'>");
    }
    
    // Used to test if the checkbox exists
    var chk_TRA_P = document.getElementById('chk_TRA_Public_Polyline_' + routeId);
    
    // Check if the checkbox exists, if not, then append to document,
    // otherwise use the one on the document.
    if (chk_TRA_P == null){
        //alert("checkbox doesn't exist");
        var d = document.getElementById('contentPrint2');
        d.appendChild(control); 
        d = null;        
    } else {
        //alert("checkbox does exist");
        control = chk_TRA_P;
    }

//alert("Start toggle Bus Route on");
    
    // toggle on bus route layer on map
    toggleLayer(control, routeId);

//alert("finish toggle Bus Route on");

    // Used to test if the checkbox exists
    var chk_TRA_P_S = document.getElementById('chk_TRA_Public_Polyline_' + routeId + '_Simulated');

    // Remove simulated checkboxes if it exists
    if (chk_TRA_P_S != null){

        //alert("remove simulated checkbox here");

        var d = document.getElementById('contentPrint2');            
        d.removeChild(chk_TRA_P_S);
        //document.removeChild(chk_TRA_P_S);        
    }
    chk_TRA_P_S = null;
}

function removeElement(divNum) {
  var d = document.getElementById('myDiv');
  var olddiv = document.getElementById(divNum);
  d.removeChild(olddiv);
  d = null;
  olddiv = null;
}

//function delayToggleBusRouteLayer(cbxName, routeId){

//    var cbxControl = document.getElementById(cbxName);
//    
//    if (cbxControl == null || cbxControl.checked == false)
//        setTimeout('delayToggleBusRouteLayer(\"'+cbxName+'\",\"'+routeId+'\")',100);
//    else
//        toggleLayer( cbxControl, routeId);// add bus route
//}

//*******************************************************************************
// Function:     HighlightBusRoute
// Author:       michael.chu@cgi.com
// Project:      iMove Build - 0.8
// Date:         Nov 20, 2006
//
// Description:  The following function adds or removes the highlighted 
//               bus route based on
//               whether the checkbox is checked or not.
//
// Parameters:   
// Returns:      
// Calls:        
// Called By:    
//
// Revision History:
//
//   Name        Date        Description
//  ------       ------      ------------------------------------------------
//
//*******************************************************************************    
function HighlightBusRoute(control, routeId) {

    // store the indication of whether checkbox is checked.
    var checked = control.checked;
    
        // Add or remove highlight bus route cookie value
    if (checked == true){

        if (isFullScreenMap == true){
            //add the route for the regular map
            Set_Cookie( FShighlightBusRouteCookieName, routeId, 30, '/', '', '' );
        } else {
            //add the route for the regular map
            Set_Cookie( highlightBusRouteCookieName, routeId, 30, '/', '', '' );
        }

    } else {

        if (isFullScreenMap == true){
            //add the route for the regular map
            Delete_Cookie( FShighlightBusRouteCookieName, '/', '' );
        } else {
            //add the route for the regular map
            Delete_Cookie( highlightBusRouteCookieName, '/', '' );
        }
    }    

	
	// Uncheck other highlight check boxes if checked
	// Retrieve cookie value for all active bus routes which can be highlighted

    if (isFullScreenMap == true){
        //add the route for the regular map
        var activeBusRoutes = Get_Cookie( FSactiveBusRoutesCookieName );
    } else {
        //add the route for the regular map
        var activeBusRoutes = Get_Cookie( activeBusRoutesCookieName );
    }

    if (isFullScreenMap == true){
        //add the route for the regular map
        var highlightBusRoute = Get_Cookie( FShighlightBusRouteCookieName );
    } else {
        //add the route for the regular map
        var highlightBusRoute = Get_Cookie( highlightBusRouteCookieName );
    }


    // If cookie is not empty, then we need to check if the checkbox
    // needs to be unchecked for the previous highlight bus route
    // and also turn off map layer for highlight bus route.
    if (activeBusRoutes != null && highlightBusRoute != null)
    {
        var partialCookieArr = activeBusRoutes.split( "," );
        
        for( var i=0; i<partialCookieArr.length; i++ ) 
        {
            var rId = partialCookieArr[i];
            if (rId != "")
            {
                 var cbxControl = document.getElementById("chk_TRA_Highlight_Public_" + rId);
                 if ((cbxControl != null))
                 {
                                        
                    if ((cbxControl.checked == true) && (rId != highlightBusRoute))
                    {
                        cbxControl.checked = false;
                        toggleLayer( cbxControl, rId);
                    }
                 }
                 cbxControl = null;
            }
        }
    }
	
    // if checkbox is unchecked, remove highlight bus route from map
    toggleLayer( control, routeId);       
}

//*******************************************************************************
// Function:     SelectBusRouteStops
// Author:       michael.chu@cgi.com
// Project:      iMove Build - 2.0
// Date:         Jan 19, 2007
//
// Description:  The following function adds or removes the stops layer for the
//               bus route based on
//               whether the checkbox is checked or not.
//
// Parameters:   
// Returns:      
// Calls:        
// Called By:    
//
// Revision History:
//
//   Name        Date        Description
//  ------       ------      ------------------------------------------------
//
//*******************************************************************************    
function SelectBusRouteStops(control, routeId) {

    // store the indication of whether checkbox is checked.
    var checked = control.checked;

    // Add or remove active bus route stops cookie value
    if (isFullScreenMap == true){
        //add the route for the regular map
        AddOrRemovePartialCookieValue( FSactiveBusRoutesStopsCookieName, routeId, checked);
    } else {
        //add the route for the regular map
        AddOrRemovePartialCookieValue( activeBusRoutesStopsCookieName, routeId, checked);
    }
	
    // if checkbox is unchecked, remove highlight bus route from map
    toggleLayer( control, routeId);   
}


//*******************************************************************************
// Function:     LoadGridDataWhenNotPanAndZoom
// Author:       michael.chu@cgi.com
// Project:      iMove Build - 1.6
// Date:         Jan 10, 2007
//
// Description:  When the map is being panned or zoomed, or is centered,
//               it will call function PanAndZoomHandler, and thus, 
//               will call the following code.
//
//               LoadMapData();
//               LoadGridData();
//
//               However, since we don't want
//               the grid to reload each time for camera groups and bus routes, 
//               we have include a new paremeter to LoadGridData to tell it not
//               to reload each time the map is pan or zoom. Hence, here for those
//               two cases, we need to manually reload the grid in cases such as when
//               the user clicks on reset, or the map is being centered to a region.
//
// Parameters:   
// Returns:      
// Calls:        
// Called By:    
//
// Revision History:
//
//   Name        Date        Description
//  ------       ------      ------------------------------------------------
//
//*******************************************************************************              
function LoadGridDataWhenNotPanAndZoom()
{
    var tabSelectedId = GridTabSelected();
    if ( (tabSelectedId == CameraGroupsTabId) || (tabSelectedId == BusRoutesTabId) )
        LoadGridData(); // pass no parameter to indicate loading everytime
}



