﻿var tries = 0;
var ogMaps = [];
var markers = [];
var infoWindows = [];
var homeMarker;

function CreateMarker(latitude, longitude, index, name) {
    var iconPath = (index == null
            ? "/uploadedimages/_Assets/images/icons/gmap_marker_home.png"
            : (index < 10
            ? "/uploadedimages/_Assets/images/icons/gmap_marker_" + (index + 1) + ".png"
            : "/uploadedimages/_Assets/images/icons/gmap_marker.png"));

    return new google.maps.Marker({
        position: new google.maps.LatLng(latitude, longitude),
        title: (name == null ? name : ''),
        icon: iconPath 
    });
}

function GMapInit(restaurants, elemID, showControls, mapHome) {
    if (typeof (elemID) == "undefined")
        elemID = "gMap";

    GMapRemoveAllMarkers(elemID);
    GMapRemoveAllInfoWindows(elemID);

    //make sure google.maps api has been loaded before we proceed
    if (typeof (google) != null && typeof (google.maps) != null
        && restaurants != null && restaurants.length > 0)
    {
        if (typeof (showControls) == "undefined")
            showControls = false;
        var opts = {
            zoom: (elemID == "myGMap" ? 9 : 12),
            center: new google.maps.LatLng(restaurants[0].Latitude, restaurants[0].Longitude),
            mapTypeId: google.maps.MapTypeId.ROADMAP,
            navigationControl: showControls,
            scaleControl: false,
            mapTypeControl: showControls,
            streetViewControl: showControls
        };

        ogMaps[elemID] = new google.maps.Map(document.getElementById(elemID), opts);

        if (mapHome) {
            homeMarker = CreateMarker(mapHome.Latitude, mapHome.Longitude, null, null);
            GMapAddMarker(homeMarker, ogMaps[elemID], elemID, null);
        }

        var latLngs = [];
        for (i = 0; i < restaurants.length; i++) {
            var marker = CreateMarker(restaurants[i].Latitude, restaurants[i].Longitude, i, restaurants[i].MapName);
            GMapAddMarker(marker, ogMaps[elemID], elemID, i);
            
            if (elemID == "myGMap" || elemID == "gMap") {
                //add latlng to latLngs array for bounds calculation
                latLngs[i] = new google.maps.LatLng(restaurants[i].Latitude, restaurants[i].Longitude);
            }

            if (elemID == "myGMap") {
                //only add info windows to location search map
                GMapAddInfoWindow(getInfoWindowInformation(restaurants[i]), marker, ogMaps[elemID], elemID);
            }
        }

        if (latLngs.length > 1) {
            var latlngbounds = new google.maps.LatLngBounds();
            for (var i = 0; i < latLngs.length; i++) {
                latlngbounds.extend(latLngs[i]);
            }

            if ((elemID == "gMap")) {
                google.maps.event.addListenerOnce(ogMaps[elemID], 'idle', function (event) {
                    zoomPaperMapToBounds(elemID, latLngs, latlngbounds.getCenter())
                });
            }
//            else {
//                ogMaps[elemID].fitBounds(latlngbounds);
//            }
        }
    }
    else if (tries < 10)
        window.setTimeout("GMapInit(" + restaurants + ", \"" + elemID + "\")", 50);
    tries++;
}

function zoomPaperMapToBounds(elemID, latLngs, centerPoint) {
    for (var i = 0; i < latLngs.length; i++) {
        var mapBounds = ogMaps[elemID].getBounds();
        if (!mapBounds.contains(latLngs[i])) {
            ogMaps[elemID].setZoom(ogMaps[elemID].getZoom() - 1);
        }
    }
    //  Allow extra room to include full map marker display
    if (ogMaps[elemID].getZoom() > 2) {
        ogMaps[elemID].setZoom(ogMaps[elemID].getZoom() - 2);
    }
    GMapCenter(centerPoint.lat(), centerPoint.lng(), elemID);
}

function getInfoWindowInformation(restaurant) {
    var info = new google.maps.InfoWindow({
        content: "<img src='/uploadedimages/_Assets/images/icons/ico_log_og.gif' align='right' />"
            + restaurant.MapName + "<br />"
            + restaurant.Address1 + "<br />"
            + (restaurant.Address2.length > 0
                ? restaurant.Address2 + "<br />"
                : "")
            + restaurant.City + ", " + restaurant.State + " " + restaurant.ZIPCode + "<br />"
            + restaurant.PhoneNumber
    });

    return info;
}

function GMapCenter(lat, lon, elemID) {
    if (ogMaps == null || ogMaps[elemID] == null)
        return;
    
    ogMaps[elemID].setCenter(new google.maps.LatLng(lat, lon));
    
    if (markers != null && markers[elemID] != null && markers[elemID].length > 0)
    {
        for (m in markers[elemID])
        {
            var latLng = markers[elemID][m].getPosition();
            if (latLng.equals(new google.maps.LatLng(lat, lon)))
            {
                google.maps.event.trigger(markers[elemID][m], "click");
            }
        }
    }
}

function GMapAddInfoWindow(infoWindow, marker, map, elemID)
{
    var infoListener = google.maps.event.addListener(marker, "click", function() {
                            for (i in infoWindows[elemID])
                                infoWindows[elemID][i][0].close();
                            
                            infoWindow.open(map, marker);
                        });
    infoWindows[elemID].push([infoWindow, infoListener]);
}

function GMapRemoveAllInfoWindows(elemID)
{
    if (infoWindows != null && infoWindows[elemID] != null && infoWindows[elemID].length > 0)
    {
        for (i in infoWindows[elemID])
            google.maps.event.removeListener(infoWindows[elemID][i][1]);
    }
    infoWindows[elemID] = [];
}

function GMapAddMarker(marker, map, elemID, index) {
    if (index != null && elemID == "myGMap") {
        google.maps.event.addListener(marker, "click", function () {
            mapMarkerClick(index);
        });
        markers[elemID].push(marker);
    }
    marker.setMap(map);
}

function GMapRemoveMarker(marker) {
    marker.setMap(null);
}

function GMapRemoveAllMarkers(elemID) {
    if (markers != null && markers[elemID] != null && markers[elemID].length > 0) {
        for (m in markers[elemID]) {
            GMapRemoveMarker(markers[elemID][m]);
        }
    }
    markers[elemID] = [];

    if (homeMarker != null) {
        GMapRemoveMarker(homeMarker);
    }
}

function GMapReload(zip, returnFunc) {
    $.getJSON("/Services/Search_Handler.ashx?t=p&term=" + zip, function (d) {
        $(".aditional_info").show();
        if (d != null)
            GMapInit(eval(d[1]));
        returnFunc(d);
    });
}
