google.load("jquery", "1.3.2");
google.load("jqueryui", "1.7.2");

var map;
var markerManager;
var geocoder;
var infowindow;
var markers;
var marker;
var markersArray = [];

function initializeStyles() {
    $("#navigation a[href$='geoprogramsearch.aspx']").removeAttr("onmouseover").removeAttr("onmouseout").children("img").attr("src", "images/nav_maps-h.gif");
    $("#filters").addClass("ui-accordion ui-widget ui-helper-reset").find("h3").addClass("ui-accordion-header ui-helper-reset ui-state-default ui-corner-top ui-corner-bottom").prepend('<span class="ui-icon ui-icon-triangle-1-e"/>').click(function() {
        $(this).toggleClass("ui-accordion-header-active").toggleClass("ui-state-active").toggleClass("ui-state-default").toggleClass("ui-corner-bottom").find(">  .ui-icon").toggleClass("ui-icon-triangle-1-e").toggleClass("ui-icon-triangle-1-s").end().next().toggleClass("ui-accordion-content-active").toggle();
        return false;
    }).next().addClass("ui-accordion-content ui-helper-reset ui-widget-content ui-corner-bottom").hide();
    $("#filters h3:first").click();
    $(".majorAgencyFilter").each(function() {
        $(this).next().attr("for", $(this).attr("id"));
    });
    $(".topicFilter").each(function() {
        $(this).next().attr("for", $(this).attr("id"));
    });
    $("#selectAllTopicFilters").click(function() {
        $(".topicFilter").each(function() {
            $(this).attr('checked', true)
        });
        return false;
    });
    $("#deselectAllTopicFilters").click(function() {
        $(".topicFilter").each(function() {
            $(this).attr('checked', false)
        });
        return false;
    });
    $("#selectAllMajorAgencyFilters").click(function() {
        $(".majorAgencyFilter").each(function() {
            $(this).attr('checked', true)
        });
        return false;
    });
    $("#deselectAllMajorAgencyFilters").click(function() {
        $(".majorAgencyFilter").each(function() {
            $(this).attr('checked', false)
        });
        return false;
    });
    $(".command").hover(function() {
        $(this).addClass("ui-state-hover");
    }, function() {
        $(this).removeClass("ui-state-hover");
    });
}

function blockMain() {
    $('#mapCanvas').block({
        message: $('#blockMainMessage'),
        overlyCSS: {
            backgroundColor: '#F1F2F7'
        }
    });
}

function unblockMain() {
    $('#mapCanvas').unblock({
        fadeOut: 0
    });
}

function initialize() {
    $("#dialog").dialog("destroy");

        initializeStyles();
    
      
        var myLatlng = new google.maps.LatLng(40, -98);
        var mapOptions = {
            zoom: 4,
            center: myLatlng,
            mapTypeId: google.maps.MapTypeId.ROADMAP
        };

        map = new google.maps.Map($("#mapCanvas")[0], mapOptions);
        
        textBoxAddress = $("[id$='textBoxAddress']");
        $("#findPrograms").click(findPrograms);
        $("#aPrintPrograms").click(function() {
            $.blockUI({
                message: $('#question'),
                css: {
                    width: '450px',
                    '-moz-opacity': '1',
                    opacity: '1',
                    left: '30%'
                },
                overlayCSS: {
                    opacity: 0.
                }
            });
        });
        $('#ok').click(function() {
            $.unblockUI();
            var found = $("body").find("[id$='formPrint']");
            if (found.length > 0) {
                $("body").remove("[id$='formPrint']");
                $("[id$='formPrint']").remove();
            }
            var rno = Math.random();
            $("body").append("<form id=\"formPrint\" target=\"_blank\" method=\"post\" action=\"geoProgramPrint.aspx?rno=" + rno + "\">" + "<input type=\"hidden\" name=\"Address\" runat=\"server\" value=\"" + $("[id$='textBoxAddress']").val() + "\" \>" + "<input type=\"hidden\" name=\"Radius\" runat=\"server\" value=\"" + $("[id$='dropDownListAddressRadius'] :selected").val() + "\" \>" + "<input type=\"hidden\" name=\"RecipientId\" runat=\"server\" value=\"" + $("[id$='textRecipientId']").val() + "\" \>" + "<input type=\"hidden\" name=\"XCord\" runat=\"server\" value=\"" + $("[id$='textX']").val() + "\" \>" + "<input type=\"hidden\" name=\"YCord\" runat=\"server\" value=\"" + $("[id$='textY']").val() + "\" \>" + "<input type=\"hidden\" name=\"TopicFilters\" runat=\"server\" value=\"" + getTopicFilters().join(',') + "\" \>" + "<input type=\"hidden\" name=\"MajorAgencyFilters\" runat=\"server\" value=\"" + getMajorAgencyFilters().join(',') + "\" \>" + "</form>").find("#formPrint").submit();
        });
        textBoxAddress.keypress(function(e) {
            keyCode = e.which ? e.which : e.keyCode;
            if (keyCode == 13) {
                $(this).blur();
                $("#findPrograms").focus().click();
                e.preventDefault();
            }
        });
        $("#textOnlyVersion").click(function() {
            $("body").append("<form id=\"formTextOnlyVersion\" method=\"post\" action=\"geoprogramsearchLight.aspx\">" + "<input type=\"hidden\" name=\"Address\" value=\"" + $("[id$='textBoxAddress']").val() + "\" \>" + "<input type=\"hidden\" name=\"Radius\" value=\"" + $("[id$='dropDownListAddressRadius'] :selected").val() + "\" \>" + "<input type=\"hidden\" name=\"TopicFilters\" value=\"" + getTopicFilters().join(',') + "\" \>" + "<input type=\"hidden\" name=\"MajorAgencyFilters\" value=\"" + getMajorAgencyFilters().join(',') + "\" \>" + "</form>").find("#formTextOnlyVersion").submit();
        });
        if (textBoxAddress.val() != "") {
            findPrograms();
        }
}

function newPrintWindow() {
    var querystring = "?Address=" + $("[id$='textBoxAddress']").val()
    querystring += "&Radius=" + $("[id$='dropDownListAddressRadius'] :selected").val()
    querystring += "&RecipientId=" + $("[id$='textRecipientId']").val()
    querystring += "&XCord=" + $("[id$='textX']").val()
    querystring += "&YCord=" + $("[id$='textY']").val()
    querystring += "&TopicFilters=" + getTopicFilters().join(',')
    querystring += "&MajorAgencyFilters=" + getMajorAgencyFilters().join(',')
    var wopen = window.open("geoProgramPrint.aspx" + querystring, "mywindow", "toolbar=yes,menubar=yes,location=yes,status=yes,scrollbars=yes,resizable=yes");
}

function findPrograms() {
    clearInfo();
    var textBoxAddress = $("[id$='textBoxAddress']");
    var requiredValidatorAddress = $("[id$='requiredValidatorAddress']")[0];
    ValidatorEnable(requiredValidatorAddress, true);
    if (requiredValidatorAddress.isvalid) {
        blockMain();
        var viewData = new Object();
        viewData.Address = textBoxAddress.val();
        $.ajax({
            type: "POST",
            url: "geoprogramsearch.aspx/GetLatLng",
            data: "{'viewData':" + JSON.stringify(viewData) + "}",
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            success: function(latLng) {
                if (!latLng.d) {
                    unblockMain();
                    updateInfo("<span style='color:#A90901;'>Unable to locate the address provided.</span>");
                    textBoxAddress.focus();
                }
                else {
                    $.ajax({
                        type: "POST",
                        url: "geoprogramsearch.aspx/FindProgramsByAddress",
                        data: "{'viewData':" + JSON.stringify(getFindProgramsByAddressViewData(latLng.d)) + "}",
                        contentType: "application/json; charset=utf-8",
                        dataType: "json",
                        success: markMapCoordinates
                    });
                }
            }
        });
    } else {
        textBoxAddress.focus();
    }
    return false;
}

function markerExists(markers, marker) {
    for (var i = 0; i < markers.length; i++) {
        currentLatLng = markers[i].getLatLng();
        latLng = marker.getLatLng();
        if (currentLatLng.lat() == latLng.lat() && currentLatLng.lng() == latLng.lng()) return true;
    }
    return false;
}

// Deletes all markers in the array by removing references to them
function deleteOverlays() {
    if (markersArray) {
        for (i in markersArray) {
            markersArray[i].setMap(null);
        }
        markersArray.length = 0;
    }
}

// Removes the overlays from the map, but keeps them in the array
function clearOverlays() {
    if (infowindow) infowindow.close();

    if (markersArray) {
        for (i in markersArray) {
            markersArray[i].setMap(null);
        }
    }
}

// Shows any overlays currently in the array
function showOverlays() {
    if (markersArray) {
        for (i in markersArray) {
            markersArray[i].setMap(map);
        }
    }
}

///	<summary>
/// Marks the map with the coordinates returned.
/// <summary>
function addMarker(location) {
    marker = new google.maps.Marker({
        position: location,
        map: map
    });
    markersArray.push(marker);
}

function attachMessageInfoWindow(marker, number) {
    google.maps.event.addListener(marker, 'click', function() {
        var latLng = new google.maps.LatLng(marker.Y, marker.X);
        marker.position = latLng;
        showRecipientInfo(marker.RecipientId, marker.Y, marker.X, marker);
    });
}

function markMapCoordinates(coordinates) {
    
    clearOverlays();
    
    if (coordinates.d.length == 0) {
        unblockMain();
        updateInfo("No programs were found for the search criteria you provided.");
        return;
    }

    var bounds = new google.maps.LatLngBounds();
    var markers = new Array();

    //Add Markers.
    for (var i = 0; i < coordinates.d.length; i++) {
        var latLng = new google.maps.LatLng(coordinates.d[i].Y, coordinates.d[i].X);

        marker = new google.maps.Marker({
            position: latLng,
            map: map,
            clickable: true,
            icon: 'markers/default.gif'
        });

        markersArray.push(marker);

        marker.setTitle(coordinates.d[i].PTA);
        marker.RecipientId = coordinates.d[i].Id;
        marker.Y = coordinates.d[i].Y;
        marker.X = coordinates.d[i].X;

        attachMessageInfoWindow(marker, i);
        bounds.extend(latLng);
    }

    map.fitBounds(bounds);

    coordinates = null;
    markers = null;
    unblockMain();
}

function getFindProgramsByAddressViewData(point) {
    var viewData = new Object();
    viewData.Latitude = point.Lat;
    viewData.Longitude = point.Lng;
    viewData.Radius = $("[id$='dropDownListAddressRadius'] :selected").val();
    viewData.TopicFilters = getTopicFilters();
    viewData.MajorAgencyFilters = getMajorAgencyFilters();
    return viewData;
}

function getTextOnlyVersionViewData() {
    var viewData = new Object();
    viewData.Address = $("[id$='textBoxAddress']").val();
    viewData.Radius = $("[id$='dropDownListAddressRadius'] :selected").val();
    viewData.TopicFilters = getTopicFilters();
    viewData.MajorAgencyFilters = getMajorAgencyFilters();
    return viewData;
}

function showRecipientInfo(recipientId, y, x, marker) {

    $.ajax({
        type: "POST",
        url: "geoprogramsearch.aspx/GetRecipientInfo",
        data: "{'viewData': {'RecipientId':'" + recipientId + "', 'Y':" + y + ", 'X':" + x + "}}",
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        success: function(recipientInfo) {
            $("[id$='textRecipientId']")[0].value = recipientId;
            $("[id$='textX']")[0].value = x;
            $("[id$='textY']")[0].value = y;

            if (infowindow) infowindow.close();

            infowindow = new google.maps.InfoWindow(
          {
              content: formatRecipientInfo(recipientInfo),
              size: new google.maps.Size(50, 50)
          });

            infowindow.open(map, marker);
        }
    });
}

function formatRecipientInfo(recipientInfo) {
    return "<br /><p style='font-size:8pt;'><strong>" + recipientInfo.d.T + "</strong>" + "<br /><strong><i>CFDA Program Number:</i></strong> " + recipientInfo.d.PN + "<br /><strong><i>Department:</i></strong> " + recipientInfo.d.MAN + "<br /><strong><i>Funding Agency:</i></strong> " + recipientInfo.d.AN + "<br /><strong><i>Recipient:</i></strong> " + recipientInfo.d.N + "<br /><strong><i>Recipient Address:</i></strong> <br />" + recipientInfo.d.A + "</p>";
}

function getProgramFilters() {
    var filters = [];
    $(".programFilter:checked").each(function() {
        filters.push($(this).val());
    });
    return filters;
}

function getTopicFilters() {
    var filters = [];
    $(".topicFilter:checked").each(function() {
        filters.push($(this).val());
    });
    return filters;
}

function getMajorAgencyFilters() {
    var filters = [];
    $(".majorAgencyFilter:checked").each(function() {
        filters.push($(this).val());
    });
    return filters;
}

function updateInfo(info) {
    $("#info").html(info).scrollTo(500).effect("highlight", {}, 2000);
}

function clearInfo() {
    $("#info").html("");
}
google.setOnLoadCallback(initialize);