﻿var map;
var markerMgr;
var facilities = [];
var geocoder;
var icon;
var _isAdvancedSearch = false;

var ERRORS = {
    map: "Sorry, we're unable to access the facility map right now. Please try again later",
    loading: "Loading facilities, please wait.",
    city: "Please enter a valid city and state.",
    state: "Please enter a state.",
    zip: "Please enter a valid zip code.",
    results: "Sorry, we have no facilities in that area.",
    filteredResults: "Sorry, we have no facilities meeting your requirements in that area."
};

var isIE6 = false/*@cc_on || @_jscript_version < 5.7@*/;

$(document).ready(loadMap);
$(window).unload(unloadMap);
$(document).keypress(function(event) {
    if (event.keyCode == 13) {
        search();
        return false;
    }
});

function loadMap() {
    $(".advanced-search").click(toggleAdvanced);
	switchSearch();
    if (GMap2 && GBrowserIsCompatible()) {
        // Create map
        var options = {}; //{ size : new GSize(400, 400) };
        map = new GMap2($('#map')[0], options);
        map.addControl(new GLargeMapControl());
        map.setCenter(new GLatLng(38.5, -95), 4);

        // Create icon
        icon = new GIcon();
        icon.iconSize = new GSize(23, 22);
        icon.iconAnchor = new GPoint(7, 21);
        icon.infoWindowAnchor = new GPoint(7, 21);
        if (isIE6) {  // IE6 can't handle all the markers
            icon.image = "/sites/global/images/marker.gif";
            icon.transparent = null;
            icon.shadow = null;
            icon.shadowSize = null;
            icon.infoShadowAnchor = null;
        } else {
            icon.image = "/sites/global/images/marker.png";
            icon.shadow = "/sites/global/images/marker_shadow.png";
            icon.shadowSize = new GSize(23, 22);
            icon.infoShadowAnchor = new GPoint(7, 21);
        }

        // Create other objects
        markerMgr = new MarkerManager(map);
        geocoder = new GClientGeocoder();

        // Request facilities
        $.getJSON("/sites/global/Templates/FacilitySearchData.aspx", addFacilities);
    }
}

function unloadMap() {
    if (GMap2) GUnload();
}

function addFacilities(facilities) {
    $.each(facilities, function(i, facility) { addFacility(facility); });
    clearStatus();
}

function addFacility(facility) {
    var options = { icon: icon };
    facility.marker = new GMarker(new GLatLng(facility.Latitude, facility.Longitude), options);
    facility.marker.bindInfoWindowHtml(getFacilityHtml(facility));
    markerMgr.addMarker(facility.marker, 1);
    facilities.push(facility);
}

function getFacilityHtml(facility) {
    var html = '<div class="map-bubble">';
    if (facility.Image != null) html += '<img src="' + facility.Image + '" />';
    html += '<h4><a href="' + facility.ViewUrl + '">' + facility.Name.toUpperCase() + '</a></h4><p>'
    if (facility.Address) html += facility.Address.toUpperCase() + "<br/>";
    if (facility.City && facility.State) html += facility.City.toUpperCase() + ", " + facility.State.toUpperCase();
    if (facility.Zip) html += " " + facility.Zip.toUpperCase() + "<br/>";
    html += '<p class="arrow-link"><a href="' + facility.ViewUrl + '">more</a></p>';
    html += "</p></div>";
    return html;
}

function switchSearch() {
    switch (searchBy()) {
        case 'city':
            $("#city_container").show();
            $("#state_container").show();
            $("#zip_container").hide();
            $("#within_container").show();
            break;
        case 'state':
            $("#city_container").hide();
            $("#state_container").show();
            $("#zip_container").hide();
            $("#within_container").hide();
            break;
        case 'zip':
            $("#city_container").hide();
            $("#state_container").hide();
            $("#zip_container").show();
            $("#within_container").show();
            break;
    }
}

function search() {

    if (!map) {
        error(ERRORS.map);
    } else if (facilities.length == 0) {
        error(ERRORS.loading);
    } else {
        var statusList = [];
        var advancedList = [];
        clearStatus();

        // Prepare search status
        if (isAdvanced()) {
            advancedList = $(".metatag:checked").map(function(i, elt) { return $(elt).attr("title"); });
        }

        // Search
        switch (searchBy()) {
            case 'city':
                var city = jQuery.trim($("#city").val());
                var state = $($("#state")[0]);
                if (city == "" || state.selectedIndex == 0) {
                    error(ERRORS.city);
                    return;
                }
                geocoder.getLocations(city + ", " + state.val(), onGetLocations);
                statusList.push(city);
                statusList.push(state.val().toUpperCase());
                status("Showing: " + jQuery.merge(statusList, advancedList).join(", "));
                break;
            case 'state':
                var state = $($("#state")[0]);
                if (state.selectedIndex == 0) {
                    error(ERRORS.state);
                    return;
                }
                statusList.push(state.val().toUpperCase());
                status("Showing: " + jQuery.merge(statusList, advancedList).join(", "));
                showFacilities(jQuery.grep(facilities, function(fac, i) {
                    return fac.State.toUpperCase() == state.val().toUpperCase();
                }));
                break;
            case 'zip':
                var zip = jQuery.trim($("#zip").val());
                if (zip == "") {
                    error(ERRORS.zip);
                    return;
                }
                $("#simpler_loader").show();
                geocoder.getLocations(zip, onGetLocations);
                statusList.push(zip);
                status("Showing: " + jQuery.merge(statusList, advancedList).join(", "));
                break;
        }
    }
}

function onGetLocations(response) {

    $("#simple_loader").hide();

    // Check status
    switch (response.Status.code) {
        case 200:
            break;
        case 601:
        case 602:
            error(searchBy() == "city" ? ERRORS.city : ERRORS.zip);
            return;
        default:
            error(errors.map);
            return;
    }

    // Get location
    var placemark = response.Placemark[0];
    var point = new GLatLng(placemark.Point.coordinates[1], placemark.Point.coordinates[0]);

    // Adjust map
    var within = $("#within")[0];
    var limit = parseInt($(within).val()) * 1609;
    var facs = jQuery.grep(facilities, function(fac, i) { return distance(point, fac) < limit; });
    facs.sort(function(a, b) { return distance(point, a) - distance(point, b); });
    showFacilities(facs);
}

function showFacilities(facs) {
    // Filter
    if (isAdvanced()) facs = ffilter2(facs);
    else showFilterdFacilities(facs);
}

function showFilterdFacilities(facs) {
    if (facs.length == 0) {
        clearStatus();
        error(isAdvanced() ? ERRORS.filteredResults : ERRORS.results);
    } else {
        var bounds = new GLatLngBounds();
        var resultsContainer = $($('#results_container')[0]);
        var results = $('#results')[0];

        // Show results pane    
        if (resultsContainer.is(":hidden")) {
            var mapContainer = $(map.getContainer());
            var width = resultsContainer.width();
            mapContainer.width(mapContainer.width() - width);
            mapContainer.css("left", width + "px");
            resultsContainer.show();
            map.checkResize();
        }

        // Add results
        markerMgr.clearMarkers();
        results.innerHTML = "";
        for (var i = 0; i < facs.length; i++) {
            results.innerHTML += getFacilityHtml(facs[i]);
            markerMgr.addMarker(facs[i].marker, 1);
            bounds.extend(facs[i].marker.getLatLng());
        }

        // Adjust map
        point = new GLatLng(
      (bounds.getNorthEast().lat() + bounds.getSouthWest().lat()) / 2,
      (bounds.getNorthEast().lng() + bounds.getSouthWest().lng()) / 2);
        map.setCenter(point, map.getBoundsZoomLevel(bounds));
        if (isAdvanced()) toggleAdvanced();
        clearStatus();
    }
}

function ffilter2(facs) {
    var checked = $(".metatag:checked").map(function(i, elt) { return elt.name; });
    var ids = jQuery.map(facs, function(fac, i) { return fac.Id; });
    if (checked.length > 0) {
        var checkedArray = prepageJQueryArrayForAjaxCall(checked);
        var facilityArray = prepageJQueryArrayForAjaxCall(ids);
        PageMethods.FFilter(checkedArray, facilityArray, ffilter2Completed);
    }
    else ffilter2Completed([])
}

function prepageJQueryArrayForAjaxCall(srcArray) {
    var arr = new Array();
    for (var i = 0; i < srcArray.length; i++)
        arr[i] = srcArray[i];
    return arr;
}

function ffilter2Completed(res) {
    showFilterdFacilities(jQuery.grep(facilities, function(fac, i) {
        return jQuery.inArray(fac.Id, res) >= 0;
    }));
}

function status(text) {
    clearStatus();
    var elt = $("#status");
    elt.text(text);
    elt.fadeIn();
}

function error(text) {
    clearStatus();
    var elt = $("#error");
    elt.text(text);
    elt.fadeIn();
}

function clearStatus() {
    $("#status").hide();
    $("#error").hide();
}

function distance(point, facility) {
    return point.distanceFrom(facility.marker.getLatLng());
}

function searchBy() {
    return $("input[name='search_by']:checked").val();
}

function isAdvanced() {
    return _isAdvancedSearch;
}

function toggleAdvanced() {
    if (_isAdvancedSearch) {
        //$(".form").animate({ marginTop: "-" + $(".find-care-location")[0].offsetHeight + "px" }, 500);
        $(".form").animate({ marginTop: "-600px" }, 500);
        $("#openCloseIdentifier").show();
        _isAdvancedSearch = false;
    } else {
        $(".form").animate({ marginTop: "0px" }, 500);
        $("#openCloseIdentifier").hide();
        _isAdvancedSearch = true;
    }
}

function findProperty(object, propertyName) {
    if (propertyName in object) {
        return object[propertyName];
    } else {
        for (var child in object) {
            if (typeof child == "string") child = object[child];
            if (typeof child == "object") {
                var property = findProperty(child, propertyName);
                if (property) return property;
            }
        }
        return null;
    }
}
