﻿    /**
     * Global variables
     */
    var mapManager = null; // VEMap code
    var slocationName = null;
    var slocationPhone = null;
    var sEndAddress = null;
    var sEndStreetAddress = null;
    var sStartAddress = null;
    var sEndLat = null;
    var sEndLong = null;
    var centerMap = null;
    var zoomLevel = null;
    var Mode = null;
    var language = null;
    var searchString = null;
    var locID = null;
    var mapChanged = false;
    var width = null;
    var height = null;
    var deleteShapes = null;
    var directionRoute = null;   
    var zLevel = null;
    var typeSearch = null;
    var printButtonImg = null;
    var buttonBackPOIImg = null;
    var buttonBackSearchResultsImg = null;
    var zServiceProviderLevel = null;
    var zPointsOfInterestLevel = null;
    var zJumpPageLevel = null;
    var zDirectionPageLevel = null;
    var zDefaultZoomLevel = null;
    var sNoDirectionResultTitle = null;
    var sToken = null;
    
     /**
     * Adds map initialization to the onload event of the containing page
     *
     * @param onloadFunction - Function add to page load 
     */
    function addLoadEvent(onloadFunction) {
        var oldonload = window.onload;
        if (typeof window.onload != 'function')
            window.onload = onloadFunction;
        else {
            window.onload = function() {
                if (oldonload)
                    oldonload();
                onloadFunction();
            }
        }
    }
    
   /**
    * Building querystring
    */
    this.location.querystring = (function() {

    var queryStringDictionary = {};
    var querystring = decodeURI(location.search);

    if (!querystring) {
        return {};
    }

    querystring = querystring.substring(1);
    var pairs = querystring.split("&");

    for (var i = 0; i < pairs.length; i++) {
        var keyValuePair = pairs[i].split("=");
        queryStringDictionary[keyValuePair[0]] = keyValuePair[1];
    }

    queryStringDictionary.toString = function() {

        if (queryStringDictionary.length == 0) {
            return "";
        }

       var toString = ["?"];
        for (var key in queryStringDictionary) {
        toString.push(key + "=" +
        queryStringDictionary[key]);
        }
        toString = toString.join("");

        return toString;
    };

    // Return the key/value dictionary

    return queryStringDictionary;
    })();
    
    /**
     * Initiaize the map and get the right width and height
     */
    function InitializeMap()
    {
        Mode = location.querystring["Mode"].toUpperCase();
        language = location.querystring["Lang"].toUpperCase();
        height = location.querystring["Height"];
        searchString = location.querystring["Find"];
        locID = location.querystring["LocationId"];
        width = location.querystring["Width"];
        
         // set the width & height of outer div for the map control
        document.getElementById("divMap-container").style.width = width + "px";
        document.getElementById("divMap-container").style.height = height + "px";
        
        if (searchString != undefined || searchString != null)
            EnableImgLoading();
        
        if (typeSearch == "Locations" || typeSearch == undefined && Mode == "LOCFIND") //Mode != "LOCPOI" && Mode != "LOCDIR")
        {
            togglePanels();
            document.getElementById("divList").style.display = "none";
            document.getElementById("divMap-header").style.display = "block";
            document.getElementById("divPOI-header").style.display = "none";
            document.getElementById("divMap").style.height = "100%";
            document.getElementById("myMap").style.width = "100%";
            document.getElementById("myMap").style.height = "99%";
        }
        else if (typeSearch == "POI" || Mode != "LOCFIND") //Mode == "LOCPOI" || Mode == "LOCDIR" || Mode == "GEOJP")
        {
            EnableImgLoading();
            togglePanels();
            document.getElementById("divList").style.display = "none";
            document.getElementById("divMap-header").style.display = "none";
            document.getElementById("divPOI-header").style.display = "none";
            document.getElementById("divMap").style.height = "100%";
            document.getElementById("myMap").style.width = "100%";
            document.getElementById("myMap").style.height = "99%";
        }
        else
            DisableImgLoading();
        
    }
    
    /**
     * Sets the wireframes for the map
     */
    function SetWireFrames(mode)
    {
        switch (mode)
        {
            case "LOCFIND":
                if (searchString != undefined)
                {
                    EnableImgLoading();
                       
                                        
                    if (typeSearch == "Locations")
                    {  
                        ShowLocationResults();
                    }                        
                       DisableImgLoading();
                }
                else
                {
                    togglePanels();
                    document.getElementById("divList").style.display = "none";
                    document.getElementById("divMap-header").style.display = "block";
                    document.getElementById("divPOI-header").style.display = "none";
    	            document.getElementById("divMap").style.height = "100%";
    	            document.getElementById("myMap").style.width = "100%";
                    document.getElementById("myMap").style.height = "99%";
                }
                break;
            case "LOCPOI":
                //add legend control
                AddPOILegendControl();
                    
                // resizes the map
                var layoutHeight = height * .91 - 62;
                
                document.getElementById("myMap").style.width = "67%";
                document.getElementById("myMap").style.height = "99%";

                document.getElementById("points-of-interest").style.display = "block";
                document.getElementById("points-of-interest").style.height = layoutHeight + "px"; 
                document.getElementById("divPOI-header").style.display = "block";
                document.getElementById("divMap-header").style.display = "none";
                document.getElementById("divMap-header").style.visibility = "hidden";
                document.getElementById("location-names-container").style.display = "none";
                document.getElementById("divCity-container").style.display = "none";
                document.getElementById("results-layout").style.display = "none";
                
                DisableImgLoading();
                break;
            case "GEOJP":
            case "BUSJP":
                ShowGroupPagesResults();
                DisableImgLoading();
                break;
	        case "LOCDIR":
	            AddSingleLegendControl();
                togglePanels();
                //add legend control
                //AddLegendControl();
                document.getElementById("divPOI-header").style.display = "block";
                document.getElementById("divMap-header").style.display = "none";
                document.getElementById("divMap-header").style.visibility = "hidden";
                document.getElementById("myMap").style.width = "100%";
                document.getElementById("myMap").style.height = "99%";

                DisableImgLoading();                
	            break;
	        default:
              togglePanels();
              document.getElementById("divMap-header").style.display = "block";
              document.getElementById("divPOI-header").style.display = "none";
    	      document.getElementById("divMap").style.height = "100%";
    	      document.getElementById("myMap").style.width = "100%";
              document.getElementById("myMap").style.height = "99%";
        }
    }

    /**
     * Encapsulates and manages interaction with the Virtual Earth map
     */
    function MapManager() {
        this.Map = null;
        this.ShapeLayer = null;
        this.Shape = null;
        var that = this;
        var shapeLayer = null;
        this.TourSteps = null;
        this.StepCount = 0;
        this.StepDelay = 3000;
        var timer = null;

        /**
         * Loads the map control with default settings
         */
        this.GetMap = function() {
            // sets the correct width & height of the control
            //SetWireFrames();
            InitializeMap();

            var map = new VEMap('myMap');
            map.SetClientToken(sToken);
            map.LoadMap();
            shapeLayer = new VEShapeLayer();
            map.AddShapeLayer(shapeLayer);
            map.AttachEvent("onmouseover", this.OnMouseOver);
            map.AttachEvent("onclick", this.OnClick);
            map.AttachEvent("onchangeview", this.OnChangedView);
            this.Map = map;
            this.ShapeLayer = shapeLayer;
            this.Shape = shapeLayer.GetShapeByIndex(0);
        }
        
        /**
         * 
         */
        this.SetMapStyle = function(locationType) {
            if (mapManager != undefined)
            {   
                if (locationType == "Cemetery")
                    mapManager.Map.SetMapStyle(VEMapStyle.Aerial);
                else
                    mapManager.Map.SetMapStyle(VEMapStyle.Road);    
            }            
        }
           
        /**
         * Helper event handler to auto pop-up callout box for a shape
         *
        */ 
        this.OnChangedView = function(e) 
        {  
            if (Mode == "LOCDIR")
            {
                var varNumShapes = mapManager.ShapeLayer.GetShapeCount();
                if (varNumShapes == 1 && mapChanged == false)
                {
                    var shape = mapManager.ShapeLayer.GetShapeByIndex(0);
                    var pts = shape.GetPoints();
                    var latLong = new VELatLong(pts[0].Latitude,pts[0].Longitude);
                    mapManager.Map.SetCenterAndZoom(latLong,zLevel);
                    mapManager.Shape = shape;
                    setTimeout("mapManager.Map.ShowInfoBox(mapManager.Shape)",500);
                    mapChanged = true;
                }
            }
        }
                          
        /**
         * Helper event handler to show pop-ups for shapes without pushpins
         *
         * @param e - Event data
         */
        this.OnMouseOver = function(e) {
            if (e.elementID != null) {
                var shape = mapManager.Map.GetShapeByID(e.elementID);
                
                if (shape != null && shape.GetShapeType() != "Point" && shape.GetCustomIcon() == null && (shape.GetTitle() != null || shape.GetDescription() != null))
                    mapManager.Map.ShowInfoBox(shape);
            }
            return false;
        }
        
        /**
         * Helper event handler to center and zoom-in on shapes when clicked
         *
         * @param e - Event data
         */
        this.OnClick = function(e) 
        {
            if (e.elementID != null) 
            {                
                var shape = mapManager.Map.GetShapeByID(e.elementID);          
                var pts = shape.GetPoints();
                var latLong = new VELatLong(pts[0].Latitude,pts[0].Longitude);
                mapManager.Map.SetCenterAndZoom(latLong,zDefaultZoomLevel);
            }
        }
                                     
        /**
         * Adds a shape to the current shape layer
         *
         * @param shape - MapShape object to add to the map
         * @returns An array of VE LatLongs from the point(s) contained in the provided shape or null
         */
        this.AddShape = function(shape) {
            if (shape == null || shape.ShapeType == null || shape.Points == null || shape.Points.length < 1)
                return null;

            var veShape = null;
            var points = new Array();

            for (var i = 0; i < shape.Points.length; i++) {
                points.push(new VELatLong(shape.Points[i].Latitude, shape.Points[i].Longitude));
            }

            // determine the type of shape to add
            switch (shape.ShapeType) {
                case 'Point':
                    veShape = new VEShape(VEShapeType.Pushpin, points[0]);
                    break;
                case 'Polyline':
                    veShape = new VEShape(VEShapeType.Polyline, points);
                    if (shape.Icon == null)
                        veShape.HideIcon();
                    break;
                case 'Polygon':
                    veShape = new VEShape(VEShapeType.Polygon, points);
                    if (shape.Icon == null)
                        veShape.HideIcon();
                    break;
                default:
                    return null; //unknown type
            }

            // check/set the line color for polylines and polygons
            if (shape.LineColor != null) {
                var lineColor = new VEColor(shape.LineColor.R, shape.LineColor.G, shape.LineColor.B, shape.LineColor.A);
                veShape.SetLineColor(lineColor);
            }

            // check/set the fill color for polylines and polygons
            if (shape.FillColor != null) {
                var fillColor = new VEColor(shape.FillColor.R, shape.FillColor.G, shape.FillColor.B, shape.FillColor.A);
                veShape.SetFillColor(fillColor);
            }

            // check/set the icon URL for pushpins
            if (shape.Icon != null) {
                var iconSpec = new VECustomIconSpecification();

                // generate an absolute URL for 3D mode if a relative one was provided
                iconSpec.Image = document.location.href.substring(0, document.location.href.lastIndexOf('/') + 1) + shape.Icon;
                veShape.SetCustomIcon(iconSpec);
            }

            // check/set the popup title content for pushpins
            if (shape.Title != null)
                veShape.SetTitle(shape.Title);

            // check/set the popup description content for pushpins
            if (shape.Description != null)
                veShape.SetDescription(shape.Description);

            if (shape.MoreDescription != null)
                veShape.SetMoreInfoURL(shape.MoreDescription);

            // check/set the popup photo content for pushpins
            //            if (shape.Photo !=null)
            //                var photoURL = document.location.href.substring(0, document.location.href.lastIndexOf('/') + 1) + shape.Photo;
            //                veShape.SetPhotoURL(photoURL);

            shapeLayer.AddShape(veShape);
            return points;
        }

        /**
         * Clears the current shape layer and adds the provided shapes to it
         *
         * @param shapes - Array of MapShape objects to add to the map
         * @param changeView - Indicates whether or not to change the current map view to bound the added shapes
         */
        this.AddShapes = function(shapes, changeView) {

            var points = new Array();
            shapeLayer.DeleteAllShapes();

            if (shapes != null && shapes.length > 0) {
                for (var i = 0; i < shapes.length; i++) {

                    var shapePoints = this.AddShape(shapes[i]);

                    if (shapePoints != null && shapePoints.length > 0) {
                        for (var s = 0; s < shapePoints.length; s++) {
                            points.push(shapePoints[s]);
                        }
                    }
                }

                if (points.length > 0 && (changeView == null || changeView != false)) {
                    try {
                        this.Map.SetMapView(points);
                        if (zLevel != 0) {
                            this.Map.SetCenterAndZoom(points[0], zLevel);
                        }
                        //this.Map.SetZoomLevel(zLevel); 
                    }
                    catch (e) {
                        alert(e);
                    }
                }

            }
//            else {
//                //alert('No results were found.');
//            }

            //if (document.getElementById("divList").style.display != "block" && Mode == "LOCFIND")
            SetWireFrames(Mode);

            if (document.getElementById("imgLoading").style.display == "block")
                DisableImgLoading();
        }  
        
        /**
         * Generates textual driving directions from a provided route and populates a control with it
         *
         * @param route - Route calculated by Virtual Earth
         * @param locationName - Location name to go to
         * @param locationPhone - Location phone number
         * @param endAddress - Address line 1 of the location name
         * @parmm endAddress2 - Address line 2 (City, state, zip) of the location name
         * @param endLat - Latitude of the Location going to
         * @param endLong - Longitude of the Location going to
         * @param startAddress - address of where search address is starting from
         */
        this.GetDirections = function(locationName, locationPhone, endStartAddress, endAddress, startAddress)
        {
            if (startAddress == null || startAddress == undefined || startAddress == 'Address, City and State/Province') 
                return false;
            
            EnableImgLoading();
            
            slocationName = locationName;
            slocationPhone = locationPhone;
            sEndAddress = endAddress;
            sEndStreetAddress = endStartAddress;
            sStartAddress = startAddress;
            //sEndLat = endLat;
            //sEndLong = endLong;
            DignityMemorial.MapControl.MapControlServices.GetDirections(startAddress, endStartAddress + " " + endAddress, language,getRoute);
            DisableImgLoading();
        }

    }  
      
      
          
    /**
     * Gets the shape info
     *
     * @param e - ShapeID
     */   
    function getPushPin(e)
    {
        var varNumShapes = mapManager.ShapeLayer.GetShapeCount();
        for (var i = 0; i < varNumShapes; ++i)
        {
            if (i == e)
            {
                var shape = mapManager.ShapeLayer.GetShapeByIndex(i);
                mapManager.Map.HideInfoBox(shape);
                mapManager.Map.ShowInfoBox(shape);
                break;
                }
        }
//        if (e != null) {
//            //var shape = mapManager.Map.GetShapeByID(e);
//            var shape = mapManager.ShapeLayer.GetShapeByIndex(e);
//                //mapManager.Map.HideInfoBox(shape);
//                
//            //if (shape != null && shape.GetShapeType() != "Point" && shape.GetCustomIcon() == null && (shape.GetTitle() != null || shape.GetDescription() != null))
//                mapManager.Map.ShowInfoBox(shape);
//        }
    }
    
    /**
     * Hides the show box info (callback box)
     *
     * @param sTitle = title of the shape
     * @param mode = mode of the page
     */
    function hideCallBackBox(sTitle, mode)
    {
         var varNumShapes = mapManager.ShapeLayer.GetShapeCount();
         for (var i = 0; i < varNumShapes; ++i) 
         {
            var shape = mapManager.ShapeLayer.GetShapeByIndex(i); 
            var shapeTitle = shape.GetMoreInfoURL().trim();
             if (mode.toUpperCase() == "LOCFIND")
                if (shapeTitle.match(","))
                    shapeTitle = shapeTitle.substring(0, shapeTitle.indexOf(', '));
            //shapeTitle = shapeTitle.substring(shapeTitle.indexOf('</tr>') + 13, shapeTitle.lastIndexOf('</td>'));
            if (shapeTitle == sTitle.trim())
            {
                mapManager.Map.HideInfoBox(shape);
                break;
            }
         }
    }
    
    /**
    * Shows the show box info (callback box)
    *
    * @param sTitle = title of the shape
    */
    function showCallBackBox(sTitle, mode)
    {
        var varNumShapes = mapManager.ShapeLayer.GetShapeCount();
         for (var i = 0; i < varNumShapes; ++i) 
         {
            var shape = mapManager.ShapeLayer.GetShapeByIndex(i); 
            var shapeTitle = shape.GetMoreInfoURL().trim();
            if (mode == "" || mode.toUpperCase() == "LOCFIND")
            {
                if (shapeTitle.match(","))
                    shapeTitle = shapeTitle.substring(0, shapeTitle.indexOf(', '));   
            }             
            //shapeTitle = shapeTitle.substring(shapeTitle.indexOf('</tr>') + 13, shapeTitle.lastIndexOf('</td>'));
            if (shapeTitle == sTitle.trim())
            {
                mapManager.Map.HideInfoBox(shape);
                mapManager.Map.ShowInfoBox(shape);
                break;
            }                
         }
    }
    
     /**
     * Generates textual driving directions from a provided route and populates a control with it
     *
     * @param route - Route calculated by Virtual Earth
     */
    function getRoute(route)
    {
        Mode = location.querystring["Mode"].toUpperCase();

        var back_button_img = null;
        if (Mode == "LOCPOI")
            back_button_img = buttonBackPOIImg;  //"../Images/button_back_POI.gif";
        else
            back_button_img = buttonBackSearchResultsImg;  //"../Images/button_back_search_results.gif";

        if (route == null || route.Legs.length <= 0)
        {
            //build the div
            var div = '';
            div += "<table border='0'>";
            div += "<tr><th align=left valign =middle style=font-size:small;>";
            div += "<img style='vertical-align:middle; cursor:pointer;' src=" + back_button_img + " width=170px height=14px onclick='BackToResults(\"" + Mode + "\")'></th></tr>";
            div += "<tr><th align='left' class='location-text' style='font-weight:bold;'><label ID='lblNoDirectionResults' class='location-text'>" + sNoDirectionResultTitle + "</label></th></tr>";
            div += "<tr><td>&nbsp;<br /></td></tr>";
            div += "</table>";

            SetNoDirections(div);
            hideCallBackBox(slocationName, Mode);
            
            return;
        } 
        directionRoute = route;
        
        // draws out mult-point route 
        var options = new VERouteOptions;
        options.RouteColor = new VEColor(174,131,141,1);
        options.RouteWeight = 3;
        options.RouteCallback = SetRouteShapes;
       
        // gets the turn-by-turn directions
        var itinerary = '';
        var turns = 1;
        var turnNum = 0; // the turn #  
        var legs = route.Legs;
        var polyPts = new Array();
        
        //var sLat = segs[0].Directions[0].LatLong.Latitude;
        //var sLong = segs[0].Directions[0].LatLong.Longitude;

        var endAddress = sEndStreetAddress + " " + sEndAddress;
        sStartAddress = legs[0].Itinerary[0].CompassDirection
        itinerary += "<table width=93% cellpadding=0 cellspacing=0 border=0>";
        itinerary += "<tr><td align=left valign =middle style=font-size:small;>";
        itinerary += "<img style='vertical-align:middle; cursor:pointer;' src=" + back_button_img + " width=170px height=14px onclick='BackToResults(\"" + Mode + "\")'></td>";
        itinerary += "<td align=left valign =middle style=font-size:small;>";
        itinerary += "<img style='vertical-align:middle; cursor:pointer;' src=" + printButtonImg + " onclick='PassDirections(\"" + slocationName + "\", \"" + slocationPhone + "\", \"" + endAddress + "\", \"" + sStartAddress + "\");'>&nbsp;</td></tr></table>";
        //itinerary += "<hr size=0 width=100% style='color:#A8C7C1' />";
        itinerary += "<table class='directions-table'>";
        itinerary += "<tr><td width=4%><img style='vertical-align:middle; cursor:hand;' src='../Images/A_start_point.gif'></td>";
        itinerary += "<td width=50% align=left><span class='expand-header-text'>Start:</span><br/><span class='location-text'>" + sStartAddress + "</span></td><td width=4%></td></tr></table>";
        //itinerary += "<tr><td width=4%></td><td>" + sStartAddress + "</td></tr>";
        //itinerary += "<hr size=0 width=100% style='color:#A8C7C1' />";
        //itinerary += "<tr><td width=4%></td><td>" + slocationName + "</td></tr>";
        //itinerary += "<tr><td width=4%></td><td>" + sEndAddress + "</td></tr>";
        //itinerary += "<<tr><td width=4%></td><td>" + sEndAddress2 + "</td></tr>";
        itinerary += "<table width=93%>";
        itinerary += "<tr><tr><td width=4%></td><td width=50% class='expand-header-text'>" + route.Summary.Distance.toFixed(1) + " mi - about " + GetTime(route.Summary.TimeInSeconds) + "</td><td width=4%></td></tr>";
        itinerary += "<tr><td colspan=3><hr size=0 width=100%/></td></tr>";
        
         // Get intermediate legs
        for (var i = 0; i < legs.length; i++) {
            var directions = legs[i].Itinerary; 
                            
            // Unroll each intermediate leg
            var turn        = null;  // The itinerary leg
            var legDistance = null;  // The distance for this leg
            var legDuration = null;  // The duration for this leg
            var num = directions.length + 1; // number of turns
            for (var j = 0; j < directions.length; j++) {
                turnNum++;
                turn = directions[j].Text; 
                var pts = directions[j].Location;

                var latLong = new VELatLong(pts.Latitude, pts.Longitude);
                //alert(turnNum + ". " + latLong);
                
                polyPts.push(latLong);
                shape = new VEShape(VEShapeType.Pushpin,latLong);
                
                //adding in step name and route description
                shape.SetTitle("Step "+turnNum);
                shape.SetDescription(turn);
                var iconSpec = new VECustomIconSpecification();
                var image =null; //"images/" + turnNum + "_turn.gif";
                switch (directions[j].ManeuverType)
                {
                    case 2:
                        image = "images/A_start_point.gif"
                        break;
                    case 5:
                        image = "images/B_start_point.gif";
                        break;
                    default:
                        image = "images/" + turnNum + "_turn.gif";
                    
                };
                           
                var url = document.location.href.substring(0, document.location.href.lastIndexOf('/') + 1) + image;
                iconSpec.Image = url;
                shape.SetCustomIcon(iconSpec);
                mapManager.ShapeLayer.AddShape(shape);     
                
                itinerary += "<tr><td valign=top width=4% class='location-text'><b>" + turnNum + ".</b>\t</td>";
                itinerary += "<td valign=top width=50% class='location-text'>" + turn + "</td>";
                //itinerary += "<b>" + turnNum + ".</b>\t" + turn;
                
                legDistance = directions[j].Summary.Distance;
                legDuration = directions[j].Summary.TimeInSeconds;
                if(legDistance >= 0)
                {
                    // Round distances to 1/10ths
                    itinerary += "<td valign=top width=4% nowrap class='location-text'> (" + legDistance.toFixed(1) + " mi";
                    // Append time if found
                    if(turn.Time != null)
                    {
                       //itinerary += "; " + GetTime(turn.Time);
                    }
                    itinerary += ")</td></tr>";
                }
                itinerary += "<tr><td colspan=3><hr size=0 width=100%/></td></tr>"
            }
        }
            itinerary += "</table><table class='directions-table'>";
            itinerary += "<tr><td valign='top' width=4%><img style='vertical-align:middle; cursor:hand;' src='../Images/B_start_point.gif'></td>";
            itinerary += "<td width=50% align=left><span class='expand-header-text'>End:</span><br/>";
            itinerary += "<span class='location-text'>" + slocationName + "</span><br/>";
            itinerary += "<span class='location-text'>" + sEndStreetAddress + "</span><br/>";
            itinerary += "<span class='location-text'>" + sEndAddress + "</span><br/></td>";
            itinerary += "<td width=4%></td></tr></table>";

            // draws route line on map    
            mapManager.Map.GetDirections(polyPts,options);
            mapManager.Map.SetMapView(polyPts);

            // Sets the div with directions adds a custom control to the map
            SetDirections(itinerary)
    }
            
             
    function SetRouteShapes(route)
    {
       // Unroll route
        var legs = route.RouteLegs;
        // Leg is a VERouteLeg object
        var leg = null;

        // Get intermediate legs
        for(var i = 0; i < legs.length; i++)
        {
            // Get this leg so we don't have to derefernce multiple times
            leg = legs[i];
   
            for(var j = 0; j < leg.Itinerary.Items.length; j ++)
            {
                //Remove original route pushpins
                mapManager.Map.DeleteShape(leg.Itinerary.Items[j].Shape);
            }
        }
    }
    
    function DeleteRouteShapes(route)
    {
        if (route == null)
            return; 
            
        var legs = route.Legs;       
        var varNumShapes = mapManager.ShapeLayer.GetShapeCount();
         
        // Get intermediate legs
        for (var i = 0; i < legs.length; i++) 
        {
            var directions = legs[i].Itinerary; 
                            
            // Unroll each intermediate leg
            var turn = null;  // The itinerary leg
           
            //Remove route pushpins            
            for (var j = 0; j < directions.length; j++) 
            {
                for (var s = 0; s < varNumShapes; ++s) 
                {
                    turn = directions[j].Text; 
                    var shape = mapManager.ShapeLayer.GetShapeByIndex(s); 
                    var shapeTitle = shape.GetDescription().trim();
                    if (shapeTitle.trim() == turn.trim())
                    {
                        mapManager.Map.DeleteShape(shape);
                        break;
                    }                
                }
            }
        }
    }
    
    /**
    * Sets the div with directions adds a custom control to the map
    *
    * @param itinerary - html with all the turn by turn directions
    */
     function SetDirections(itinerary)
     {           
        var layoutHeight = height * .88 - 62;
        var t = document.getElementById("directions");
        t.style.display = "block";
        t.style.height = layoutHeight + "px";
        t.innerHTML = itinerary;
        document.getElementById("divCity-container").style.display = "none";
        document.getElementById("divList").style.display = "none";
        document.getElementById("points-of-interest").style.display = "none";
        document.getElementById("divNoDirectionResults").style.display = "none";
        // resizes the map
        document.getElementById("divMap").style.height = "80%";
        document.getElementById("myMap").style.width = "70%";
        document.getElementById("myMap").style.height = "99%";
    }

    /**
    * Sets the div with no directions adds a custom control to the map
    *
    * @param itinerary - 
    */
    function SetNoDirections(itinerary) {
        var layoutHeight = height * .88 - 62;
        var t = document.getElementById("divNoDirectionResults");
        t.style.display = "block";
        t.style.height = layoutHeight + "px";
        t.innerHTML = itinerary;
        document.getElementById("divCity-container").style.display = "none";
        document.getElementById("divList").style.display = "none";
        document.getElementById("points-of-interest").style.display = "none";
        // resizes the map
        document.getElementById("divMap").style.height = "80%";
        document.getElementById("myMap").style.width = "70%";
        document.getElementById("myMap").style.height = "99%";
    }
     
     
    function BackToResults(mode)
    {
        document.getElementById("directions").style.display = "none";
        document.getElementById("divNoDirectionResults").style.display = "none";
            
        if (mode == "LOCPOI")
        {
            document.getElementById("myMap").style.width = "67%";
            document.getElementById("myMap").style.height = "99%";
            document.getElementById("points-of-interest").style.display = "block";     
        } 
        else if (mode == "LOCDIR")
        {
            GetCenterAndZoom();
            document.getElementById("divMap").style.height = "100%";
    	    document.getElementById("myMap").style.width = "100%";
            document.getElementById("myMap").style.height = "99%";
            document.getElementById("divList").style.display = "none";
        }
        else
        {
            ShowLocationResults();
        }
            
            
        if (directionRoute != null)
            DeleteRouteShapes(directionRoute);
                
        mapManager.Map.DeleteRoute();
        mapManager.Map.SetCenter(centerMap);
        mapManager.Map.SetZoomLevel(zoomLevel);
    }
    
    function GetCenterAndZoom()
    {
        if (mapManager != null) {
            centerMap = mapManager.Map.GetCenter();
            zoomLevel = mapManager.Map.GetZoomLevel();
        }
    }
     
    /**
    * Clears out the route and directions on the map
    */
    function ClearRoute()
    {
        if (mapManager != undefined)
        {
            if (mapManager.Map != undefined)
            {
                mapManager.Map.DeleteRoute();
                SetDirections("");
            }
        }
    }
              
    /**
    * Adds the Legend of icons that are pin pointed 
    */
     function AddLegendControl()
     {
        var legend = document.getElementById("legend");                
        var poiLegend = document.getElementById("poiLegend");    
        var singleLegend = document.getElementById("singleLegend");

        //div.style.height = height;
        poiLegend.style.display = "none";    
        singleLegend.style.display = "none";    
        legend.style.left = "0px";
        //legend.style.width = "72%";
        //legend.style.height = "100%";
        legend.style.background = "transparent";
        legend.style.display = "block";                
     }
     
     /**
     *Adds the point of interest Legend of icons that are pin pointed 
     */
     function AddPOILegendControl()
     {
        var legend = document.getElementById("legend");                
        var poiLegend = document.getElementById("poiLegend");    
        var singleLegend = document.getElementById("singleLegend");
        
        //div.style.height = "800px";
        legend.style.display = "none";            
        singleLegend.style.display = "none";    
        poiLegend.style.left = "0px";
        poiLegend.style.width = "80%";
        poiLegend.style.height = "100%";
        poiLegend.style.background = "transparent";
        poiLegend.style.display = "block";
     }
     
       /**
     *Adds the single point Legend of icons that are pin pointed 
     */
     function AddSingleLegendControl()
     {
        var legend = document.getElementById("legend");                
        var poiLegend = document.getElementById("poiLegend");    
        var singleLegend = document.getElementById("singleLegend");
        
        legend.style.display = "none";            
        singleLegend.style.display = "none";            
        singleLegend.style.left = "0px";
        singleLegend.style.width = "80%";
        singleLegend.style.height = "100%";
        singleLegend.style.background = "transparent";
        singleLegend.style.display = "block";
     }

     // time is an integer representing seconds
     // returns a formatted string
     function GetTime(time)
     {
        if(time == null)
        {
           return("");
        }

        if(time > 60)
        {                                 // if time == 100
           var seconds = time % 60;       // seconds == 40
           var minutes = time - seconds;  // minutes == 60
           minutes     = minutes / 60;    // minutes == 1

           if(minutes > 60)
           {                                     // if minutes == 100
              var minLeft = minutes % 60;        // minLeft    == 40
              var hours   = minutes - minLeft;   // hours      == 60
              hours       = hours / 60;          // hours      == 1
              
              var txtHour = null;
              if (hours > 1)
                  txtHour = "hours";
              else
                  txtHour = "hour";
                
              return(hours + " " + txtHour + " " + minLeft + " mins");
              //return(hours + " hour(s), " + minLeft + " minute(s), " + seconds + " second(s)");
           }
           else
           {
                return(minutes + " mins");
              //return(minutes + " minutes, " + seconds + " seconds");
           }
        }
        else
        {
           return(time + " seconds");
        }
     }

/**
 * Represents a shape to be added to the map
 *
 * @param points - Array of geographic points
 * @param shapeType - Type of shape (Point, Line, Polygon)
 * @param lineColor - Outer line color
 * @param fillColor - Inner shape fill color
 * @param icon - Pushpin icon image URL
 * @param title - Popup title markup
 * @param description - Popup description markup
 */
function MapShape(points, shapeType, lineColor, fillColor, icon, title, description) {
    this.Points = points;
    this.ShapeType = shapeType;
    this.LineColor = lineColor;
    this.FillColor = fillColor;
    this.Icon = icon;
    this.Title = title;
    this.Description = description;
}
    
    /**
     * Clears all objects on map and sets the map back to it's default location
    */
    function ClearMap()
    {
//            ClearRoute();
//            mapManager.Map.DeleteAllShapes();
//            mapManager.Map.DeleteAllShapeLayers();
        mapManager.Map.Clear();
        //shapeLayer = new VEShapeLayer();
        //mapManager.Map.AddShapeLayer(shapeLayer);     
        
        searchPanel = document.getElementById("divCity-container");
        resultsPanel = document.getElementById("divList");
        directionPanel = document.getElementById("directions");
        legendPanel = document.getElementById("legend");
        
        if (searchPanel != undefined)
            searchPanel.style.display = "block";
            
        if (directionPanel != undefined)
            directionPanel.style.display = "none";
            
        if (resultsPanel != undefined)
            resultsPanel.style.display = "none";       
            
        if (legendPanel != undefined)
            legendPanel.style.display = "none";
    }
    
    
    /**
     * Resize the Map control
     * @param - the width of the map
     * @param - the height of the map
     */
    function resizeMap(width, height)
    {        
        if (mapManager != undefined)
            mapManager.Map.Resize(width,height);
    }
    
    /**
    * Deletes all shapes on the map
    */
    function DeleteAllShape()      
    {         
        if (mapManager != undefined)
            mapManager.Map.DeleteAllShapes();     
    }

    /**
     * sets the zoom level from the config
     
     */
    function SetZoomLevel(level)
    {
         //if (mapManager != undefined)
         //{
            //if (level != "")
            //{
                //mapManager.Map.SetZoomLevel(level);    
                zLevel = level;
            //}
         //}
        
    
    }    
    
     /**
     * sets the overall map zoom level from the config
     
     */
    function SetDefaultZoom(level)
    {
        zDefaultZoomLevel = level;
    
    }                
        
    /**
     * sets the direction page zoom level from the config
     
     */
    function SetDirectionPageZoom(level)
    {
        if (level == "")
            level = 12;
            
        zLevel = level;
    
    }          
    
    function SetPrintImage(image)
    {
        printButtonImg = image;
    }
    
    function SetBackPOIImage(image)
    {
        buttonBackPOIImg = image;
    }
    
    function SetBackSearchResults(image) {
        buttonBackSearchResultsImg = image;
    }

    function SetNoDirectionsResultTitle(title) 
    {
        sNoDirectionResultTitle = title;
    }
    
    function LocationString(value)
    {
        searchString = value;
    }
    
    function TypeOfSearch(value)
    {
        typeSearch = value;
    }

    function SetToken(value) {
        sToken = value
    }

/**
 * Initialize the map control
 */
    addLoadEvent(function() { if (mapManager == null) { mapManager = new MapManager(); mapManager.GetMap(); } });
