﻿/*
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 = 'Enter Address Here!';
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 panelPrioritySearchResultsId = '';
var disableBirdsEye = true;

var veToken = '';

function LoadMap() 
{
    try 
    {
        mapDivElement = document.getElementById(mapDivElementName);
        map = new VEMap(mapDivElementName);

        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(pushpinName);
            lookupPushpin.SetCustomIcon("<img src='./graphics/arrow_green.gif'/>");

            map.AddShape(lookupPushpin);
            pushpins.push(lookupPushpin);
        }


        drivingDirectionsPopupControlHTMLInner = "";
        var pinid = 1;
        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>');

            var pushpinPopupDescription = '<DIV style="text-align:left">';
            pushpinPopupDescription += '<DIV style="margin-bottom:4px">' + pushpinSearchResults[i]['description'].replace("*QUOTE_SUBSTITUTION*", "'");

            if (pushpinSearchResults[i]['telephone'] != '') {
                pushpinPopupDescription += '<BR><BR>' + pushpinSearchResults[i]['telephone'];
            }

            pushpinPopupDescription += '</DIV>';
            pushpinPopupDescription += '<DIV>' + pushpinSearchResults[i]['comment'].replace("*QUOTE_SUBSTITUTION*", "'") + '</DIV>';
            if (siteSupportsDrivingDirections) {
                pushpinPopupDescription += '<DIV class="getDirectionsPopupContainer">';

                pushpinPopupDescription += '<P style="font-size:10px; color:#333333; padding-bottom:3px;">';
                pushpinPopupDescription += '<Label for="getDirections" class="getDirectionsLabel">' + drivingDirectionsPopupTitle + '</Label><BR>';
                pushpinPopupDescription += '<DIV style="float:left;">';
                pushpinPopupDescription += '<input id="routeToAddress" type="text" class="getDirectionsTextBox" onkeypress="if (isKeyPressed(event, 13)) driveTo(\'' + pushpinSearchResults[i]['name'] + '\',\'' + pushpinSearchResults[i]['description'].replace("*QUOTE_SUBSTITUTION*", "'") + '\',\'' + pushpinSearchResults[i]['comment'].replace("*QUOTE_SUBSTITUTION*", "'") + '\',\'' + pushpinSearchResults[i]['telephone'] + '\',' + pushpinSearchResults[i]['latitude'] + ',' + pushpinSearchResults[i]['longitude'] + ');" onclick="clearAddressText();" value="' + defaultAddressText + '" />';
                pushpinPopupDescription += '</DIV>';
                pushpinPopupDescription += '<DIV style="float:left;padding-top:2px;">';
                pushpinPopupDescription += '<span class="leftButton">';
                pushpinPopupDescription += '<span class="rightButton">';
                pushpinPopupDescription += '<input type="submit" name="driveToLinkButton" value="' + driveToLinkButton + '" id="driveToLinkButton" title="' + driveToLinkButton + '" class="middleButton" onclick="driveTo(\'' + pushpinSearchResults[i]['name'] + '\',\'' + pushpinSearchResults[i]['description'].replace("*QUOTE_SUBSTITUTION*", "'") + '\',\'' + pushpinSearchResults[i]['comment'].replace("*QUOTE_SUBSTITUTION*", "'") + '\',\'' + pushpinSearchResults[i]['telephone'] + '\',' + pushpinSearchResults[i]['latitude'] + ',' + pushpinSearchResults[i]['longitude'] + ');"/>';
                pushpinPopupDescription += '</span>';
                pushpinPopupDescription += '</span>';
                pushpinPopupDescription += '</DIV>';
                pushpinPopupDescription += '</DIV>';
                pushpinPopupDescription += '</DIV>';
            }
            pushpinPopupDescription += '</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>';

            pushpin.SetDescription(pushpinPopupDescription);
            map.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);
        }
             
        
    } catch (err) {
        alert(err);
    }
}

function moveToPushpin(latitude, longitude) {
    if (map != null) {
        map.SetCenter(new VELatLong(latitude, longitude));
    }
}

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;
        destinationAddress = addressLine;
        destinationPhoneNumber = phoneNumber;
        destinationComment = comment;

        map.Find(null, address, null, null, null, null, true, true, true, false, onDriveToGeocodeResponse)
    }
}

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) {

    if (lookupPushpin != null) {
        map.DeleteShape(lookupPushpin);
        lookupPushpin = null;
    }

    var locations = new Array();
    locations.push(startLocation, endLocation);
    var options = new VERouteOptions;
    options.DrawRoute = true;
    options.SetBestMapView = true;
    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) {

    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 segmentImageElementParent = document.createElement('div');
            segmentImageElementParent.className = 'routeSegmentImage';
            var segmentImageElement = document.createElement('img');
            var segmentDirectionsElement = document.createElement('p');
            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';
            }
            else {
                segmentImageElement.src = './graphics/route/mapicon_end.gif';
            }

            segmentImageElementParent.style.display = 'inline';

            segmentImageElement.style.display = 'inline';


            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 += GetTime(route.RouteLegs[0].Time) + " for " + route.RouteLegs[0].Distance.toFixed(2) + " " + unitsOfTravel + " of travel";

    return routeinfo;
}

function onShowJourneyDirections(route) {
    if (route.RouteLegs.length > 0) {
        HideControl('searchResults');
        HideControl(panelPrioritySearchResultsId);
        document.getElementById("routeInstructions").innerText = '';
        document.getElementById("routeInstructions").appendChild(onGotRoute(route));

        document.getElementById("routeResultsSummary").innerHTML = onGotRouteSummary(route);
        document.getElementById("leftbarTitle").innerHTML = drivingDirectionsTitle;
        ShowControl('routeResults');
        ShowControl('routeInstructions');
        ShowControl('routeResultsSummary');
    }
}

// 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 (hours + " hour(s), " + minLeft + " minute(s), " + seconds + " second(s)");
        }
        else {
            return (minutes + " minutes, " + seconds + " seconds");
        }
    }
    else {
        return (time + " seconds");
    }
}

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"), "");
}