﻿var map_markers = [];
var map;
var bounds;
var geo;
var currentlyOpenedInfoWindow = null;

// ===== list of words to be standardized =====
var standards = [   ["road","rd"],   
                    ["street","st"], 
                    ["avenue","ave"], 
                    ["av","ave"], 
                    ["drive","dr"],
                    ["saint","st"], 
                    ["north","n"],   
                    ["south","s"],    
                    ["east","e"], 
                    ["west","w"],
                    ["expressway","expy"],
                    ["parkway","pkwy"],
                    ["terrace","ter"],
                    ["turnpike","tpke"],
                    ["highway","hwy"],
                    ["lane","ln"]
                 ];

// ===== convert words to standard versions =====
function standardize(a) {
  for (var i=0; i<standards.length; i++) {
    if (a == standards[i][0])  {a = standards[i][1];}
  }
  return a;
}

function loadResultAndSendToResultsPage(url,address,ddlAffiliateType,ddlAffiliateLevel)
{
    geo = new google.maps.Geocoder(); 

    geo.geocode({address:address}, function (results, status)
    {
        if (status == google.maps.GeocoderStatus.OK && results.length == 1) {
           sendToResultsPage(url,results[0],ddlAffiliateType,ddlAffiliateLevel);
        }
    });
}

function sendToResultsPage(url,result,ddlAffiliateType,ddlAffiliateLevel)
{
    var pieces = new Array();

    for(var i = 0; i < result.address_components.length; i++)
    {
        if (result.address_components[i].types && result.address_components[i].types.length > 0)
        {
            switch(result.address_components[i].types[0])
            {
                case "postal_code":
                    pieces.push("postal_code=" + escape(result.address_components[i].long_name));
                    break;
                    
                case "locality":
                    pieces.push("city=" +  escape(result.address_components[i].long_name));
                    break;
                    
                case "administrative_area_level_1":
                    pieces.push("adminAreaShort=" +  escape(result.address_components[i].short_name));
                    pieces.push("adminAreaLong=" +  escape(result.address_components[i].long_name));
                    break;
                    
                case "country":
                    pieces.push("country=" + escape(result.address_components[i].short_name));
                    break;
            }
        }
    }
    
    pieces.push("lat=" + result.geometry.location.lat());
    pieces.push("lng=" + result.geometry.location.lng());
    pieces.push("addr=" + result.formatted_address);
    
    if (ddlAffiliateType != null && document.getElementById(ddlAffiliateType) != null)
        pieces.push("affiliateType=" + document.getElementById(ddlAffiliateType).value);
    if (ddlAffiliateLevel != null && document.getElementById(ddlAffiliateLevel) != null)
        pieces.push("affiliateLevel=" + document.getElementById(ddlAffiliateLevel).value);
    
    document.location.href = url + "?" + pieces.join("&");
}

function showMap(lat, lng, zoomLevel)
{
    var mapObj = document.getElementById("map");
    mapObj.style.display = 'block';

    var myLatLng = new google.maps.LatLng(lat, lng);

    map = new google.maps.Map(mapObj, { center: myLatLng, mapTypeId: google.maps.MapTypeId.ROADMAP, zoom: zoomLevel });
    bounds = new google.maps.LatLngBounds();
}

function addMarkers() {
    // Clear all existing map markers
    clearOverlays();

    geo = new google.maps.Geocoder(); 

    if (postalCodes && postalCodes.length > 0) {
        for (var i = 0; i < postalCodes.length; i++) {
            // Determine lat/lng for postal code
            geo.geocode({address:postalCodes[i]}, function (results, status)
            {
                if (status == google.maps.GeocoderStatus.OK && results.length >= 1) {
                    addMarker(results[0]);
                }
            });
        }
    }  
}

function addMarker(result) {
    // Get the postal code info for this request...
    var postal_code = null;
    for (var j = 0; j < result.address_components.length; j++)
    {
        if (result.address_components[j].types != null && result.address_components[j].types.length > 0 && result.address_components[j].types[0] == "postal_code")
        {
            postal_code = result.address_components[j].short_name;
            break;
        }
    }
    
    var myOverlay = null;
    for (var k = 0; k < postalCodes.length; k++)
        if (postalCodes[k] == postal_code && overlays.length > k)
        {
            myOverlay = overlays[k];
            break;
        }

    var marker = new google.maps.Marker();
    marker.setTitle("Members in " + postal_code);
    marker.setPosition(result.geometry.location);
    marker.setMap(map);

    map_markers.push(marker);
    
    bounds.extend(marker.getPosition());
    
    if (myOverlay != null)
        createOverlay(marker, myOverlay)

    map.fitBounds(bounds);
    
    if (map.getZoom() > 12)
        map.setZoom(12);
    
    map.setCenter(bounds.getCenter());
}

function clearOverlays() {
    for (var i = 0; i < map_markers.length; i++)
        map_markers[i].setMap(null);

    map_markers.length = 0;
}

function createOverlay(marker, overlayProperties) {
    var overlay = new google.maps.InfoWindow(overlayProperties);
    
    google.maps.event.addListener(marker, 'click', function() {
        if (currentlyOpenedInfoWindow != null)
            currentlyOpenedInfoWindow.close();
        
        overlay.open(map, marker);
        currentlyOpenedInfoWindow = overlay;
    });
}

// ====== Geocoding ======
function showAddress(url,txtSearch,ddlAffiliateType,ddlAffiliateLevel) {
    var search = document.getElementById(txtSearch).value;
    
    if (search.length == 0)
        return;
    
    // ====== Perform the Geocoding ======        
    geo = new google.maps.Geocoder(); 

    geo.geocode({address:search}, function (results, status)
    {
        if (status == google.maps.GeocoderStatus.OK) {
          // ===== If there was more than one result, "ask did you mean" on them all =====
          if (results.length > 1) { 
            document.getElementById("message").innerHTML = "Did you mean:";
            // Loop through the results
            for (var i=0; i<results.length; i++) {
              document.getElementById("message").innerHTML += "<br>"+(i+1)+": <a href='javascript:loadResultAndSendToResultsPage(\"" + url + "\",\"" +results[i].formatted_address+"\",\"" + ddlAffiliateType + "\",\"" + ddlAffiliateLevel + "\")'>"+ results[i].formatted_address +"<\/a>";
            }
          }
          // ===== If there was a single marker, is the returned address significantly different =====
          else
              sendToResultsPage(url,results[0],ddlAffiliateType,ddlAffiliateLevel);
        }
        // ====== Decode the error status ======
        else
          alert('Search on address "'+search+ '" was not successful: ' + status);
      }
    );
}

