﻿var DefaultViewLatitude = 28.3235;
var DefaultViewLongitude = -83.496094;
var DefaultViewZoom = 7;
var LocationViewZoom = 11;
var FfbMatchMarkerIconImages = ["ffbmarkerA.png", "ffbmarkerB.png", "ffbmarkerC.png"];

var map;
var geocoder;
var offices;
var ffbDefaultMarkerIcon;
var divAgentList;

function InitializeDefaultMap() {
    InitializeMap("", []);
}

function InitializeMap(location, matchingOffices) {
    if (!GBrowserIsCompatible()) {
        return false;
    }
    divAgentList = document.getElementById("divAgentList");
    map = new GMap2(document.getElementById("divMap"));
    geocoder = new GClientGeocoder();
    ffbDefaultMarkerIcon = new GIcon(G_DEFAULT_ICON);
    ffbDefaultMarkerIcon.image = "ffbmarker.png";
    offices = GetOffices();
    if (location == "") {
        ShowSearchResultsByMatches(matchingOffices);
    } else {
        SearchForLocation(location);
    }
}

function UseDefaultMapView() {
    map.setCenter(new GLatLng(DefaultViewLatitude, DefaultViewLongitude), DefaultViewZoom);
    PlotMarkers();
}

function SearchForLocation(location) {
    geocoder.getLatLng(location, function(point) {
                                    if (!point) {
                                        UseDefaultMapView();
                                        alert(location + " not found");
                                    } else {
                                        if (IsWithinFloridaBounds(point)) {
                                            ShowSearchResultsByPoint(point);
                                        } else {
                                            if (location.length > 1 && location.substring(location.length - 2) != "FL") {
                                                SearchForLocation(location + " FL");
                                            } else {
                                                UseDefaultMapView();
                                                alert(location + " not found");
                                            }
                                        }
                                    }
                                 });
}

function IsWithinFloridaBounds(point) {
    return point.lat() >= 24.4 &&
           point.lat() <= 31.1 &&
           point.lng() >= -87.7 &&
           point.lng() <= -79.9;
}

function CreateOffice(office) {
    office.html = "<div><b>" + office.name + "</b>&nbsp;&nbsp;&nbsp;" +
                  office.phoneNumber + "<br /><div>" +
                  office.address1 + "</div><div>" +
                  office.address2 + "</div><div>" +
                  office.city + ", " + office.state + " " +
                  office.zipcode + "</div><a target=\"_blank\" " +
                  "href=\"http://maps.google.com/?daddr=" +
                  office.latitude.toString() + ", " +
                  office.longitude.toString() + " (" +
                  office.urlEncodedAddress + ")\">Get directions to this office</a>" +
                  "<p>Agents in this office:</p>" + office.htmlAgentList + "</div>";
    office.marker = CreateOfficeMarker(office, ffbDefaultMarkerIcon);
    return office;
}

function CreateOfficeMarker(office, markerIcon) {
    var officeLatLng = new GLatLng(office.latitude, office.longitude);
    var officeMarker = new GMarker(officeLatLng, { icon: markerIcon });
    GEvent.addListener(officeMarker, "click", function() {divAgentList.innerHTML = office.html;});
    return officeMarker;
}

function PlotMarkers() {
    map.setUIToDefault();
    map.disableScrollWheelZoom();
    for (var i = 0; i < offices.length; i++) {
        map.addOverlay(offices[i].marker);
    }
}

function ShowSearchResultsByPoint(point) {
    map.setCenter(point, LocationViewZoom);
    offices.sort(CompareOfficeDistanceToMapCenter);
    divAgentList.innerHTML = "";
    for (var i = 0; i < FfbMatchMarkerIconImages.length; i++) {
        var ffbMatchMarkerIcon = new GIcon(G_DEFAULT_ICON);
        ffbMatchMarkerIcon.image = FfbMatchMarkerIconImages[i];
        offices[i].marker = CreateOfficeMarker(offices[i], ffbMatchMarkerIcon);
        divAgentList.innerHTML = divAgentList.innerHTML + "<div><img src=\"" +
                                     FfbMatchMarkerIconImages[i] + "\" alt=\"Marker\" /></div>" +
                                     offices[i].html;
    }
    ZoomOutUntilVisible(offices[0].marker.getLatLng());
    PlotMarkers();
}

function ShowSearchResultsByMatches(matchingOffices) {
    var BestMatchIndices = new Array();
    var BestMatchMapBounds = new GLatLngBounds();
    var matchingOfficeIndex;
    var i;
    for (i = 0; i < FfbMatchMarkerIconImages.length && i < matchingOffices.length; i++) {
        matchingOfficeIndex = IndexOfOffice(matchingOffices[i].county, matchingOffices[i].branch);
        if (matchingOfficeIndex > -1) {
            BestMatchIndices.push(matchingOfficeIndex);
        }        
    }
    divAgentList.innerHTML = "";
    for (i = 0; i < BestMatchIndices.length; i++) {
        var ffbMatchMarkerIcon = new GIcon(G_DEFAULT_ICON);
        ffbMatchMarkerIcon.image = FfbMatchMarkerIconImages[i];
        offices[BestMatchIndices[i]].marker = CreateOfficeMarker(offices[BestMatchIndices[i]], ffbMatchMarkerIcon);
        BestMatchMapBounds.extend(offices[BestMatchIndices[i]].marker.getLatLng());
        divAgentList.innerHTML = divAgentList.innerHTML + "<div><img src=\"" +
                                 FfbMatchMarkerIconImages[i] + "\" alt=\"Marker\" /></div>" +
                                 offices[BestMatchIndices[i]].html;
    }
    if (BestMatchIndices.length > 0) {
        map.setCenter(BestMatchMapBounds.getCenter(), Math.min(map.getBoundsZoomLevel(BestMatchMapBounds), LocationViewZoom));
        PlotMarkers();
    } else {
        UseDefaultMapView()
    }
}

function ZoomOutUntilVisible(point) {
    var CurrentBounds = map.getBounds();
    while (!CurrentBounds.containsLatLng(point)) {
        map.zoomOut();
        CurrentBounds = map.getBounds();
    }
}

function IndexOfOffice(county, branch) {
    for (var i = 0; i < offices.length; i++) {
        if (offices[i].county == county && offices[i].branch == branch) {
            return i;
        }
    }
    return -1;
}

function CompareOfficeDistanceToMapCenter(office1, office2) {
    return map.getCenter().distanceFrom(office1.marker.getLatLng()) -
           map.getCenter().distanceFrom(office2.marker.getLatLng());

}
