﻿/*
Copyright (c) 2009, SpatialPoint, LLC.
    
All rights reserved.
    
http://www.spatialpoint.com
*/

var map, mapDivElement;
var drivingDirectionsControlHTML = "";
var mapDivElementName = "map";

var distanceUnitsMiles = true;
var unitsOfTravel = "miles";

var mapLatitude;
var mapLongitude;
var mapZoom;
var pushpinName = "";
var pushpinDescription = "";

var pushpinSearchResults = [];

var siteSupportsDrivingDirections = true; // set to true if site/country supports driving directions.

var endLocation = null;
var routeToItemId = null;


var drivingDirectionsTitle = 'Driving Directions';
var getDrivingDirectionsTitle = 'Get Directions To';
var estimatedTimeTaken = 'Estimated Trip time:';
var drivingDirectionsPopupTitle = 'Get Driving Directions';
var defaultAddressText = 'Copy Address here';
var defaultSearchText = 'Address, Postal code...';
var driveToLinkButton = 'Drive';
var pleaseEnterStartLocation = 'Please enter a start location';
var noMatchStartAddress = 'There are no locations that match your search criteria, please refine your search or check spellings';

var drivingDirectionsSummary = '[Time] for [Distance] [DistanceUnits] of travel';
var drivingDirectionsJustSeconds = '[Seconds] seconds';
var drivingDirectionsJustMinutesAndSeconds = '[Minutes] minutes, [Seconds] seconds';
var drivingDirectionsJustHoursMinutesSeconds = '[Hours] hour(s), [Minutes] minute(s), [Seconds] second(s)';

var pushpinPageLocation = 'Location';
var pushpinPageHours = 'Hours';
var pushpinPageProducts = 'Products';
var pushpinPageGetDrivingDirections = 'Get Driving Directions';
var pushpinPageProductCarried = 'Product carried:';
var pushpinPageGenerateDrivingDirections = 'Go';

var roadMapStyle = '';
var roadMapStyleTooltip = '';
var roadMapStyleLinkWidth = '';

var aerialMapStyle = '';
var aerialMapStyleTooltip = '';
var aerialMapStyleLinkWidth = '';

var showLabels = '';
var showLabelsTooltip = '';
var hideLabelsTooltip = '';
var showLabelsLinkWidth = '';

var zoomOutToolTip = '';
var zoomInToolTip = '';

var panToolTip = '';
var showNavControl = '';
var hideNavControl = '';   

var panelPrioritySearchResultsId = '';
var disableBirdsEye = true;

var veToken = '';
var globalVersion = false;

function LoadMap() 
{
    try {

        TranslateMapControl();
    
        mapDivElement = document.getElementById(mapDivElementName);
        map = new VEMap(mapDivElementName);

        if (globalVersion) {
            if (veToken != null && veToken != '') {
                map.SetClientToken(veToken);
            }
        }

        // How many rings of tiles to "prefech" around the visible viewport.
        map.SetTileBuffer(0);

        var mapOptions = new VEMapOptions();

        if (disableBirdsEye) {
            mapOptions.EnableBirdseye = false;
        }
        
        if (mapLatitude != 0 && mapLongitude != 0) {
            // View port where to start.,
            map.LoadMap(new VELatLong(mapLatitude, mapLongitude), mapZoom, VEMapStyle.Road, false, VEMapMode.Mode2D, false, 0, mapOptions);
        }
        else {
            map.LoadMap(new VELatLong(mapLatitude, mapLongitude), 1, VEMapStyle.Road, false, VEMapMode.Mode2D, false, 0, mapOptions);
        }

        var pushpins = new Array();

        if (pushpinName != '') {
            lookupPushpin = new VEShape(VEShapeType.Pushpin, new VELatLong(mapLatitude, mapLongitude));

            lookupPushpin.SetTitle("<DIV class='pushpinLookup'>" + pushpinName + "</DIV>");
            lookupPushpin.SetCustomIcon("<img src='./graphics/arrow_green.gif'/>");

            map.AddShape(lookupPushpin);
            pushpins.push(lookupPushpin);
        }


        drivingDirectionsPopupControlHTMLInner = "";
        var pinid = 1;

        var layer = new VEShapeLayer();
        layer.SetTitle("Pushpin layer");
        layer.SetDescription("Pushpin layer");

        map.AddShapeLayer(layer);

        for (var i = 0; i < pushpinSearchResults.length; i++) {
            var pushpin = new VEShape(VEShapeType.Pushpin, new VELatLong(pushpinSearchResults[i]['latitude'], pushpinSearchResults[i]['longitude']));

            pushpin.SetCustomIcon('<div class="pushpin">' + pushpinSearchResults[i]['pinID'] + '</div>');
            //pushpin.SetTitle('<DIV style="text-align:left">' + pushpinSearchResults[i]['name'].replace("*QUOTE_SUBSTITUTION*", "'") + '</div>');

            drivingDirectionsPopupControlHTMLInner += '<li style=\'cursor:pointer;padding-bottom:0px;\' onmouseover=\'onMouseOverDriveTo(this);\' onmouseout=\'onMouseOutDriveTo(this);\' onclick=\'popUpOnClickLink("' + pushpinSearchResults[i]['name'].replace("*QUOTE_SUBSTITUTION*", "'") + '","' + pushpinSearchResults[i]['description'].replace("*QUOTE_SUBSTITUTION*", "'") + '","' + pushpinSearchResults[i]['comment'].replace("*QUOTE_SUBSTITUTION*", "'") + '","' + pushpinSearchResults[i]['telephone'] + '",' + pushpinSearchResults[i]['latitude'] + ',' + pushpinSearchResults[i]['longitude'] + ');\'>';
            drivingDirectionsPopupControlHTMLInner += '<div class=\'pushpin\'>' + pushpinSearchResults[i]['pinID'] + '</div>';
            drivingDirectionsPopupControlHTMLInner += '<p style=\'color:#1B5E8E\'>';
            drivingDirectionsPopupControlHTMLInner += '<strong>' + pushpinSearchResults[i]['name'].replace("*QUOTE_SUBSTITUTION*", "'") + '</strong>';

            drivingDirectionsPopupControlHTMLInner += '<span>' + pushpinSearchResults[i]['description'].replace("*QUOTE_SUBSTITUTION*", "'") + '</span>';
            drivingDirectionsPopupControlHTMLInner += '</p>';
            drivingDirectionsPopupControlHTMLInner += '<div style=\'cursor:default;height:5px\'>';
            drivingDirectionsPopupControlHTMLInner += '</div>';
            drivingDirectionsPopupControlHTMLInner += '</li>';

            var pushpinPopupDescription = '<div id="result_rollover_wrapper" class="result_rollover_wrapper">';
            pushpinPopupDescription += '<div id="result_rollover_opening" class="result_rollover_opening"><img id="result_rollover_opening_image" src="./images/dealer-locator/bg/rollover-opening.gif" /></div>';
            pushpinPopupDescription += '<div class="result_rollover">';

            pushpinPopupDescription += '<ul class="tabs">';

            secondTab = false;
            if (pushpinSearchResults[i]['hours'] != '') {
                secondTab = true;
            }


            if (secondTab) {
                pushpinPopupDescription += '<li><a href="#">' + pushpinPageLocation + '</a></li>';
            }
            else {
                pushpinPopupDescription += '<li><a style="width:260px !important" href="#">' + pushpinPageLocation + '</a></li>';
            }
            
            if (pushpinSearchResults[i]['hours'] != '') {
                pushpinPopupDescription += '<li><a href="#">' + pushpinPageHours + '</a></li>';
            }

            pushpinPopupDescription += '</ul>';

            pushpinPopupDescription += '<div id="panes" class="panes">';

            pushpinPopupDescription += '<div id="location_pane" class="location_pane">';
            pushpinPopupDescription += '<div class="header">';
            pushpinPopupDescription += '<h4>' + pushpinSearchResults[i]['name'].replace("*QUOTE_SUBSTITUTION*", "'") + '</h4>';
            pushpinPopupDescription += '<span class="distance">' + pushpinSearchResults[i]['distance'] + '</span>';
            pushpinPopupDescription += '</div>';
            pushpinPopupDescription += '<div class="address">';
            pushpinPopupDescription += '<p>' + pushpinSearchResults[i]['description'].replace("*QUOTE_SUBSTITUTION*", "'") + '</p>';
            pushpinPopupDescription += '<p>' + pushpinSearchResults[i]['telephone'].replace("*QUOTE_SUBSTITUTION*", "'") + '</p>';
            pushpinPopupDescription += '</div>';
            
            if (siteSupportsDrivingDirections) {
                pushpinPopupDescription += '<div class="directions_form">';
                pushpinPopupDescription += '<label>' + pushpinPageGetDrivingDirections + '</label>';
                pushpinPopupDescription += '<a href="" class="linkbutton" onclick="return driveTo(\'' + pushpinSearchResults[i]['name'] + '\',\'' + pushpinSearchResults[i]['description'] + '\',\'' + pushpinSearchResults[i]['comment'] + '\',\'' + pushpinSearchResults[i]['telephone'] + '\',' + pushpinSearchResults[i]['latitude'] + ',' + pushpinSearchResults[i]['longitude'] + ');">' + pushpinPageGenerateDrivingDirections + '</a>';
                pushpinPopupDescription += '<input id="routeToAddress" type="text" class="txt" />';
                pushpinPopupDescription += '</div>';
            }

            if (pushpinSearchResults[i]['products'] != '') {
                pushpinPopupDescription += '<div class="products">';
                pushpinPopupDescription += '<h4>' + pushpinPageProductCarried + '</h4>';
                var products = pushpinSearchResults[i]['products'].split('|');
                for (var product = 0; product < products.length; product++) {
                    var productValues = products[product].split(':');
                    pushpinPopupDescription += '<div style="float:left;margin-right:5px">';
                    pushpinPopupDescription += '<img src="./images/icons/' + productValues[1] + '" alt="' + productValues[0] + '"></img>';
                    pushpinPopupDescription += '</div>';
                }

                pushpinPopupDescription += '<div style="clear:both"></div>';
                
                /*
                pushpinPopupDescription += '<ul>';

                var products = pushpinSearchResults[i]['products'].split('|');
                for (var product = 0; product < products.length; product++) {
                    pushpinPopupDescription += '<li>' + products[product] + '</li>';
                }

                pushpinPopupDescription += '</ul>';
                */
                pushpinPopupDescription += '</div>';

            }

            pushpinPopupDescription += '</div>';
            pushpinPopupDescription += '<div id="hours_pane" class="hours_pane">';
            if (pushpinSearchResults[i]['hours'] != '') {

                       
                pushpinPopupDescription += '<div class="hours">';
                pushpinPopupDescription += '<h4>' + pushpinPageHours + '</h4>';
                pushpinPopupDescription += '<ul>';

                var hours = pushpinSearchResults[i]['hours'].split('|');
                for (var hour = 0; hour < hours.length; hour++) {
                    pushpinPopupDescription += '<li>' + hours[hour] + '</li>';
                }
                pushpinPopupDescription += '</ul>';
                pushpinPopupDescription += '</div>';
            }


            pushpinPopupDescription += '</div>';
            
            pushpinPopupDescription += '</div>'; // end <div class="panes">
            pushpinPopupDescription += '</div>'; // end <div class="result_rollover">
            pushpinPopupDescription += '</div>'; // end <div class="result_rollover_opening">
            pushpinPopupDescription += '</div>'; // end <div class="result_rollover_wrapper">            

            pushpin.SetDescription(pushpinPopupDescription);
            layer.AddShape(pushpin);

            pushpins.push(pushpin);
            pinid++;
        }
        drivingDirectionsControlHTML = '';

        drivingDirectionsControlHTML += '<table><tr><td>';
        drivingDirectionsControlHTML += '<div id=\'outer\' style=\'width:auto\'>';
        drivingDirectionsControlHTML += '<div id=\'columns\' class=\'mappage\'>';
        drivingDirectionsControlHTML += '<div id=\'leftcolumn\' class=\'withleftbar\'>';
        drivingDirectionsControlHTML += '<div id=\'leftbar\' style=\'float:none;width:160px;height:auto;padding:0px\'>';
        drivingDirectionsControlHTML += '<div id=\'leftbarTitle\' style=\'width:auto;font-size:10px\'>';
        drivingDirectionsControlHTML += getDrivingDirectionsTitle;
        drivingDirectionsControlHTML += '</div>';
        drivingDirectionsControlHTML += '<div style=\'clear:both\' id=\'routeToResults\'>';
        drivingDirectionsControlHTML += '<ul id=\'routeToResultsList\'>';
        drivingDirectionsControlHTML += drivingDirectionsPopupControlHTMLInner;
        drivingDirectionsControlHTML += '</div>';
        drivingDirectionsControlHTML += '</div>';
        drivingDirectionsControlHTML += '</div>';
        drivingDirectionsControlHTML += '</div>';
        drivingDirectionsControlHTML += '</div>';
        drivingDirectionsControlHTML += '</td></tr></table>';

        if (pushpins.length > 0) {
            map.SetMapView(pushpins);
        }

        map.AttachEvent("onmouseover", onMouseOver);
        //map.AttachEvent("onmouseout", onMouseOut);        
        map.ClearInfoBoxStyles();

        AdjustMapControlForLanguage();
    
    } catch (err) {
        alert(err);
    }
}

function TranslateMapControl() {

    if (roadMapStyle != '') {
        L_NavActionRoad_Text = roadMapStyle;
    }

    if (roadMapStyleTooltip != '') {
        L_NavActionRoadToolTip_Text = roadMapStyleTooltip;
    }



    if (aerialMapStyle != '') {
        L_NavActionAerial_Text = aerialMapStyle;
    }

    if (aerialMapStyleTooltip != '') {
        L_NavActionAerialToolTip_Text = aerialMapStyleTooltip;
    }

    if (showLabels != '') {
        L_NavActionLabels_Text = showLabels;
    }

    if (showLabelsTooltip != '') {
        L_NavActionShowLabels_Text = showLabelsTooltip;
    }
    
    if (hideLabelsTooltip != '') {
        L_NavActionHideLabels_Text = hideLabelsTooltip
    }
    

    if (hideNavControl != '') {
        L_NavActionHideToolTip_Text = hideNavControl;
    }
    
    if (showNavControl != '') {
        L_NavActionShowToolTip_Text = showNavControl;
    }

    
 
    if (zoomOutToolTip != '') {
        L_ZoomBarMinusToolTip_Text = zoomOutToolTip;
    }

    if (zoomInToolTip != '') {
        L_ZoomBarPlusToolTip_Text = zoomInToolTip;
    }

    if (panToolTip != '')
    {
        L_NavActionCompassPan_Text = panToolTip;
    }
}

function AdjustMapControlForLanguage(){
    if (roadMapStyleLinkWidth != '') {
        document.getElementById('MSVE_navAction_RoadMapStyle').style.width = roadMapStyleLinkWidth;
    }

    if (aerialMapStyleLinkWidth != '') {
        document.getElementById('MSVE_navAction_AerialMapStyle').style.width = aerialMapStyleLinkWidth;
    }

    if (showLabelsLinkWidth != '') {
        document.getElementById('MSVE_navAction_showLabels').style.width = showLabelsLinkWidth;
    }
}


function onMouseOut(e) {
    if (e.elementID) {

        return true;
    }
}

var moveToPin = null; 
function onMouseOver(e)
{
    if (e.elementID) {
        moveToPin = map.GetShapeByID(e.elementID);

        if (moveToPin.GetTitle().indexOf('pushpinLookup') == -1) {
            map.HideInfoBox();
            showInfoPopup();

            return true;
        }
    }
}

function showInfoPopup() {
    map.ShowInfoBox(moveToPin);

    setTimeout("setPopupTabs(moveToPin);", 150);
}

function gotoRegion(latitude, longitude, zoom) {
    map.SetCenterAndZoom(new VELatLong(latitude, longitude), zoom);
    return false;
}


function moveToPushpin(latitude, longitude, index) {

    if (map != null) {
    
        var pushpinLayer = map.GetShapeLayerByIndex(1);

        if (pushpinLayer != null) {
            moveToPin = pushpinLayer.GetShapeByIndex(index);

            map.SetCenter(new VELatLong(latitude, longitude));
            map.HideInfoBox();
            setTimeout("map.ShowInfoBox(moveToPin);setPopupTabs(moveToPin);", 500);
            
        }
    }
}

function endsWith(testString, endingString) {
    if (endingString.length > testString.length) return false;
    return testString.indexOf(endingString) == (testString.length - endingString.length);
}

function setPopupTabs(pin) {
    jQuery(function($) {
        // set up tabs in dealer locator rollover dialog
        $(function() {
            $("ul.tabs").tabs("div.panes > div");
        });
        $("#routeToAddress").Watermark(defaultAddressText);        
    });


    try
    {
        if (pin != null) {
            var pixel = map.LatLongToPixel(new VELatLong(pin.Latitude, pin.Longitude), map.GetZoomLevel());

            var beak = document.getElementById("result_rollover_opening");
            if (beak != null) {
                var popUpContainer = beak.parentNode.parentNode.parentNode.parentNode.parentNode.parentNode.parentNode.parentNode;

                var locationPane = document.getElementById("location_pane");
                var hoursPane = document.getElementById("hours_pane");

                if (locationPane.clientHeight > hoursPane.clientHeight) {
                    hoursPane.style.height = locationPane.clientHeight - 31 + 'px';
                }

                if (beak != null) {
                    beak.style.top = (mapDivElement.offsetTop + pixel.y - 18) + 'px';

                    var fiveStarDealersPanel = document.getElementById("five_star_dealers")
                    var fiveStarDealersPanelHeight = 0;
                    if (fiveStarDealersPanel != null) {
                        fiveStarDealersPanelHeight = fiveStarDealersPanel.clientHeight + 16;
                    }

                    if (/MSIE (\d+\.\d+);/.test(navigator.userAgent)) {
                        beak.style.top = (pixel.y - popUpContainer.offsetTop + 68 + fiveStarDealersPanelHeight) + 'px';
                    }
                    else {
                        beak.style.top = (pixel.y - popUpContainer.offsetTop + 45 + fiveStarDealersPanelHeight) + 'px';
                    }

                    if (endsWith(popUpContainer.className, 'rightBeak')) {
                        var beakImageElement = document.getElementById("result_rollover_opening_image");
                        beakImageElement.src = "./images/dealer-locator/bg/rollover-opening-right.gif"
                        popUpContainer.style.left = (popUpContainer.offsetLeft - 40) + 'px';
                        beak.style.left = '280px';
                    }
                    else {
                        beak.style.left = '0px';
                    }
                    beak.style.position = 'absolute';
                }
            }
        }
    } 
    catch (err) {
        alert(err);
    }
}

function driveTo(destination, addressLine, comment, phoneNumber, latitude, longitude) {
    var address = document.getElementById('routeToAddress').value;

    if (address != '' && address != defaultAddressText) {
        endLocation = new VELatLong(latitude, longitude);
        destinationName = destination.replace("*QUOTE_SUBSTITUTION*", "'"); ;
        destinationAddress = addressLine.replace("*QUOTE_SUBSTITUTION*", "'"); ;
        destinationPhoneNumber = phoneNumber.replace("*QUOTE_SUBSTITUTION*", "'"); ;
        destinationComment = comment.replace("*QUOTE_SUBSTITUTION*", "'"); ;

        map.Find(null, address, null, null, null, null, true, true, true, false, onDriveToGeocodeResponse)
    }

    return false;
}

function urlencode(str) {
    return escape(str).replace(/\+/g, '%2B').replace(/%20/g, '+').replace(/\*/g, '%2A').replace(/\//g, '%2F').replace(/@/g, '%40');
}

// make pop up window
function makewindow(url, name, wi, hi, scroll, resizable) {
    if (!scroll) {
        scroll = 0;
    }
    mywin = window.open(url, name, 'width=' + wi + ',height=' + hi + ',toolbar=0,location=0,directories=0,status=1,menubar=0,scrollbars=' + scroll + ',resizable=' + resizable);

}

function generateRoute(startLocation, endLocation) {

    var locations = new Array();
    locations.push(startLocation, endLocation);
    var options = new VERouteOptions;
    options.DrawRoute = true;
    options.SetBestMapView = true;
    if (globalVersion) {
        options.UseMWS = true;
    }
    // Call this function when map route is determined:
    options.RouteCallback = onShowJourneyDirections;

    if (distanceUnitsMiles) {
        options.DistanceUnit = VERouteDistanceUnit.Mile;
    }
    else {
        options.DistanceUnit = VERouteDistanceUnit.Kilometer;
    }
    map.GetDirections(locations, options);

}

function onDriveToGeocodeResponse(veShapeLayer, veFindResultArray, vePlaceArray, hasMore, veErrorMessage) {
    if (veErrorMessage != null) {
        alert(veErrorMessage);
    }
    else {
        if (vePlaceArray != null) {
            if (vePlaceArray.length == 0) {
                alert("Unable to find the location, please try again.");
            }
            else {


                try {
                    map.HideInfoBox();

                    var startLocation = new VELatLong(vePlaceArray[0].LatLong.Latitude, vePlaceArray[0].LatLong.Longitude);
                    generateRoute(startLocation, endLocation);
                }
                catch (ex) {
                    alert("The following exception has occurred: " + ex.name + ", " + ex.message);
                }
            }
        }
    }
}

function onGotRoute(route, routeDirectionsParentElement) {

    //var routeDirectionsParentElement = document.createElement('ul');
    //routeDirectionsParentElement.setAttribute('id', 'directionList');
    var len = route.RouteLegs[0].Itinerary.Items.length;

    routeMapView = new Array();

    for (var i = 0; i < len; i++) {
        if (i > 0) {
            var segmentParentElement = document.createElement('li');

            var segmentImageElement = document.createElement('img');
            var segmentDirectionsElement = document.createElement('div');
            var segmentImageElementParent = document.createElement('div');

            segmentImageElementParent.appendChild(segmentImageElement);
            segmentParentElement.appendChild(segmentImageElementParent);
            if (i == 1) {
                segmentImageElement.src = './graphics/route/mapicon_start.gif';
            }
            else if (i != (len - 1)) {
                segmentImageElement.src = './graphics/route/RedCircle' + (i - 1) + '.gif';
                var segmentPaddingImageElement = document.createElement('img');
                segmentPaddingImageElement.src = './graphics/clear.gif';
                segmentPaddingImageElement.style.width = "4px";
                segmentPaddingImageElement.style.height = "17px";
                segmentImageElementParent.appendChild(segmentPaddingImageElement);
            }
            else {
                segmentImageElement.src = './graphics/route/mapicon_end.gif';
            }

            //segmentImageElement.style.width = '25px';
            
            segmentImageElementParent.style.styleFloat = "left"; 
                         
            segmentParentElement.className = 'result';
            segmentDirectionsElement.className = 'result_title';
            segmentDirectionsElement.style.width = '235px';
  

            segmentParentElement.appendChild(segmentDirectionsElement);
            if (i % 2 == 0) {
                segmentDirectionsElement.style.backgroundColor = 'white';
            }
            else {
                segmentParentElement.style.backgroundColor = '#f0f0f0';
                segmentDirectionsElement.style.backgroundColor = '#f0f0f0';
            }

            routeDirectionsParentElement.appendChild(segmentParentElement);

            var steps = '';
            steps += trim(route.RouteLegs[0].Itinerary.Items[i].Text);
            if (route.RouteLegs[0].Itinerary.Items[i].Distance != null && route.RouteLegs[0].Itinerary.Items[i].Distance > 0) {
                steps += ' (';
                steps += route.RouteLegs[0].Itinerary.Items[i].Distance.toFixed(2) + ' ';
                steps += unitsOfTravel + ')<BR>\n';
            }

            if (i == (len - 1)) {
                steps += ' ' + destinationName.replace("*QUOTE_SUBSTITUTION*", "'") + ' ';

                steps += "<span style='margin-top:2px'>" + destinationAddress + "</span>";
                if (destinationComment != '') {
                    steps += "<span style='margin-top:2px'>" + destinationComment + "</span>";
                }
                steps += "<span style='margin-top:4px'>" + destinationPhoneNumber + "</span>";
            }

            segmentDirectionsElement.innerHTML = steps;
        }


        routeMapView[i] = new VELatLong(route.RouteLegs[0].Itinerary.Items[i].LatLong.Latitude, route.RouteLegs[0].Itinerary.Items[i].LatLong.Longitude);
    }

    return routeDirectionsParentElement;
}


function onGotRouteSummary(route) {
    var routeinfo = "";

    routeinfo += "<STRONG>" + estimatedTimeTaken + " </STRONG>";
    routeinfo += drivingDirectionsSummary.replace('[Time]', GetTime(route.RouteLegs[0].Time)).replace('[Distance]', route.RouteLegs[0].Distance.toFixed(2)).replace('[DistanceUnits]', unitsOfTravel);

    return routeinfo;
}

function onShowJourneyDirections(route) {
    if (route.RouteLegs.length > 0) {
        if (lookupPushpin != null) {
            map.DeleteShape(lookupPushpin);
            lookupPushpin = null;
        }
    
        var pushpinLayer = map.GetShapeLayerByIndex(1);

        if (pushpinLayer != null) {
            pushpinLayer.DeleteAllShapes(); 
        }
        
        map.SetDefaultInfoBoxStyles();
        HideControl('searchResults');
        HideControl(panelPrioritySearchResultsId);

        var routeDirectionsParentElement = document.getElementById("routeInstructions");

        routeDirectionsParentElement.innerText = '';
        onGotRoute(route, routeDirectionsParentElement);

        document.getElementById("routeResultsSummary").innerHTML = onGotRouteSummary(route);

        ShowControl('routeResults');
        ShowControl('routeInstructions');
        ShowControl('routeResultsSummary');
        ShowControl('routeResultsButtons');
    }
}

// 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

            return drivingDirectionsJustHoursMinutesSeconds.replace('[Hours]', hours).replace('[Seconds]', seconds).replace('[Minutes]', minLeft);
        }
        else {
            return drivingDirectionsJustMinutesAndSeconds.replace('[Seconds]', seconds).replace('[Minutes]', minutes);
        }
    }
    else {
        return (drivingDirectionsJustSeconds.replace('[Seconds]', time));
    }
}
function clearAddressText() {
    var address = document.getElementById("routeToAddress");
    if (address != null) {
        if (address.value == defaultAddressText) address.value = "";
    }
}

function isKeyPressed(evt, code) {
    // this function supports IE, Netscape, and FireFox
    evt = (evt) ? evt : (window.event) ? event : null;

    if (evt) {
        var charCode = (evt.charCode) ? evt.charCode :
			((evt.keyCode) ? evt.keyCode : ((evt.which) ? evt.which : 0));

        return (charCode == code);
    }

    return false;
}

function HideControl(controlId) {
    var control = document.getElementById(controlId);

    if (control != null) {
        control.style.display = 'none';
        control.style.visibility = 'hidden';
    }
}

function ShowControl(controlId) {
    var control = document.getElementById(controlId);

    if (control != null) {
        control.style.display = 'block';
        control.style.visibility = 'visible';
    }
}

function trim(str, chars) {
    return ltrim(rtrim(str, chars), chars);
}

function ltrim(str, chars) {
    chars = chars || "\\s";
    return str.replace(new RegExp("^[" + chars + "]+", "g"), "");
}

function rtrim(str, chars) {
    chars = chars || "\\s";
    return str.replace(new RegExp("[" + chars + "]+$", "g"), "");
}
