﻿/*var placeLayer = [
{
'id':'1199',
'name':'Parkdale Fire Station',
'img':'http://bno-dev-inet3:6095/crhp-public/images/thumbnails/1199_thumb.jpg',
'posn':[45.399780, -75.728940],
'location':'blah_blah_blah'
}
];*/

var map = null;
var panorama = null;
var markerClusterer = null;
var markers = [];
var activeInfoWindow = null;
var searchBounds = null;
var startLatLng;
var endLatLng;

var searchRectangle;
var resultsRectangle;
var resultsCircle;

var radiusCenter;
var searchCircle;
var radiusControls;
var radiusListener;
var radius;

var markerShadow = new google.maps.MarkerImage('/hpimages/hp-mapmarker-shadow-2.png', new google.maps.Size(39, 33), new google.maps.Point(-6, 1), null, null);
var markerImage = new google.maps.MarkerImage('/hpimages/hp-mapmarker-2.png', new google.maps.Size(22, 33), null, null, null);

/*MarkerImage(url:string, size?:Size, origin?:Point, anchor?:Point, scaledSize?:Size)*/

var userLat = null;
var userLng = null;


function foundLocation(position) {
    userLat = position.coords.latitude;
    userLng = position.coords.longitude;
        
    if (map.getDiv().id == "map_search") {

        radiusCenter = new google.maps.LatLng(userLat, userLng);
        radius = 10;

        var markerOptions = {
            map: map,
            position: radiusCenter,
            title: "You"
        };

        var marker = new google.maps.Marker(markerOptions);
        markers.push(marker);

        if (searchCircle) searchCircle.setMap(null);
        searchCircle = new google.maps.Circle({
            map: map,
            radius: radius * 1000,
            center: radiusCenter,
            fillOpacity: 0.5
            
        });
        map.setCenter(new google.maps.LatLng(userLat, userLng));
        map.fitBounds(searchCircle.getBounds());

        $('#btnMapSearch').removeAttr('disabled');
        $('#btnMapSearch').removeClass('disabled');
    
    }
}
function noLocation() {
    //alert('Could not find location');
}

// Initializes the map and places the markers
function initializeMap(mapId, zoomLevel) {
    var cancelGeoloc = true;
    if (navigator && navigator.geolocation) {
        cancelGeoloc = false;
        navigator.geolocation.getCurrentPosition(foundLocation, noLocation);
        
    }
        


    /*** Basic Map Setup ***/
    // Define the map with some basic settings
    map = new google.maps.Map(document.getElementById(mapId), {
        mapTypeControl: true,
        mapTypeControlOptions: { style: google.maps.MapTypeControlStyle.DROPDOWN_MENU },
        navigationControl: true,
        navigationControlOptions: { style: (isMobile ? google.maps.NavigationControlStyle.ANDROID : google.maps.NavigationControlStyle.DEFAULT) },
        streetViewControl: mapId != "map_search",
        mapTypeId: google.maps.MapTypeId.ROADMAP
    });
    var bounds = new google.maps.LatLngBounds();

    panorama = map.getStreetView();

    // Handle the different map types
    if (mapId == "map_results") {

        for (var i = 0; i < placeLayer.length; i++) {
            var place = placeLayer[i];
            var latlng = new google.maps.LatLng(place["posn"][0], place["posn"][1]);
            bounds.extend(latlng);
            makePopupMarker(place);
        }
                
    }
    else if (mapId == "map_place" && placeLayer.length > 0) {
        makeMarker(placeLayer[0]);
        zoomLevel = 14;
        panorama.set('addressControl', false);
    }
    else if (mapId == "map_search") {
    
    }

    if (mapId != "map_place") {

        // Create a div to hold the control.
        var radiusDiv = document.createElement('DIV');
        radiusDiv.setAttribute('id', 'radiusDiv');
        
        // Create the div for the border
        var radiusUI = document.createElement('DIV');
        radiusUI.setAttribute('id', 'radiusUI');
        radiusUI.title = 'Click to define the center point for a search';
        radiusDiv.appendChild(radiusUI);

        // Create the div for the inner control
        var radiusText = document.createElement('DIV');
        radiusText.setAttribute('id', 'radiusText');
        radiusText.innerHTML = '<strong>(( km ))</strong>';
        radiusUI.appendChild(radiusText);

        var radiusListUI = document.createElement('DIV')
        radiusListUI.setAttribute('id', 'radiusListUI');

        var radiusList = document.createElement('UL');
        radiusList.setAttribute('id', 'radiusList');
        
        var radiusList1K = document.createElement('LI');
        var radiusList5K = document.createElement('LI');
        var radiusList10K = document.createElement('LI');
        var radiusList25K = document.createElement('LI');
        var radiusList50K = document.createElement('LI');
        var radiusList100K = document.createElement('LI');
        
        // The naming convention's a bit confusing here because we're showing the user the diameter (not the radius)
        radiusList1K.innerHTML = "2km";
        radiusList5K.innerHTML = "10km";
        radiusList10K.innerHTML = "20km";
        radiusList25K.innerHTML = "50km";
        radiusList50K.innerHTML = "100km";
        radiusList100K.innerHTML = "200km";

        radiusList.appendChild(radiusList1K);
        radiusList.appendChild(radiusList5K);
        radiusList.appendChild(radiusList10K);
        radiusList.appendChild(radiusList25K);
        radiusList.appendChild(radiusList50K);
        radiusList.appendChild(radiusList100K);

        radiusListUI.appendChild(radiusList);
        radiusDiv.appendChild(radiusListUI);

        google.maps.event.addDomListener(radiusDiv, 'click', function() {
            $('#radiusListUI').toggle();
        });

        google.maps.event.addDomListener(radiusText, 'click', function() {
            disableRadius();
        });

        google.maps.event.addDomListener(radiusList1K, 'click', function() {
            enableRadius(1);
        });

        google.maps.event.addDomListener(radiusList5K, 'click', function() {
            enableRadius(5);
        });

        google.maps.event.addDomListener(radiusList10K, 'click', function() {
            enableRadius(10);
        });

        google.maps.event.addDomListener(radiusList25K, 'click', function() {
            enableRadius(25);
        });

        google.maps.event.addDomListener(radiusList50K, 'click', function() {
            enableRadius(50);
        });

        google.maps.event.addDomListener(radiusList100K, 'click', function() {
            enableRadius(100);
        });

        map.controls[google.maps.ControlPosition.TOP_RIGHT].push(radiusDiv);
        
        /*
        if (!cancelGeoloc) {

            // Create a div to hold the control.
            var geolocDiv = document.createElement('DIV');
            geolocDiv.setAttribute('id', 'geolocDiv');

            // Create the div for the border
            var geolocUI = document.createElement('DIV');
            geolocUI.setAttribute('id', 'geolocUI');
            geolocUI.title = 'Click to center a search on your location';
            geolocDiv.appendChild(geolocUI);

            // Create the div for the inner control
            var geolocText = document.createElement('DIV');
            geolocText.setAttribute('id', 'geolocText');
            geolocText.innerHTML = '<strong>( Me )</strong>';
            geolocUI.appendChild(geolocText);


            map.controls[google.maps.ControlPosition.TOP_RIGHT].push(geolocDiv);

            google.maps.event.addDomListener(geolocDiv, 'click', function() {
            if (userLat != null && userLng != null) {
            var markerOptions = {
            map: map,
            position: new google.maps.LatLng(userLat, userLng),
            title: "You"
            };

                    var marker = new google.maps.Marker(markerOptions);
            markers.push(marker);

                    if (resultsCircle) resultsCircle.setMap(null);
            resultsCircle = new google.maps.Circle({
            map: map,
            radius: 10000,
            center: new google.maps.LatLng(userLat, userLng),
            fillOpacity: 0.0,
            strokeColor: "#ce2d01"
            });
            map.setCenter(new google.maps.LatLng(userLat, userLng));
            map.fitBounds(resultsCircle.getBounds());
            }

            });
        }*/
    }
    
    // If we have coords from an Area search, draw the rectangle
    if (typeof neLat != 'undefined' && typeof neLng != 'undefined' && typeof swLat != 'undefined' && typeof swLng != 'undefined') {

        if (resultsRectangle) resultsRectangle.setMap(null);
        resultsRectangle = new google.maps.Rectangle({
            map: map,
            bounds: new google.maps.LatLngBounds(new google.maps.LatLng(swLat, swLng), new google.maps.LatLng(neLat, neLng)),
            strokeColor: "#ce2d01",
            fillOpacity: 0.0
        });
        map.fitBounds(resultsRectangle.getBounds());
    }
    // If we have coords from a Radius search, draw the circle
    else if (typeof rad != 'undefined' && typeof cLat != 'undefined' && typeof cLng != 'undefined') {
        if (resultsCircle) resultsCircle.setMap(null);
        resultsCircle = new google.maps.Circle({
            map: map,
            radius: rad * 1000,
            center: new google.maps.LatLng(cLat, cLng),
            fillOpacity: 0.0,
            strokeColor: "#ce2d01"
        });
        map.fitBounds(resultsCircle.getBounds());
    }else{
        // If we've been passed a zoom, use it, otherwise fit the zoom to the markers
        if (zoomLevel != null)
            map.setZoom(zoomLevel);
        else
            map.fitBounds(bounds);
    }
    
    centerMap();

    

    // Cluster the markers
    markerClusterer = new MarkerClusterer(map, markers, {
        maxZoom: 12,
        gridSize: 50,
        styles: null
    });
    /***********************/

    /*** Set up DragZoom ***/
    // Define the style for the box
    map.enableKeyDragZoom({
        boxStyle: {
            border: "2px solid #ce2d01",
            opacity: 0.5
        }
    });

    var dz = map.getDragZoomObject();

    google.maps.event.addListener(dz, 'activate', function() {

    });

    // Null the searchBounds when we start defining a new rectangle
    google.maps.event.addListener(dz, 'dragstart', function(latlng) {
        searchBounds = null;
        disableRadius();
    });

    google.maps.event.addListener(dz, 'drag', function(start, end) {

    });

    google.maps.event.addListener(dz, 'dragend', function(bnds) {

        // Set the searchBounds for the search button to use (in SubmitSearchCoordinates)
        searchBounds = bnds;

        // Enable the search button
        $('#btnMapSearch').removeAttr('disabled');
        $('#btnMapSearch').removeClass('disabled');
        
        

        // Kill the previous rectangle (and circle if one exists)
        if (searchRectangle) searchRectangle.setMap(null);
        
        // Define the new rectangle based on the bounds
        searchRectangle = new google.maps.Rectangle({
            map: map,
            bounds: bnds
        });
    });

    google.maps.event.addListener(dz, 'deactivate', function() {
    });
    /***********************/
   
}

function enableRadius(rad) {
    
    map.setOptions({ draggableCursor: 'crosshair' });

    $('#radiusUI').css('border-color', '#ce2d01');
    $('#radiusDiv').css('color', '#ce2d01');
    $('#radiusText').html('( ' + rad*2 + 'km )');
    
    radius = rad;

    radiusListener = google.maps.event.addListener(map, 'click', function(event) {

        // Enable the search button
        $('#btnMapSearch').removeAttr('disabled');
        $('#btnMapSearch').removeClass('disabled');
                
        radiusCenter = event.latLng;

        if (searchCircle) searchCircle.setMap(null);
        if (searchRectangle) searchRectangle.setMap(null);
        searchCircle = new google.maps.Circle({
            map: map,
            radius: rad * 1000,
            center: event.latLng,
            fillOpacity: 0.5

        });

        map.fitBounds(searchCircle.getBounds());
    });

}

function disableRadius() {
    
    // Disable the search button
    $('#btnMapSearch').attr('disabled', 'disabled');
    $('#btnMapSearch').addClass('disabled');

    $('#radiusUI').css('border-color', '#000');
    $('#radiusDiv').css('color', '#000');
    $('#radiusText').html('(( km ))');
    map.setOptions({ draggableCursor: '' });

    if(searchCircle) searchCircle.setMap(null);

    if(radiusListener) google.maps.event.removeListener(radiusListener);
    
    radiusCenter = null;
        

}

// Called from the search button that accompanies the map - requires searchBounds to be defined
function SubmitSearchCoordinates() {
       
    var dir;
    if (location.href.indexOf("/en/") >= 0)
        dir = "/en/";
    else
        dir = "/fr/";
    
    if (radiusCenter != null && radius != null) {    
        //m=4: Radius Search    
        window.location = dir + "results-resultats.aspx?m=4&r=" + radius + "&cLat=" + radiusCenter.lat() + "&cLng=" + radiusCenter.lng();
    }
    else if (searchBounds != null) {
        //m=3: Area Search    
        window.location = dir + "results-resultats.aspx?m=3&neLat=" + searchBounds.getNorthEast().lat() + "&neLng=" + searchBounds.getNorthEast().lng() + "&swLat=" + searchBounds.getSouthWest().lat() + "&swLng=" + searchBounds.getSouthWest().lng();
    }
}

/** Map Utilities **/

function centerMap() {
    if (markers != null && markers.length > 0)
        map.setCenter(markers[markers.length - 1].getPosition());
    else
        map.setCenter(new google.maps.LatLng(60, -95));
}

function clearMarkers() {
    if (markers) {
        for (i in markers) {
            markers[i].setMap(null);
        }
    }
}

function clearOverlays() {
    while (overlays[0]) {
        overlays.pop().setMap(null);
    }
}

function clearClusters(e) {
    e.preventDefault();
    e.stopPropagation();
    markerClusterer.clearMarkers();
}

function makeMarker(place) {


    /*function addMarker(point) {
        var icon = new GIcon();
        icon.image = "images/hp-mapmarker.png";
        icon.shadow = "images/shadow-hp-mapmarker.png";
        icon.iconSize = new GSize(30.0, 46.0);
        icon.shadowSize = new GSize(54.0, 46.0);
        icon.iconAnchor = new GPoint(15.0, 23.0);
        icon.infoWindowAnchor = new GPoint(15.0, 23.0);
            
        map.addOverlay(new GMarker(point, icon));
    }*/


    var markerOptions = {
        map: map,
        position: new google.maps.LatLng(place["posn"][0], place["posn"][1]),
        title: place["name"],
        icon: markerImage,
        shadow: markerShadow
    };

    var marker = new google.maps.Marker(markerOptions);
    markers.push(marker);

}

function makePopupMarker(place) {
    var markerOptions = {
        map: map,
        position: new google.maps.LatLng(place["posn"][0], place["posn"][1]),
        title: place["name"],
        icon: markerImage,
        shadow: markerShadow
    };

    var marker = new google.maps.Marker(markerOptions);
    markers.push(marker);

    var pageUrl = "";
    if (isMobile)
        pageUrl = "mobile.aspx?mm=page&";
    else
        pageUrl = "rep-reg/place-lieu.aspx?";

    var contentString = '<div class="mapPopup">' +
                            '<img height="50px" width="50px" class="" src="' + place["img"] + '"/>' +
                            '<a href="' + pageUrl + 'id=' + place["id"] + '">' + place["name"] + '</a>' +
                            '<p>' + place["location"] + '</p>' +
                        '</div>';
    var infowindow = new google.maps.InfoWindow({
        content: contentString
    });

    google.maps.event.addListener(marker, 'click', function() {
        if (activeInfoWindow != null)
            activeInfoWindow.close();
        infowindow.open(map, marker);
        activeInfoWindow = infowindow;
    });

    $('#map_' + place["id"]).bind("click", function() {
        if (activeInfoWindow != null)
            activeInfoWindow.close();
        infowindow.open(map, marker);
        activeInfoWindow = infowindow;
    });
}
