﻿/// <reference path="jquery-1.4.2.js" /> 
function MetabolicEffectMap() { }

MetabolicEffectMap.MapDivId = 'theMap';
MetabolicEffectMap._map = null;
MetabolicEffectMap._points = [];
MetabolicEffectMap._shapes = [];

//Load the map to the default location
MetabolicEffectMap.LoadMap = function(latitude, longitude, onMapLoaded) {
    MetabolicEffectMap._map = new VEMap(MetabolicEffectMap.MapDivId);

    var options = new VEMapOptions();

    options.EnableBirdseye = false

    // Makes the control bar less obtrusize.
    this._map.SetDashboardSize(VEDashboardSize.Small);

    if (onMapLoaded != null)
        MetabolicEffectMap._map.onLoadMap = onMapLoaded;

    if (latitude != null && longitude != null) {
        var center = new VELatLong(latitude, longitude);
    }

    MetabolicEffectMap._map.LoadMap(center, null, null, null, null, null, null, options);
}

//Clears the map and resets the arrays
MetabolicEffectMap.ClearMap = function() {
    MetabolicEffectMap._map.Clear();
    MetabolicEffectMap._points = [];
    MetabolicEffectMap._shapes = [];
}

//Builds a pin for a location and its hover balloon
MetabolicEffectMap.LoadPin = function(LL, name, description, locationID) {
    var shape = new VEShape(VEShapeType.Pushpin, LL);

    //Make a nice Pushpin shape with a title and description
    shape.SetTitle("<span class=\"pinTitle\"> " + escape(name) + "</span>");
    var descString = "";
    if (description !== undefined) {
        descString="<p class=\"pinDetails\">" + escape(description) + "</p>";
    }

    if (locationID !== undefined) {
        descString+="<p class=\"pinDetails\"><a href=\"../ShowClasses/" + escape(locationID) + "\">View Classes</a></p>";
    }
    
    shape.SetDescription(descString);
    MetabolicEffectMap._map.AddShape(shape);

    MetabolicEffectMap._points.push(LL);
    
    MetabolicEffectMap._shapes.push(shape);
}

//Finds 1 location on the map by calling back for info
MetabolicEffectMap.FindAddressOnMap = function(where) {
    var numberOfResults = 1;
    var setBestMapView = true;
    var showResults = true;
    var defaultDisambiguation = true;

    MetabolicEffectMap._map.Find("", where, null, null, null,
                         numberOfResults, showResults, true, defaultDisambiguation,
                         setBestMapView, MetabolicEffectMap._callbackForLocation);
}

//Assembles the pins and balloons. Resizes map to fit all results based on center.
MetabolicEffectMap._callbackForLocation = function(layer, resultsArray, places, hasMore, VEErrorMessage) {
    MetabolicEffectMap.ClearMap();

    if (places == null) {
        MetabolicEffectMap._map.ShowMessage(VEErrorMessage);
        return;
    }

    //Make a pushpin for each place we find
    $.each(places, function(i, item) {
        var description = "";
        if (item.Description !== undefined) {
            description = item.Description;
        }
        var LL = new VELatLong(item.LatLong.Latitude,
                        item.LatLong.Longitude);

        MetabolicEffectMap.LoadPin(LL, item.Name, description);
    });

    //Make sure all pushpins are visible
    if (MetabolicEffectMap._points.length > 1) {
        MetabolicEffectMap._map.SetMapView(MetabolicEffectMap._points);
    }

    //If we've found exactly one place, that's our address.
    if (MetabolicEffectMap._points.length === 1) {
        $(".txtLatitude").val(MetabolicEffectMap._points[0].Latitude);// Removed .toLocaleString(); because it was rounding to 2 decimal places
        $(".txtLongitude").val(MetabolicEffectMap._points[0].Longitude);
    }
}
//Find the center of the map based on search parm and call back for locations in range.
MetabolicEffectMap.FindLocationsGivenLocation = function(where) {
    MetabolicEffectMap._map.Find("", where, null, null, null, null, null, false,
                         null, null, MetabolicEffectMap._callbackUpdateMapLocations);
}
//Call back for locations in range.
MetabolicEffectMap._callbackUpdateMapLocations = function(layer, resultsArray, places, hasMore, VEErrorMessage) {
    var center = MetabolicEffectMap._map.GetCenter();
    $.ajax({
        type: "POST",
        contentType: "application/json; charset=utf-8",
        url: "/Callbacks/MetabolicEffectCallbacks.asmx/SearchByLocation",
        data: "{'latitude':'" + center.Latitude + "','longitude':'" + center.Longitude + "','distance': null}",
        dataType: "json",
        processData: "false",
        success: function(msg) {
            MetabolicEffectMap._renderLocations(msg);
        },
        error: AjaxFailed
    });
    //    NopCommerceStore.Callbacks.MetabolicEffectCallbacks.SearchByLocation(center.Latitude, center.Longitude, null, MetabolicEffectMap._renderLocations);
}

    function AjaxFailed(result) {
        alert(result.status + " " + result.statusText);
    }

    MetabolicEffectMap._renderLocations = function(meLocations) {
        $("#searchResults").empty();
        MetabolicEffectMap.ClearMap();
        $.each(meLocations, function(i, retArray) {
            //alert(retArray);
            if (retArray.length <= 2) {
                $('#searchResults').html('There are no locations in your area at this time.<br/><br/><a href="http://www.metaboliceffect.com/Category/6-workouts.aspx">Click here</a> to check out our video workouts and DVDs.');
            }
            else {
                var locationArray = $.parseJSON(retArray);
                $.each(locationArray, function(z, location) {
                    //alert(location.locationLat);
                    var LL = new VELatLong(location.locationLat, location.locationLong, 0, null);

                    // Add Pin to Map
                    MetabolicEffectMap.LoadPin(LL, _getLocationLinkHTML(location), _getLocationDescriptionHTML(location));
                    //Add a location to the <ul> on the right
                    $('#searchResults').append($('<li/>')
                        .attr("class", "classItem")
                        .append(_getLocationLinkHTML(location)));

                });
            }
        });

        // Adjust zoom to display all the pins we just added.
        if (MetabolicEffectMap._points.length > 1) {
            MetabolicEffectMap._map.SetMapView(MetabolicEffectMap._points);
        }

        // Display the location's pin-bubble on hover.
        $(".classItem").each(function(i, location) {
            $(location).hover(
            function() { MetabolicEffectMap._map.ShowInfoBox(MetabolicEffectMap._shapes[i]); },
            function() { MetabolicEffectMap._map.HideInfoBox(MetabolicEffectMap._shapes[i]); }
        );
        });

        //    function _getLocationDate(dinner, formatStr) {
        //        return '<strong>' + _dateDeserialize(dinner.EventDate).format(formatStr) + '</strong>';
        //    }

        //Build the HTML for the link in the DIV
        function _getLocationLinkHTML(location) {
            //alert(location.hasSchedule);
            if (location.hasSchedule) {
                return "<a href=\"LocationSchedule.aspx?lid=" + location.locationID + "\" >" + location.locationName + "</a>";
            }
            if (location.locationWebsite != null && location.locationWebsite != "") {
                return "<a target='_blank' href=\"" + location.locationWebsite + "\" >" + location.locationName + "</a>";
            }
            else {
                return "<a href=\"#\" >" + location.locationName + '</a>';
            }
            //\"/Me_Location/ShowClasses/" + escape(location.locationID) + 
        }

        //Build the HTML for inside the bubble.
        function _getLocationDescriptionHTML(location) {
            var descString = "<p class=\"pinDetails\">" + location.locationAddress + "<br/>" +
            location.locationCity + ", " + location.stateID + " " +
            location.locationZip + "<br/>" + location.locationPhone;
            if (location.locationAdditional != null)
                descString += "<br/>" + location.locationAdditional;
            descString += "</p><p class=\"pinDetails\">"
            if (location.locationWebsite != null) {
                descString += "<a href=\"" + location.locationWebsite + "\" target=\"_blank\">Website</a><br/><br/>";
            }
            if (location.hasSchedule) {
                descString += "<a href=\"LocationSchedule.aspx?lid=" + location.locationID + "\" >Click To View Schedule</a>";
            }
            else {
                descString += "<br/>Call for class times.";
            }            
            descString += "</p>";
            
            return descString;
        }

        function _dateDeserialize(dateStr) {
            return eval('new' + dateStr.replace(/\//g, ' '));
        }

        function OnMapClick(e) {
            map.RemovePushpin('targetpin');
            map.AddPushpin('targetpin', e.view.latlong.latitude, e.view.latlong.longitude, 14, 15,
            '<img src="target.gif" width="14 height="15"/>', 24);
        }
    }
