﻿/*
Copyright (c) 2008, SpatialPoint, LLC.
    
All rights reserved.
    
http://www.spatialpoint.com
*/

var map, mapDivElement;
var mapDivElementName = "map";

var mapLatitude;
var mapLongitude;
var mapZoom;
var pushpinName = "";
var pushpinDescription = "";
var pushpinURL = "";

var pushpinSearchResults = [];

var siteSupportsDrivingDirections = false;
var distanceUnitsMiles = true;

var destinationName = '';
var destinationAddress = '';
var destinationPhoneNumber = '';
var destinationComment = '';

var unitsOfTravel = "miles";

// translations
var drivingDirectionsTitle = 'Driving Directions';
var getDrivingDirectionsTitle = 'Get Directions To';
var estimatedTimeTaken = 'Estimated Trip time:';
var drivingDirectionsPopupTitle = 'Get Directions';
var searchAddress = '';
var defaultAddressText = 'Enter Address Here!';
var driveToLinkButton = 'Go';
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 veChina = false;
var useLiveLocalChina = false;
var veControl = '';
var clickedLatLong = null;
var drivingDirectionsControlHTML = "";
var clickX = -1;
var clickY = -1;
var routeTopushpin;
var lookupPushpin;
var endLocation = null;
var routeToItemId = null;

function LoadMap() 
{
    try 
    {
        mapDivElement = document.getElementById(mapDivElementName);
        map = new VEMap(mapDivElementName);

        // How many rings of tiles to "prefech" around the visible viewport.
        map.SetTileBuffer(0);

        if (mapLatitude != 0 && mapLongitude != 0) {
            // View port where to start.,
            map.LoadMap(new VELatLong(mapLatitude, mapLongitude), mapZoom, VEMapStyle.Road, false, VEMapMode.Mode2D, false);
        }
        else {
            map.LoadMap(new VELatLong(mapLatitude, mapLongitude), 1, VEMapStyle.Road, false, VEMapMode.Mode2D, false);
        }
        if (distanceUnitsMiles) {
            map.SetScaleBarDistanceUnit(VEDistanceUnit.Miles);
        }
        else {
            map.SetScaleBarDistanceUnit(VEDistanceUnit.Kilometers);
        }

        var pushpins = new Array();

        if (pushpinName != '') 
        {
            lookupPushpin = new VEShape(VEShapeType.Pushpin, new VELatLong(mapLatitude, mapLongitude));

            lookupPushpin.SetTitle(pushpinName);
            lookupPushpin.SetDescription(pushpinDescription);
            lookupPushpin.SetCustomIcon("<img src='../../../images/arrow_green.gif'/>");
            //pushpin.SetMoreInfoURL(pushpinURL);
            map.AddShape(lookupPushpin);
            pushpins.push(lookupPushpin);
        }

        drivingDirectionsControlHTMLInner = "";
        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("*LCCQUOTE*", "'") + '</div>');

            var pushpinPopupDescription = '<DIV style="text-align:left">';
            pushpinPopupDescription += '<DIV style="margin-bottom:4px">' + pushpinSearchResults[i]['description'].replace("*LCCQUOTE*", "'");

            if (pushpinSearchResults[i]['telephone'] != '') {
                pushpinPopupDescription += '<BR><BR>' + pushpinSearchResults[i]['telephone'];
            }
            
            pushpinPopupDescription += '</DIV>';
            pushpinPopupDescription += '<DIV>' + pushpinSearchResults[i]['comment'].replace("*LCCQUOTE*", "'") + '</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("*LCCQUOTE*", "'") + '\',\'' + pushpinSearchResults[i]['comment'].replace("*LCCQUOTE*", "'") + '\',\'' + pushpinSearchResults[i]['telephone'] + '\',' + pushpinSearchResults[i]['latitude'] + ',' + pushpinSearchResults[i]['longitude'] + ');" onclick="clearAddressText();" value="' + searchAddress + '" />';
                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("*LCCQUOTE*", "'") + '\',\'' + pushpinSearchResults[i]['comment'].replace("*LCCQUOTE*", "'") + '\',\'' + pushpinSearchResults[i]['telephone'] + '\',' + pushpinSearchResults[i]['latitude'] + ',' + pushpinSearchResults[i]['longitude'] + ');"/>';
                pushpinPopupDescription += '</span>';
                pushpinPopupDescription += '</span>';
                pushpinPopupDescription += '</DIV>';
                pushpinPopupDescription += '</DIV>';
                pushpinPopupDescription += '</DIV>';
            }
            pushpinPopupDescription += '</div>';

            drivingDirectionsControlHTMLInner += '<li style=\'cursor:pointer;padding-bottom:0px;\' onmouseover=\'onMouseOverDriveTo(this);\' onmouseout=\'onMouseOutDriveTo(this);\' onclick=\'popUpOnClickLink("' + pushpinSearchResults[i]['name'].replace("*LCCQUOTE*", "'") + '","' + pushpinSearchResults[i]['description'].replace("*LCCQUOTE*", "'") + '","' + pushpinSearchResults[i]['comment'].replace("*LCCQUOTE*", "'") + '","' + pushpinSearchResults[i]['telephone'] + '",' + pushpinSearchResults[i]['latitude'] + ',' + pushpinSearchResults[i]['longitude'] + ');\'>';
            drivingDirectionsControlHTMLInner += '<div class=\'pushpin\'>' + pushpinSearchResults[i]['pinID'] + '</div>';
            drivingDirectionsControlHTMLInner += '<p style=\'color:#1B5E8E\'>';
            drivingDirectionsControlHTMLInner += '<strong>' + pushpinSearchResults[i]['name'].replace("*LCCQUOTE*", "'") + '</strong>';

            drivingDirectionsControlHTMLInner += '<span>' + pushpinSearchResults[i]['description'].replace("*LCCQUOTE*", "'") + '</span>';
            drivingDirectionsControlHTMLInner += '</p>';
            drivingDirectionsControlHTMLInner += '<div style=\'cursor:default;height:5px\'>';
            drivingDirectionsControlHTMLInner += '</div>';
            drivingDirectionsControlHTMLInner += '</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 += drivingDirectionsControlHTMLInner;
        drivingDirectionsControlHTML += '</div>';
        drivingDirectionsControlHTML += '</div>';
        drivingDirectionsControlHTML += '</div>';
        drivingDirectionsControlHTML += '</div>';         
        drivingDirectionsControlHTML += '</div>';               
        drivingDirectionsControlHTML += '</td></tr></table>';

        if (pushpins.length > 0) 
        {
            map.SetMapView(pushpins);
        }

        if (siteSupportsDrivingDirections) {
            map.AttachEvent("onmousedown", mouseDown);
            map.AttachEvent("onclick", mouseClick);            
            map.AttachEvent("onmousemove", mouseMouseMove);            
        }

    } catch (err) {

        alert(err);
    }
}

function onMouseOverDriveTo(control) {
    control.style.backgroundColor = '#F1F6FA';
}

function onMouseOutDriveTo(control) {
    control.style.backgroundColor = '';
}

function AddControlPanel(controlId, top, left, border, height, width, backgroundColor) {
    try {
        var el = document.createElement("div");

        el.id = controlId;
        el.style.top = top + "px";
        el.style.left = left + "px";
        el.style.border = border;
        //el.style.height = height + "px";
        el.style.height = 'auto';
        //el.style.width = width + "px";
        el.style.width = 'auto';
        el.style.backgroundColor = backgroundColor;

        el.onmouseleave = function() { onControlMouseLeave(el); }

        el.oncontextmenu = function() {return false;}                    

        try {
            map.AddControl(el);
        }
        catch (err) {
            return null;
        }

        return el;

        //addShim(el);

    } catch (err) {
        SetErrorMsg("AddControl error", err);
    }
}



function onControlMouseLeave(control) {
    DeleteRouteToPopup();
}

function addShim(el) {
    var shim = document.createElement("iframe");
    shim.id = "myShim";
    shim.frameBorder = "0";
    shim.style.position = "absolute";
    shim.style.zIndex = "1";
    shim.style.top = el.offsetTop;
    shim.style.left = el.offsetLeft;
    shim.width = el.offsetWidth;
    shim.height = el.offsetHeight;
    el.shimElement = shim;
    el.parentNode.insertBefore(shim, el);
}


function AddRouteToPopup(legend, height, width, mapX, mapY) {
    try {

        var border = '1px solid gray';
        var backgroundColor = 'white';

        var el = AddControlPanel('RouteToPopup', mapY, mapX, border, height, width, backgroundColor);
        el.innerHTML = legend;


        if (el.scrollHeight + mapY > mapDivElement.clientHeight) {
             el.style.top = (el.offsetTop - el.scrollHeight - 8) + 'px';
         }

         if (el.scrollWidth + mapX > mapDivElement.clientWidth) {
             el.style.left = (el.offsetLeft - el.scrollWidth -8) + 'px';
         }

    } catch (err) {
        alert("AddLegend error", err);
    }
}

function DeleteRouteToPopup() {
    var currentPopup = document.getElementById('RouteToPopup');
    if (currentPopup != null) {
        map.DeleteControl(currentPopup);
    }

    if (routeTopushpin != null) {
        map.DeleteShape(routeTopushpin);
    }

    routeTopushpin = null;
    currentPopup = null;

    clickX = -1;
    clickY = -1;
}

// if the 'DriveTo' popup is displayed then remove if the user moves the mouse back over the map
function mouseMouseMove(e) {
    if (clickX >= 0 && clickY >= 0) {
        if (Math.abs(clickX - e.mapX) > 15 || Math.abs(clickY - e.mapY) > 15) {
            DeleteRouteToPopup();
        }
    }
}

function mouseDown(e) {
    DeleteRouteToPopup();

    clickX = e.mapX;
    clickY = e.mapY;
}

function mouseClick(e) {


    if (clickX == e.mapX && clickY == e.mapY && e.rightMouseButton && document.getElementById('searchResults').style.visibility != 'hidden') {
        var height = 350;
        var width = 200;

        clickedLatLong = map.PixelToLatLong(new VEPixel(e.mapX, e.mapY));

        routeTopushpin = new VEShape(VEShapeType.Pushpin, clickedLatLong);

        routeTopushpin.SetTitle("");
        routeTopushpin.SetDescription("");
        routeTopushpin.SetCustomIcon("<img src='../../../images/red_dot.gif'/>");

        map.AddShape(routeTopushpin);

        AddRouteToPopup(drivingDirectionsControlHTML, height, width, e.mapX, e.mapY);
    }
    else {
        clickX = -1;
        clickY = -1;
    }
}

function popUpOnClickLink(destination, addressLine, comment, phoneNumber, latitude, longitude) {
    DeleteRouteToPopup();

    if (clickedLatLong != null) {
        var endLocation = new VELatLong(latitude, longitude);
        destinationName = destination;
        destinationAddress = addressLine;
        destinationPhoneNumber = phoneNumber;
        destinationComment = comment;
        if (veChina && useLiveLocalChina) {

            //popup the JourneyDirections page passing in all the required parameters

            var queryString = 'http://ditu.live.com/?rtp=pos.'
                  + clickedLatLong.Latitude + '_' + clickedLatLong.Longitude
                  + '~pos.' + endLocation.Latitude + '_' + endLocation.Longitude + '_' + urlencode(destinationName + ' ' + destinationAddress + ' ' + destinationPhoneNumber);

            makewindow(queryString, 'directions', '1024', '768', '1', '1');
        
        }
        else {
            generateRoute(clickedLatLong, endLocation);
        }
        clickedLatLong = null;
    }
}

function moveToPushpin(latitude, longitude) {
    if (map != null) {
        map.SetCenter(new VELatLong(latitude, longitude));
    }
}


function driveToSite(destination, addressLine, comment, phoneNumber, latitude, longitude, addressElement) 
{
    var address = document.getElementById(addressElement).value;

    if (address != '' && address != defaultAddressText) {

        if (veControl != '') {
            endLocation = new VELatLong(latitude, longitude);
            destinationName = destination;
            destinationAddress = addressLine;
            destinationPhoneNumber = phoneNumber;
            destinationComment = comment;

            if (veChina && useLiveLocalChina) {
                map.Find(null, address, null, null, null, null, true, true, true, false, onDriveToGeocodeResponseExternal)
            }
            else {
                map.Find(null, address, null, null, null, null, true, true, true, false, onDriveToGeocodeResponse)
            }
        }
        else {
            return false; // current just stop the driving directions
        }
    }
    else {
        alert(pleaseEnterStartLocation);
    }
    return false;
}

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;

        if (veChina && useLiveLocalChina) {
            map.Find(null, address, null, null, null, null, true, true, true, false, onDriveToGeocodeResponseExternal)
        }
        else {
            map.Find(null, address, null, null, null, null, true, true, true, false, onDriveToGeocodeResponse)
        }
    }
    else {
        alert(pleaseEnterStartLocation);
    }
}

function onDriveToGeocodeResponseExternal(veShapeLayer, veFindResultArray, vePlaceArray, hasMore, veErrorMessage) {
    if (veErrorMessage != null) {
        alert(veErrorMessage);
    }
    else {
        if (vePlaceArray != null) {
            if (vePlaceArray.length == 0) {
                alert(noMatchStartAddress);
            }
            else {
                map.HideInfoBox();

                var startLocation = new VELatLong(vePlaceArray[0].LatLong.Latitude, vePlaceArray[0].LatLong.Longitude);

                //popup the JourneyDirections page passing in all the required parameters

                //var queryString = 'http://ditu.live.com/?rtp=pos.'
                //      + vePlaceArray[0].LatLong.Latitude + '_' + vePlaceArray[0].LatLong.Longitude
                //      + '~pos.' + endLocation.Latitude + '_' + endLocation.Longitude;

                var queryString = 'http://ditu.live.com/?rtp=adr.'
                     + urlencode(vePlaceArray[0].Name)
                      + '~pos.' + endLocation.Latitude + '_' + endLocation.Longitude + '_' + urlencode(destinationName + ' ' + destinationAddress + ' ' + destinationPhoneNumber);                

                makewindow(queryString, 'directions', '1024', '768', '1', '1');
            }
        }
        else {
            alert(noMatchStartAddress);
        }
    }
}

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;
    }

    //alert(queryString);
    var locations = new Array();
    locations.push(startLocation, endLocation);
    var options = new VERouteOptions;
    options.DrawRoute = true;
    options.SetBestMapView = true;
    if (!veChina) {
        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 queryString = 'directions.html?'
                      + 'itemId=' + routeToItemId
                      + '&latitude=' + endLocation.Latitude
                      + '&longitude=' + endLocation.Longitude
                      + '&startName=' + vePlaceArray[0].Name.replace(', ', ',<BR>')
                      + '&startLatitude=' + vePlaceArray[0].LatLong.Latitude
                      + '&startLongitude=' + vePlaceArray[0].LatLong.Longitude;                    

                    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 = '../../../images/route/mapicon_start.gif';
            }
            else if (i != (len - 1)) {
                segmentImageElement.src = '../../../images/route/RedCircle' + (i - 1) + '.gif';
            }
            else {
                segmentImageElement.src = '../../../images/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("*LCCQUOTE*", "'");

                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');
        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");
    }
}