﻿// Map Object
var map = null;
// ClientGeocoder Object
var geocoder = null;
// Directions Object
var directions = null;
// LatLngBounds Object
var bounds = null;
// Address list iterator
var currentAddress = 0;
// Object for tracking the current marker
var currentMarker = null;
// Base Print Link
var printLink = "http://maps.google.com/maps?f=d&saddr=##STARTADDR##&daddr=##DESTADDR##&hl=en&pw=2";

function loadMap() {
    if (google.maps.BrowserIsCompatible()) {
        // Create a new map
        map = new google.maps.Map2(document.getElementById("map"));
        // Run the map configuration
        configureMap();
    }
    else {
        // Notify the user of unsupported configuration
        alert('Google Maps are unsupported on this configuration!');
    }
}

function configureMap() {
    // Add the large pan and zoom control
    map.addControl(new google.maps.LargeMapControl());
    // Add the bottom scale control
    map.addControl(new google.maps.ScaleControl());
    // Add the map type toggle control
    map.addControl(new google.maps.MapTypeControl());
    // Add the collapsible over control
    // map.addControl(new google.maps.OverviewMapControl());

    // Enable ability to scroll via mouse wheel
    map.enableScrollWheelZoom();
    // Enable ability to double click zoom
    map.enableDoubleClickZoom();
    // Enable "smooth" zoom control
    map.enableContinuousZoom();

    // Create the GeoCoding object for use on locations later in teh script
    geocoder = new google.maps.ClientGeocoder();
    // Create the bounds object to track markers
    bounds = new google.maps.LatLngBounds();
    // Create the directions object for driving directions
    directions = new google.maps.Directions(map, $("#directions").get(0));
    google.maps.Event.addListener(directions, "load", directionsLoaded);
    google.maps.Event.addListener(directions, "error", function() {
        if (directions.getStatus().code != 200) {
            alert('Unable to locate that address!');
        }
    });

    // SetCenter on teh map to fully initialize the map of overlays
    map.setCenter(new google.maps.LatLng(0, 0));

    // Begin loading addresses
    findLoc();
}

function findLoc() {
    // The location array is established in a separate script and is simply expected to be present
    if (locations != null && locations.length > 0) {
        // Starting from the first address (currentAddress), check for a lat/long.
        if (locations[currentAddress].latitude != "" && locations[currentAddress].longitude != "") {
            // If availalble, map that point.
            var point = new google.maps.LatLng(locations[currentAddress].latitude, locations[currentAddress].longitude);
            addLocation(point);
        } else {
            // If not, try to GeoCode it.
            geocoder.getLatLng(formatLocationAddress(locations[currentAddress]), addLocation);
        }        
    }
}

function addLocation(point) {
    // Evaluate to ensure a point exists
    if (!point) {
        alert(formatLocationAddress(locations[currentAddress]) + " not found");
    } else {
        // Extend our bounds to keep track of the new marker
        bounds.extend(point);
        // Create a marker to show this location
        var marker = new google.maps.Marker(point);
        // Bind the infoWindow
        var desc = formatLocationTooltip(locations[currentAddress]);
        google.maps.Event.addListener(marker, "click", function() {
            marker.openInfoWindowHtml(desc);
            currentMarker = marker;
        });
        // Add the marker as an overlay
        map.addOverlay(marker);
    }
    // Increment the address
    currentAddress += 1;
    // If there are more
    if (currentAddress < locations.length) {
        // Find the next one
        findLoc();
    }
    else {
        // Set the zoom and center
        layoutMap();
        // Remove the loading screen
        $("#mapLoading").css("display", "none");
    }
}

function layoutMap() {
    map.setCenter(bounds.getCenter());
    map.setZoom(map.getBoundsZoomLevel(bounds) - 4);
}

// Helper function to format the address for geocoding
function formatLocationAddress(location) {
    return location.address1 + ", " + location.city + ", " + location.state + " " + location.zip
}

// Helper function to format the address for tooltip display
function formatLocationTooltip(location) {
    var desc = document.createElement('div');
    $(desc).attr("class", "locationTooltip");
    var name = document.createElement('div');
    $(name).css("font-weight", "bold");
    $(name).html(location.name);
    $(desc).append(name);
    if (location.time != null && location.time != "") {
        $(desc).append(location.time + "<br />");
    }
    if (location.address1 != null && location.address1 != "") {
        $(desc).append(location.address1 + "<br />");
    }
    if (location.city != null && location.city != "") {
        $(desc).append(location.city + ", " + location.state + " " + location.zip);
    }
    if (location.phone != null && location.phone != "") {
        var phone = document.createElement('div');
        var phonename = document.createTextNode("Phone: ");
        $(phone).append(phonename);
        $(phone).append(location.phone);
        $(desc).append(phone);
    }
    if (location.fax != null && location.fax != "") {
        var fax = document.createElement('div');
        var faxname = document.createTextNode("Fax: ");
        $(fax).append(faxname);
        $(fax).append(location.fax);
        $(desc).append(fax);
    }
    if (location.contactemail != null && location.contactemail != "") {
        var contact = document.createElement('div');
        var contactname = document.createTextNode("Contact: ");
        $(contact).append(contactname);
        var contactanchor = document.createElement('a');
        $(contactanchor).attr("href", "mailto:" + location.contactemail);
        $(contactanchor).html(location.contactname);
        $(contact).append(contactanchor);
        $(desc).append(contact);
    }
    else if (location.contactname != null && location.contactname != "") {
        var contact = document.createElement('div');
        $(contact).append("Contact: " + location.contactname);
        $(desc).append(contact);
    }
    if (location.infoageurl != null && location.infoageurl != "") {
        var infopage = document.createElement('div');
        var infopageanchor = document.createElement('a');
        $(infopageanchor).attr("href", location.infopageurl);
        $(infopageanchor).attr("target", "_blank");
        $(infopageanchor).html("More Information");
        $(infopage).append(infopageanchor);
        $(desc).append(infopage);
    }

    var getdirections = document.createElement('div');
    $(getdirections).attr("id", "getdirections");
    var getdirectionsanchor = document.createElement('a');
    $(getdirectionsanchor).attr("href", "javascript:InitializeDirections();");
    $(getdirectionsanchor).html("Get Directions");
    $(getdirections).append(getdirectionsanchor);
    $(desc).append(getdirections);

    var getdirectionsform = document.createElement('div');
    $(getdirectionsform).attr("id", "getdirectionsform");
    var directiontext = document.createElement('input');
    $(directiontext).attr("id", "directionText");
    $(directiontext).attr("type", "text");
    $(getdirectionsform).append(directiontext);
    $(getdirectionsform).append(document.createTextNode(" "));
    var directionslink = document.createElement('a');
    $(directionslink).attr("href", "javascript:getDirections();");
    $(directionslink).html("Go >>");
    $(getdirectionsform).append(directionslink);
    $(getdirectionsform).append(document.createElement('br'));
    var resetdirections = document.createElement('a');
    $(resetdirections).attr("id", "resetDirections");
    $(resetdirections).attr("href", "javascript:ResetDirection();");
    $(resetdirections).html("Go Back >>");
    $(getdirectionsform).append(resetdirections);
    $(desc).append(getdirectionsform);
    
    return desc;
}

function InitializeDirections() {
    // Hide the link
    $("#getdirections").slideUp("fast");
    // Show the form
    $("#getdirectionsform").slideDown("slow");
}

function ResetDirection() {
    // Hide the form
    $("#getdirectionsform").slideUp("fast");
    // Show the link
    $("#getdirections").slideDown("slow");
}

function getDirections() {
    // Animate the map inward and directions outward
    $("#directionscontainer").animate({ "left": "-=250px" }, "slow");
    // We don't want to continue until this animation is complete so that map resized properly
    $("#mapcontainer").animate({ "width": "-=250px" }, "slow", "linear", getDirectionsContinue);
}

function getDirectionsContinue() {
    // Resize the map
    map.checkResize();
    // Get the from directions from the textbox
    var from = $("#directionText").val();
    // Get the to lat/long from the currentMarker
    var to = currentMarker.getLatLng().lat() + ", " + currentMarker.getLatLng().lng();
    // Build the query string
    var query = "from: " + from + " to: " + to;
    // Close the info window
    // NOTE: This MUST only be done after retrieving the address from the window
    map.closeInfoWindow();
    // Load the directions from teh previously created directions object
    directions.load(query);
}

function clearDirections() {
    // Make sure any info windows are closed
    map.closeInfoWindow();
    // Remove the directions results
    directions.clear();
    // Animate the map inward and directions outward
    $("#mapcontainer").animate({ "width": "+=250px" }, "slow");
    // We don't want to continue until this animation is complete so that map resized properly
    $("#directionscontainer").animate({ "left": "+=250px" }, "slow", "linear", clearDirectionsContinue);
}

function clearDirectionsContinue() {    
    // Resize the map
    map.checkResize();
    // Recenter the map
    layoutMap();
}

function directionsLoaded() {
    if (directions.getNumRoutes() > 0) {
        var route = directions.getRoute(0);
        var start = route.getStep(0).getLatLng().lat() + "," + route.getStep(0).getLatLng().lng();
        var end = route.getEndLatLng().lat() + "," + route.getEndLatLng().lng();
        var print = printLink.replace("##STARTADDR##", start);
        print = print.replace("##DESTADDR##", end);
        $("#directionsPrintLink").attr("href", print);
    }
}