﻿var geocoder;
var map;
function initialize() {
    var latlng = new google.maps.LatLng(45.531681, -73.578165);
    geocoder = new google.maps.Geocoder();
    var myOptions = {
        backgroundColor: "#d23302",
        zoom: 13,
        center: latlng,
        mapTypeControl: false,
        mapTypeId: google.maps.MapTypeId.ROADMAP
    };
    map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
}


function codeClassifiedAddresses(csvListOfIds) {

    $.getJSON("GeoLocatorTool.aspx", { q: csvListOfIds },
                                function(data) {
                                    codeStaticAddresses(data);
                                });




}

function codeStaticAddresses(jSONData) {
    var latLongs = [0, 0, 0, 0];
    var myKey = "ABQIAAAAJ-sG_HhNeGZ-M2olwpWZ7xRjdLrM5CmW4huc_vg41vV-g7u2kxQxgGlPXNYn0WfroUvW2lf-UjnKJg";
    var totalAddressCount = jSONData.GeoAds.length;
    var treatedAddressCount = 0;

    for (var i = 0; i < jSONData.GeoAds.length; i++) {

        if (jSONData.GeoAds[i].Lat != 0 && jSONData.GeoAds[i].Lng != 0) {
            createMapMarker(jSONData.GeoAds[i].Lat, jSONData.GeoAds[i].Lng, jSONData.GeoAds[i].PostalCodeDetails);

            if (jSONData.GeoAds[i].Lat > latLongs[0] || latLongs[0] == 0) { latLongs[0] = jSONData.GeoAds[i].Lat; }
            if (jSONData.GeoAds[i].Lat < latLongs[2] || latLongs[2] == 0) { latLongs[2] = jSONData.GeoAds[i].Lat; }
            if (jSONData.GeoAds[i].Lng > latLongs[1] || latLongs[1] == 0) { latLongs[1] = jSONData.GeoAds[i].Lng; }
            if (jSONData.GeoAds[i].Lng < latLongs[3] || latLongs[3] == 0) { latLongs[3] = jSONData.GeoAds[i].Lng; }
            
        }
        else {
            var url = "http://maps.google.com/maps/geo?q=" + jSONData.GeoAds[i].PostalCode + "&output=json&sensor=false&key=" + myKey + "&gl=ca&callback=?";

            $.getJSON(url,
            function(data) {
                if (data.Status.code == "200") {

                    var curLat = data.Placemark[0].Point.coordinates[1];
                    var curLng = data.Placemark[0].Point.coordinates[0];

                    // Update the postal code with the lat-lng value
                    updatePostalCodeWithGeoData(data.name, curLat, curLng);

                    var curLatLong = new google.maps.LatLng(curLat, curLng);
                    var marker = new google.maps.Marker({
                        map: map,
                        position: curLatLong,
                        clickable: true
                    });

                    addInfoWindow(jSONData, marker, data.name);

                    if (curLat > latLongs[0] || latLongs[0] == 0) { latLongs[0] = curLat; }
                    if (curLat < latLongs[2] || latLongs[2] == 0) { latLongs[2] = curLat; }
                    if (curLng > latLongs[1] || latLongs[1] == 0) { latLongs[1] = curLng; }
                    if (curLng < latLongs[3] || latLongs[3] == 0) { latLongs[3] = curLng; }

                }
                treatedAddressCount++;
                if (totalAddressCount == treatedAddressCount) {
                    map.fitBounds(new google.maps.LatLngBounds(new google.maps.LatLng(latLongs[2], latLongs[3]), new google.maps.LatLng(latLongs[0], latLongs[1])));
                }
            });

        } // if

    } // for

    map.fitBounds(new google.maps.LatLngBounds(new google.maps.LatLng(latLongs[2], latLongs[3]), new google.maps.LatLng(latLongs[0], latLongs[1])));

} // function




function createMapMarker(latValue, lngValue, adsText) {
    if (adsText.length > 0) {
    
        // Concatinate the text together
        var infoWindowContent = "";
        for (var i = 0; i < adsText.length; i++) {
            if (infoWindowContent.length > 0) {
                infoWindowContent = infoWindowContent + "<hr />";
            }
            infoWindowContent = infoWindowContent + adsText[i].AdText;
        }
        
        // Create the info window
        var infowindow = new google.maps.InfoWindow({
            content: "<div class=\"MapAdText\">" + infoWindowContent + "</div>"
        });

        var curLatLong = new google.maps.LatLng(latValue, lngValue);

        // Create the marker
        var marker = new google.maps.Marker({
            map: map,
            position: curLatLong,
            clickable: true
        });
        
        // Add the info window to the map
        google.maps.event.addListener(marker, 'click', function() {
            infowindow.open(map, marker);
        });
    }
}



function updatePostalCodeWithGeoData(postalCode, latValue, lngValue) {
    var url = "GeoLocatorTool.aspx";
    $.post(url, { PostalCodeIdToUpdate: postalCode, lat: latValue, lng: lngValue });
}




function addInfoWindow(jSONData, marker, postalCode) {
    for (var i = 0; i < jSONData.GeoAds.length; i++) {
        if (jSONData.GeoAds[i].PostalCode == postalCode && jSONData.GeoAds[i].Lat == 0 && jSONData.GeoAds[i].Lng == 0) {
            var infoWindowContent = "";
            for (var j = 0; j < jSONData.GeoAds[i].PostalCodeDetails.length; j++) {
                if (infoWindowContent.length > 0) {
                    infoWindowContent = infoWindowContent + "<hr />";
                }
                infoWindowContent = infoWindowContent + jSONData.GeoAds[i].PostalCodeDetails[j].AdText;
            }
            var infowindow = new google.maps.InfoWindow({
                content: "<div class=\"MapAdText\">" + infoWindowContent + "</div>"
            });


            google.maps.event.addListener(marker, 'click', function() {
                infowindow.open(map, marker);
            });

        }
    }
    return true;
}





function codeDynamicAddress() {
    var addresses = ["H2S 2S9", "H2T 3C7", "H3B 1A5", "H4T 1M8"];

    var latMin = 0;
    var latMax = 0;
    var lngMin = 0;
    var lngMax = 0;

    for (var i = 0; i < addresses.length; i++) {
        if (geocoder) {
            geocoder.geocode({ 'address': addresses[i] }, function(results, status) {
                if (status == google.maps.GeocoderStatus.OK) {
                    //map.setCenter(results[0].geometry.location);
                    var marker = new google.maps.Marker({
                        map: map,
                        position: results[0].geometry.location
                    });

                    if (results[0].geometry.location.lat() > latMax || latMax == 0) { latMax = results[0].geometry.location.lat(); }

                    if (results[0].geometry.location.lat() < latMin || latMin == 0) { latMin = results[0].geometry.location.lat(); }

                    if (results[0].geometry.location.lng() > lngMax || lngMax == 0) { lngMax = results[0].geometry.location.lng(); }

                    if (results[0].geometry.location.lng() < lngMin || lngMin == 0) { lngMin = results[0].geometry.location.lng(); }

                    /*
                    if (i == addresses.length - 1) {
                    alert("latMax = " + latMax + "; latMin = " + latMin + "; lngMax = " + lngMax + "; lngMin = " + lngMin);
                    map.fitBounds(new google.maps.LatLngBounds(new google.maps.LatLng(latMax, lngMax), new google.maps.LatLng(latMin, lngMin)));
                    map.setCenter(new google.maps.LatLng((latMin + lngMin) / 2, (latMax + lngMax) / 2));                
                    }
                    */

                } else {
                    alert("Geocode was not successful for the following reason: " + status);
                }
            });
        }
    }

}