﻿// Map Object
var map = null;
// Cluster Object - http://googlemapsapi.martinpearman.co.uk/articles.php?cat_id=1
var cluster = null;
// Marker Array
var markersArray = [];
// Event Icon
var icon;
// Multiple Events Icon
var multipleIcon;
// 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());
    // Set the Map Type
    // map.setMapType(G_HYBRID_MAP);

    // 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));

    icon = new GIcon();
    icon.image = '/Images/icon_person.png';
    icon.shadow = '/Images/icon_shadow.png';
    icon.shadowSize = new GSize(52, 29);
    icon.iconSize = new GSize(21, 31);
    icon.iconAnchor = new GPoint(10, 30);
    icon.infoWindowAnchor = new GPoint(10, 8);

    multipleIcon = new GIcon();
    multipleIcon.image = '/Images/icon_magnifying.png';
    multipleIcon.shadow = '/Images/icon_magnifying_shadow.png';
    multipleIcon.shadowSize = new GSize(46, 33);
    multipleIcon.iconSize = new GSize(29, 33);
    multipleIcon.iconAnchor = new GPoint(10, 30);
    multipleIcon.infoWindowAnchor = new GPoint(10, 8);

    // 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, { icon:icon });
        // Bind the infoWindow
        var desc = formatLocationTooltip(locations[currentAddress]);
            google.maps.Event.addListener(marker, "mouseover", showToolTip);
            google.maps.Event.addListener(marker, "mouseout", hideToolTip);
//        google.maps.Event.addListener(marker, "click", function() {
//            marker.openInfoWindowHtml(desc);
//            currentMarker = marker;
//        });
        // Add the marker to the array
        markersArray.push(marker);
    }
    // Increment the address
    currentAddress += 1;
    // If there are more
    if (currentAddress < locations.length) {
        // Find the next one
        findLoc();
    }
    else {
        // Configure the cluster manager
        cluster = new ClusterMarker(map, { markers:markersArray, clusterMarkerIcon:multipleIcon, clusterMarkerTitle:'Click to zoom in and see %count members', intersectPadding:0 });
        cluster.fitMapToMarkers();
        map.zoomOut();
        map.savePosition();
        // Remove the loading screen
        $("#mapLoading").css("display", "none");
    }
}

function layoutMap() {
    map.setCenter(bounds.getCenter());
    map.setZoom(map.getBoundsZoomLevel(bounds) - 1);
}

// 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.Company != null && location.Company != "") {
        $(desc).append(location.Company + "<br />");
    }
    if (location.city != null && location.city != "") {
        $(desc).append(location.city + ", " + location.state + " " + location.zip);
    }
    var nos = document.createElement('div');
    if (location.MemberNo != null && location.MemberNo != "") {
        var mno = document.createElement('span');
        $(mno).append("No: " + location.MemberNo + "&nbsp;");
        $(nos).append(mno);
    }
    if (location.CGENo != null && location.CGENo != "") {
        var cge = document.createElement('span');
        $(cge).append("CGE: " + location.CGENo);
        $(nos).append(cge);
    }
    $(desc).append(nos);

    /*
    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);
    }
}

// *** ToolTip Logic *** //
function showToolTip(point) {
    var desc = document.createElement('div');
    $(desc).attr("class", "locationTooltipContainer");
    var count = 0;

    alert(point.lat());
    alert(point.lng());

    $.each(locations, function(index, location) {
        if (location.Latitude == point.lat() && location.Longitude == point.lng()) {
            count++;
            var l = document.createElement('div');
            $(l).attr("id", "location-" + count);
            var css = "location";
            if ((count % 2) == 0) {
                css = css + ' lastcolumn';
            }
            if (count < 3) {
                css = css + ' firstrow';
            }

            $(l).attr("class", css);
            $(l).append(formatLocationTooltip(location));
            $(desc).append(l);
        }
    });

    if (count == 1) {
        $(desc).find("div:first").attr("class", "location firstrow lastcolumn");
    }

    if ((count % 2) > 0 && count > 3) {
        var filler = document.createElement('div');
        $(filler).attr("class", "location lastcolumn");
        $(filler).html("&nbsp;");
        $(desc).append(filler);
    }

    var cols = 1;
    if (count > 1) {
        cols += 1;
    }

    var rows = 1;
    if (count > 2) {
        rows = Math.floor(count / 2);
        if ((count % 2) > 0) {
            rows++;
        }
    }

    var tooltip = $("#tooltip");
    $(tooltip).css("width", cols * 175 + 4);
    $(tooltip).css("height", rows * 68 + 4);
    $(tooltip).css("left", mouseX + 5);
    $(tooltip).css("top", mouseY + 5);
    $(tooltip).html($(desc).html());
    $(tooltip).show("fast");
}

function hideToolTip(point) {
    $("#tooltip").hide();
}
