﻿/// <reference path="jquery-1.2.6.js" />

var map = null;
var points = [];
var shapes = [];
var center = null;

function LoadMap(latitude, longitude, onMapLoaded) {
    map = new VEMap('theMap');
    options = new VEMapOptions();
    options.EnableBirdseye = false;

    // Makes the control bar less obtrusize.
    // map.SetDashboardSize(VEDashboardSize.Small);
    
    if (onMapLoaded != null)
        map.onLoadMap = onMapLoaded;

    if (latitude != null && longitude != null) {
        center = new VELatLong(latitude, longitude);
    }

    map.LoadMap(center, null, null, null, null, null, null, options);
   // 
    
}

function LoadPin(LL, name, description, icon) {
    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>");
    shape.SetCustomIcon(icon);
    if (description !== undefined) {
        shape.SetDescription("<p class=\"pinDetails\">" + 
        escape(description) + "</p>");
    }
    map.AddShape(shape);
    points.push(LL);
    shapes.push(shape);

}

function FindAddressOnMap(where) {
    var numberOfResults = 20;
    var setBestMapView = true;
    var showResults = true;

    map.Find("", where, null, null, null,
           numberOfResults, showResults, true, true,
           setBestMapView, callbackForLocation);
}

function callbackForLocation(layer, resultsArray, places,
            hasMore, VEErrorMessage) {
    
    clearMap();
    
    if (places == null) 
        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);
            
        LoadPin(LL, item.Name, description, "<img src='../../images/smtooth.gif'>");
    });
    

    //Make sure all pushpins are visible
    if (points.length > 1) {
        map.SetMapView(points);
    }

    //If we've found exactly one place, that's our address.
    if (points.length === 1) {
        $("#Latitude").val(points[0].Latitude);
        $("#Longitude").val(points[0].Longitude);
    }
}

function clearMap() {
    map.Clear();
    points = [];
    shapes = [];
}

function getDistance(p1, p2, miles) {
    p1.Latitude = latLonToRadians(p1.Latitude);
    p1.Longitude = latLonToRadians(p1.Longitude);

    p2.Latitude = latLonToRadians(p2.Latitude);
    p2.Longitude = latLonToRadians(p2.Longitude);

    var R = 6371; // earth's mean radius in km
    var dLat = p2.Latitude - p1.Latitude;
    var dLong = p2.Longitude - p1.Longitude;
    var a = Math.sin(dLat / 2) * Math.sin(dLat / 2) +
		Math.cos(p1.Latitude) * Math.cos(p2.Latitude) * Math.sin(dLong / 2) * Math.sin(dLong / 2);
    var c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));
    var disKm = R * c;
    var disMiles = disKm * 0.6214;

    return (miles ? disMiles : disKm);
}

//  convert lat/long in degrees to radians
function latLonToRadians(point) {
    return point * Math.PI / 180;
}


function OnGotRoute(route) {
    $("#directionsarea").empty();
    var toaddress = jQuery.trim($("#ModelLoc").val());
    var routeinfo = "<h4>Directions:</h4>";
    var steps = "";
    var len = route.Itinerary.Segments.length;
    for (var i = 0; i < len - 1; i++) {
        steps += "<li>";
        steps += (i+1) + ". " + route.Itinerary.Segments[i].Instruction + " --<i> (continue ";
        steps += route.Itinerary.Segments[i].Distance + " miles)</i></li><br />";
        }
    routeinfo += "<table border=0 cellpadding=20><tr><td>";
    routeinfo += steps;
    routeinfo += "<li><strong>Arrive at " + toaddress + "</strong></li>";
    routeinfo += "</td></tr></table><h4>Total distance: ";
    routeinfo += route.Itinerary.Distance + " ";
    routeinfo += route.Itinerary.DistanceUnit + "<br />Estimated time: ";
    routeinfo += route.Itinerary.Time + " ";
    routeinfo += "  </h4><a href='#' onclick=$('#directionsarea').empty()>^^ Hide directions</a>";
    $('#directionsarea').append(routeinfo);
}


function FindDentistsGivenLocation(where) {
    map.SetZoomLevel(7);
    map.Find("", where, null, null, null, null, null, false,
       null, null, callbackUpdateMapDentists);
}

function callbackUpdateMapDentists(layer, resultsArray, places, hasMore, VEErrorMessage) {
    $("#dentistList").empty();
    clearMap();
    var center = map.GetCenter();
    LoadPin(center, "Your location",
                        $("#Location").val(),
                        "<img src='../../images/x.gif'>");
    var cnt = 0;
    
    $.post("/search/searchbylocation", { latitude: center.Latitude,
        longitude: center.Longitude
    }, function(dentists) {
        $.each(dentists, function(i, dentist) {
            var LL = new VELatLong(dentist.Latitude, dentist.Longitude, 0, null);
            cnt++;
    
            // Add Pin to Map
            var linkhtml = '<a href="/' + dentist.City.replace(/ /g, '-') + '-dentist/' + dentist.Title.replace(/ /g, '-') + '">';
            
            LoadPin(LL, linkhtml + dentist.Title + '</a>',
                        dentist.Address + '<br />' + dentist.City + ', ' + dentist.State + '<br /><br /><strong>' + dentist.Phone + '</strong><br /><br />' + linkhtml + '<img src="../../images/' + dentist.Pic + '" width=200 border=0></a>',
                        "<img src='../../images/smtooth" + cnt + ".gif'>");

            //Add a dentist to the <ul> dentistList on the right
            var dist = getDistance(new VELatLong(center.Latitude, center.Longitude), new VELatLong(dentist.Latitude, dentist.Longitude), true);
            dist = Math.round(dist * 10) / 10;

            $('#dentistList').append('<div id="dentistItem"><li class="dentItem">' + linkhtml + '<strong>' + cnt + ". " + dentist.Title + '</strong><br />' + dentist.Address + "<br />" + dentist.City + ", " + dentist.State + "<br />" + dentist.Phone + "<br /><strong>Distance: " + dist + " miles</strong><br /></a></li></div><br />");

        });

        // Adjust zoom to display all the pins we just added.
        if (points.length > 1) {
            map.SetMapView(points);
        }

        // Display the event's pin-bubble on hover.
        $(".dentItem").each(function(i, dentist) {
            var j = i + 1;
            $(dentist).hover(
                function() { map.ShowInfoBox(shapes[j]); },
                function() { map.HideInfoBox(shapes[j]); }
            );
        });
    }, "json");
}

