﻿var map;
var RangeInterpolated = "RANGE_INTERPOLATED";
var Rooftop = "ROOFTOP";
var Markers = [];
var InfoWindow = new google.maps.InfoWindow({ content: null });

function GetDefaultMapStyles() {
    var myStyles = [
        {
            elementType: 'all',
            stylers: [
                { invert_lightness: false },
                { saturation: 0 },
                { lightness: 0 }
            ]
        },
        {
            featureType: 'water',
            elementType: 'labels',
            stylers: [
                { visibility: 'off' }
            ]
        },
        {
            featureType: 'poi',
            elementType: 'geometry',
            stylers: [
                { visibility: 'off' }
            ]
        },
        {
            featureType: 'poi',
            elementType: 'labels',
            stylers: [
                { visibility: 'off' }
            ]
        },
        {
            featureType: 'administrative.land_parcel',
            elementType: 'geometry',
            stylers: [
                { visibility: 'off' }
            ]
        },
        {
            featureType: 'administrative.locality',
            elementType: 'geometry',
            stylers: [
                { visibility: 'off' }
            ]
        },
        {
            featureType: 'administrative.neighborhood',
            elementType: 'geometry',
            stylers: [
                { visibility: 'off' }
            ]
        },
        {
            featureType: 'transit',
            elementType: 'geometry',
            stylers: [
                { visibility: 'off' }
            ]
        },
        {
            featureType: 'transit',
            elementType: 'labels',
            stylers: [
                { visibility: 'off' }
            ]
        }
    ];

    //{ hue: '' },
    //        { saturation: '' },
    //        { lightness: '' },

    var styleMap = new google.maps.StyledMapType(myStyles, { name: 'myStyle' });
    return styleMap;
}

function GetDefaultOptions(latlng, zoom) {
    var myOptions = {
        mapTypeControl: false,
        streetViewControl: false,
        panControl: true,
        panControlOptions: {
            position: google.maps.ControlPosition.LEFT_CENTER
        },
        zoomControl: true,
        zoomControlOptions: {
            style: google.maps.ZoomControlStyle.LARGE,
            position: google.maps.ControlPosition.LEFT_CENTER
        },
        zoom: parseInt(zoom),
        center: latlng,
        mapTypeIds: [google.maps.MapTypeId.ROADMAP, 'myStyle']
    };
    return myOptions;
}

function GetSmallMapOptions(latlng, zoom) {
    var myOptions = GetDefaultOptions(latlng, zoom);
    myOptions.zoomControlOptions.style = google.maps.ZoomControlStyle.SMALL;
    myOptions.panControl = false;
    return myOptions;
}

function MakeSafeForUrl(text) {
    text = text.replace('.', '');
    text = text.replace('&amp', 'and');
    text = text.replace('&', 'and');
    text = text.replace('\\', '');
    text = text.replace(':', '');
    text = text.replace('/', '');
    text = text.replace(/[^a-zA-Z 0-9]+/g,'');
    return text;
}

function GetMarkerContent(location) {
    var content = "<div style=\"white-space:nowrap;\">" +
                            "<table class=\"MapPopup\">" +
                                "<tr>" +
                                    "<td colspan=\"2\" style=\"\">" +
                                        "<h3>" + location.BusinessName + "</h3>" +
                                    "</td>" +
                                "</tr>" +
                                "<tr>" +
                                    "<td style=\"\">" +
                                        "<address>" +
                                            location.AddressLine + "<br/>";
    if(location.AddressLine2 != null) {
        if (location.AddressLine2.length > 0) {
            content += location.AddressLine2 + "<br/>";
        }    
    }
    content += location.City + ", " + location.AdminArea1Code + " " + location.PostalCode + "<br/>" +
                                        "</address>" +
                                        "<br/>";
    if (location.Phone.length > 0) {
        content += "p. " + location.Phone + "<br/>";
    }
    if(location.Phone2 != null) {
        if (location.Phone2.length > 0) {
            content += "p. " + location.Phone2 + "<br/>";
        }
    }
    if (location.Fax != null) {
        if (location.Fax.length > 0) {
            content += "f. " + location.Fax + "<br/>";
        }
    }
    content += "</td>" +
                                    "<td style=\"\">" +
                                        "<h4>Services</h4>" +
                                        "<ul style=\"\">";
    
    $(location.Services).each(function () {
        content += "<li><a href=\"/Location/" + location.Id + "/" + this.replace('&','and') + "/" + MakeSafeForUrl(location.BusinessName) + "_" + MakeSafeForUrl(location.City) + "_" + MakeSafeForUrl(location.AdminArea1) + "_" + MakeSafeForUrl(location.PostalCode) + "\">" + this + "</a></li>";
    });
    content += "</ul>" +
                                    "</td>" +
                                "</tr>" +
                            "</table>" +
                        "</div>";
    return content;
}

function GetMatchingMarker(markerLocationId) {
    var match = null;
    $(Markers).each(function (index) {
        if (Markers[index].locationId == markerLocationId) {
            match = Markers[index];
            return false;
        }
    });
    return match;
}

function MarkAllMarkersNotMatching() {
    $(Markers).each(function (index) {
        Markers[index].match = false;
    });
}

function MarkAllMarkersNotShown() {
    $(Markers).each(function (index) {
        Markers[index].shown = false;
        Markers[index].setMap(null);
    });
}

function HideAllNotShownMarkers() {
    $(Markers).each(function (index) {
        if (Markers[index].match == false) {
            Markers[index].shown = false;
            Markers[index].setMap(null);
        }
    });
}

function HandleLocationsData(data, textStatus, jqXHR) {
    //Data will be a list of locations

    MarkAllMarkersNotMatching();

    $(data).each(function () {

        var markerMatch = GetMatchingMarker(this.Id);

        if (markerMatch == null) {

            var position = new google.maps.LatLng(this.Latitude, this.Longitude, true);
            var marker = new google.maps.Marker({
                position: position,
                icon: '/Areas/AdminAreas/content/images/marker.png',
                title: this.BusinessName,
                locationId: this.Id,
                shown: true,
                match: true
            });

            marker.content = GetMarkerContent(this);

            google.maps.event.addListener(marker, 'click', function () {
                InfoWindow.content = marker.content;
                InfoWindow.open(map, marker);
            });

            marker.setMap(map);
            Markers.push(marker);
        } else {
            markerMatch.match = true;
            if (markerMatch.shown == false) {
                markerMatch.shown = true;
                markerMatch.setMap(map);
            }
        }
    });

    HideAllNotShownMarkers();
}

function SetMap(latlng, zoom, services, mapElementId) {
    var myOptions = GetDefaultOptions(latlng, zoom);
    map = new google.maps.Map(document.getElementById(mapElementId), myOptions);
    google.maps.event.addListener(map, 'bounds_changed', function () {
        GetLocations(services);
    });
    var styleMap = GetDefaultMapStyles();
    map.mapTypes.set('myStyle', styleMap);
    map.setMapTypeId('myStyle');
    MarkAllMarkersNotShown();
}

function SetSmallMap(latlng, zoom, mapElementId) {
    var myOptions = GetSmallMapOptions(latlng, zoom);
    map = new google.maps.Map(document.getElementById(mapElementId), myOptions);
    var styleMap = GetDefaultMapStyles();
    map.mapTypes.set('myStyle', styleMap);
    map.setMapTypeId('myStyle');
}

function GetLocations(services) {
    $.cookie('Lat', map.getCenter().lat());
    $.cookie('Lng', map.getCenter().lng());
    $.cookie('Zoom', map.getZoom());
    var bounds = map.getBounds();
    var ne = bounds.getNorthEast();
    var sw = bounds.getSouthWest();
    var neLat = ne.lat();
    var neLng = ne.lng();
    var swLat = sw.lat();
    var swLng = sw.lng();
    var params = JSON.stringify({
        NorthEastLat: neLat,
        NorthEastLng: neLng,
        SouthWestLat: swLat,
        SouthWestLng: swLng,
        Services: services()
    });

    $.ajax({
        type: "POST",
        url: "/Home/GetLocations",
        data: params,
        dataType: "json",
        contentType: "application/json; charset=utf-8",
        success: HandleLocationsData
    });
}
