﻿    /**
     * 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;
    var routeTime = null;
    var routeDistance = null;
    var brand = 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();
    brand = location.querystring["Brand"].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 - 20 + "px";
}

    /**
     * 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
            InitializeMap();

            var map = new VEMap('myMap');
            map.LoadMap();
            shapeLayer = new VEShapeLayer();
            map.AddShapeLayer(shapeLayer);
            map.AttachEvent("onmouseover", this.OnMouseOver);
            //map.AttachEvent("onclick", this.OnClick);
            map.AttachEvent("onchangeview", this.OnChangedView);
            //map.Resize("935px", "560px");
            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);
                    }
                }

            }
            height = location.querystring["Height"];
            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 - 20 + "px";
            document.getElementById("divMap").style.height = "100%";
            //document.getElementById("divMap").style.width = "98%";
            resizeMap("630px", "560px");
            
//            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, toAddress, fromAddress, time, distance) {
            language = location.querystring["Lang"].toUpperCase();
            routeDistance = distance;
            routeTime = time;
            slocationName = locationName;
            slocationPhone = locationPhone;
            sEndAddress = fromAddress;
            sStartAddress = toAddress;
            DignityMemorial.MapControl.MapControlServices.GetDirections(toAddress, fromAddress, language, distance, time, getRoute);
        }

    }  
      
      
          
    /**
     * 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() == "RESULTS" || mode.toUpperCase() == "RESULTSNAME" || mode.toUpperCase() == "JUMPPAGE")
            {
                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;
            }                
         }
     }

     function mouseOverTitle(sTitle, mode, number) {
         brand = location.querystring["Brand"].toUpperCase();
         var varNumShapes = mapManager.ShapeLayer.GetShapeCount();
      for (var i = 0; i < varNumShapes; ++i) {
          var iconSpec = new VECustomIconSpecification();
          var shape = mapManager.ShapeLayer.GetShapeByIndex(i);
          var image = null;

          var strNumber = null;
          if (number < 10) {
              strNumber = "0" + number.toString();
          }
          else {
              strNumber = number.toString();
          }

          if (brand == "DMJ") {
              image = "../Brand_Lang/" + brand + "/images/" + brand + "_map_icon_" + strNumber + "_over.png";
          }
          else if (brand == "MP" || brand == "GHL") {
            image = "../Brand_Lang/" + brand + "/images/DM_over_" + number + ".png";
          }
          else {
              image = "../Brand_Lang/" + brand + "/images/" + brand + "_over_" + number + ".png";
          }
          
          var shapeTitle = shape.GetMoreInfoURL().trim();
          if (mode == "" || mode.toUpperCase() == "RESULTS" || mode.toUpperCase() == "RESULTSNAME" || mode.toUpperCase() == "JUMPPAGE") {
              if (shapeTitle.match(","))
                  shapeTitle = shapeTitle.substring(0, shapeTitle.indexOf(', '));
          }
          if (shapeTitle == sTitle.trim()) {
              iconSpec.Image = document.location.href.substring(0, document.location.href.lastIndexOf('/') + 1) + image;
              shape.SetCustomIcon(iconSpec);
              SetZIndex(shape, 100);
              //break;
          }
          else {
              SetZIndex(shape, -10);
          }
          
      }
  }

  function mouseOutTitle(sTitle, mode, number) {
      brand = location.querystring["Brand"].toUpperCase();
      var varNumShapes = mapManager.ShapeLayer.GetShapeCount();
      for (var i = 0; i < varNumShapes; ++i) {
          var iconSpec = new VECustomIconSpecification();
          var shape = mapManager.ShapeLayer.GetShapeByIndex(i);
          var image = null;
          
          var strNumber = null;
          if (number < 10) {
              strNumber = "0" + number.toString();
          }
          else {
              strNumber = number.toString();
          }

          if (brand == "DMJ") {
              image = "../Brand_Lang/" + brand + "/images/" + brand + "_map_icon_" + strNumber + "_off.png";
          }
          else if (brand == "MP" || brand == "GHL") {
              image = "../Brand_Lang/" + brand + "/images/DM_" + number + ".png";
          }
          else {
              image = "../Brand_Lang/" + brand + "/images/" + brand + "_" + number + ".png";
          }
          
          var shapeTitle = shape.GetMoreInfoURL().trim();
          if (mode == "" || mode.toUpperCase() == "RESULTS" || mode.toUpperCase() == "RESULTSNAME" || mode.toUpperCase() == "JUMPPAGE") {
              if (shapeTitle.match(","))
                  shapeTitle = shapeTitle.substring(0, shapeTitle.indexOf(', '));
          }
          if (shapeTitle == sTitle.trim()) {
              iconSpec.Image = document.location.href.substring(0, document.location.href.lastIndexOf('/') + 1) + image;
              shape.SetCustomIcon(iconSpec);
              SetZIndex(shape, 100);
              //break;
          }
          else {
              SetZIndex(shape, -10);
          }
      }

  }

  function SetZIndex(shape, delta) {
      // We could use shape.SetZIndex here, but it may create problems with onmouseout, so
      // we use a different approach, by directly setting the zIndex to the element.
      if (shape && shape.GetPrimitive) {
          var shapeElem = document.getElementById(shape.GetPrimitive(0).iid);
          if (shapeElem && shapeElem.style && shapeElem != null)
              shapeElem.style.zIndex = parseInt(shapeElem.style.zIndex) + delta;
      }
  }

     /**
     * 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();
        brand = location.querystring["Brand"].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);
            alert("The location entered cannot be found.");
            return false;
        } 
        directionRoute = route;
        
        // draws out mult-point route 
        var options = new VERouteOptions;
        //options.RouteColor = new VEColor(174, 131, 141, 1);
        if (brand == "FDA")
            options.RouteColor = new VEColor(0, 92, 171, 1);
        else
            options.RouteColor = new VEColor(0, 102, 68, 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 = sEndAddress;
        var labelDistance;

        if (routeDistance == "miles")
            labelDistance = "mi";
        else
            labelDistance = "km";

        var img_A = "../Brand_Lang/" + brand + "/images/A_start_point.png"
        var img_B = "../Brand_Lang/" + brand + "/images/B_start_point.png"
        
        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 + "\", \"" + routeTime + "\", \"" + routeDistance + "\");'>&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=" + img_A + "></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) + " " + labelDistance + " - 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 = img_A
                        break;
                    case 5:
                        image = img_B
                        break;
                    default:
                        image = "../Brand_Lang/" + brand + "/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);
                SetZIndex(shape, 100);
                
                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) + " " + labelDistance;
                    // 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=" + img_B + "></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 divProvider_container = document.getElementById("divProvider_container");
        var divDirections = document.getElementById("divDirections");
        var directionFrom = document.getElementById("txtDirectionsA");
        var directionTo = document.getElementById("txtDirectionsB");
        var radioDistance = document.getElementById("resultsControl_radiobuttonDistance");
        var radioTime = document.getElementById("resultsControl_radiobuttonTime");

        if (radioDistance == undefined || radioDistance == null)
            radioDistance = document.getElementById("jumpControl_radiobuttonDistance");

        if (radioTime == undefined || radioTime == null)
            radioTime = document.getElementById("jumpControl_radiobuttonTime");

        var rbDistance = radioDistance.getElementsByTagName("input");
        var rbTime = radioTime.getElementsByTagName("input");

        divDirections.style.display = "block";
        divDirections.innerHTML = itinerary;
        divProvider_container.style.display = "none";
        directionFrom.value = "";
        directionTo.value = "";
        rbDistance[0].checked = true;
        rbTime[0].checked = true;
    }

    /**
    * 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("divDirections").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 {
            ClearRoute();
            var divContainer = document.getElementById("divProvider_container");
            var divGetDirections = document.getElementById("divGetDirections");
            var divResults = document.getElementById("results-layout");
            var divPaging = document.getElementById("divPaging");

            divContainer.style.display = "block"
            divPaging.style.display = "block"
            divGetDirections.style.display = "none";
            divResults.style.height = "502px";
                        
            //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.DeleteRoute();
        //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 == null) {
            mapManager = new MapManager();
            mapManager.GetMap();
        }

        if (mapManager != undefined) {
            mapManager.Map.Resize(width, height);
            //document.getElementById("myMap").style.width = width + "px";
            //document.getElementById("myMap").style.height = height + "px";
            //document.getElementById("divProvider_container").style.width = "300px";
            
        }
    }
    
    /**
    * 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(); } });
