﻿/* VEMapping.js
 *
 * Deals with the Virtual Earth map.
 * In mavStoreLocatorResults.ascx there are javascript members of this object that get set.
 * This script uses that information to draw the map.
 */
 
VEMapping = (function(){
    /***************************/
    /***** private members *****/
    /***************************/
    
    var _clientIds = {
        map: 'VEMap',
        drivingDirections: 'routeDirections'
    };
    var map = null;
    var numberOfPins = 0;
    var useDefaultDisambiguation = true;
    
    return {
        /**************************/
        /***** public members *****/
        /**************************/
        
        init: function(){
            VEMapping.GetMap();
        },
        GetMap: function(){
            if(VEMapping.ShowMap == "true"){
                map = new VEMap(_clientIds.map);
                // the map must be loaded to call any other functions
                // load the map but do not display it
                map.LoadMap();
                map.HideDashboard();
                map.AttachEvent("onerror", VEMapping.VEMap_Error);
                
                map.ShowDisambiguationDialog(false);
                map.DisambiguationCallback = VEMapping.DisambiguationCallback;
                
                if (VEMapping.PlaceToFind != '') {
                    map.Find(null, //what
                                VEMapping.PlaceToFind, // where
                                null, // findType
                                null, // shapeLayer
                                null, // startIndex
                                null, // numberOfResults
                                true, // showResults
                                true, // createResults
                                useDefaultDisambiguation,// useDefaultDisambiguation
                                true, // setBaseMapView
                                VEMapping.MapLoaded // callback
                     );
                }
                else if (this.StartAddress != '' && this.EndAddress != '') 
                {
                    var options = new VERouteOptions;
                    // Otherwise what's the point?
                    options.DrawRoute = true;
                    
                    // Call this function when map route is determined:
                    options.RouteCallback = VEMapping.ShowTurns;
                    
                    // Show as miles
                    options.DistanceUnit = VERouteDistanceUnit.Mile;
                    
                    // Show the disambiguation dialog
                    options.ShowDisambiguation = useDefaultDisambiguation;
                    
                    map.GetDirections([this.StartAddress, this.EndAddress], options);
                }
                
                if(VEMapping.ListOfStores.length > 0){
                    VEMapping.ShowStorePins();
                }
            }
        },
        // Shows one pin for each store using the property VEMapping.ListOfStores
        // which is populated on the server side.
        ShowStorePins: function(){
            for(var counter = 0; counter < VEMapping.ListOfStores.length; counter++){
                var storeInfo = VEMapping.ListOfStores[counter];
                var extraInfo = storeInfo.Phone;
                if(storeInfo.Address1 != ''){
                    extraInfo += "<br/>" + storeInfo.Address1;
                }
                if(storeInfo.Address2 != ''){
                    extraInfo += "<br/>" + storeInfo.Address3;
                }
                if(storeInfo.Address3 != ''){
                    extraInfo += "<br/>" + storeInfo.Address3;
                }
                var pin = new VEPushpin(
                   numberOfPins, 
                   new VELatLong(storeInfo.Latitude, storeInfo.Longitude), 
                   null, 
                   storeInfo.Name, 
                   extraInfo
                   );
                map.AddPushpin(pin);
                
                numberOfPins++;
            }
        },
        MapLoaded: function(layer, resultsArray, places, hasMore, veErrorMessage){
            VEMapping.DisplayMap();
            map.SetZoomLevel(VEMapping.ZoomLevel);
            map.ClearInfoBoxStyles();
        },
        ShowTurns: function(route){
            // The route that is passed to this function inlcludes an arbitrary number of legs to the trip,
            // we expect and map only one
            var turns = '';
            turns += "<span id=\"routeTimeLabel\">Est. Time:</span> <span id=\"routeTimeData\"> " + VEMapping.GetTime(route.Time) + "</span><br/>";
            turns += "<span id=\"routeDistLabel\">Est. Distance:</span> <span id=\"routeDistData\">" + route.Distance.toFixed(1) + " miles</span>";
            turns += "<br/><br/>";
            
            // Unroll route and populate DIV
            var legs = route.RouteLegs;
            var leg = null;
            var turnNum = 0; // The turn #
            // 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]; // Leg is a VERouteLeg object
                
                // Unroll each intermediate leg
                var turn = null; // The itinerary leg
                var legDistance = null; // The distance for this leg
                for (var j = 0; j < leg.Itinerary.Items.length; j++) {
                    turnNum++;
                    
                    turn = leg.Itinerary.Items[j]; // turn is a VERouteItineraryItem object
                    turns += "<b>" + turnNum + "</b>\t" + turn.Text;
                    
                    legDistance = turn.Distance;
                    
                    // So we don't show 0.0 for the arrival
                    if (legDistance > 0) {
                        // Round distances to 1/10ths
                        turns += " (" + legDistance.toFixed(1) + " miles";
                        
                        // Append time if found
                        if (turn.Time != null) {
                            turns += "; " + VEMapping.GetTime(turn.Time);
                        }
                        
                        turns += ")<br/>";
                    }
                }
                
                document.getElementById(_clientIds.drivingDirections).innerHTML = turns;
                VEMapping.DisplayMap();
            }
        },
        // time is an integer representing seconds
        // returns a formatted string
        GetTime: function(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");
            }
        },
        DisposeMap: function(){
            if(map.Dispose != null)
            {
              map.Dispose();
            }
        },
        DisplayMap:function(){
            var VEMapElement = document.getElementById('VEMap');
            
            VEMapElement.style.visibility = 'visible';
        },
        VEMap_Error:function(MapEvent){
        },
        DisambiguationCallback: function(e)
        {
             var results="More than one location was retruned. Please select the location you were looking for:<br>";
             for (x=0; x<e.length; x++)
             {
                results+="<a href='javascript:map.FindLocation(\""+e[x].ID+"\");'>"+e[x].ID+"</a><br>";
             }
        }
    };
})();
