
var map = null;
var overlay = null;

//  Obtain the project details and display in a pop-up window.
function requestContent(langCd, marker, id) {
    var content = getProject(langCd, id, 0, 2);

    marker.openInfoWindowHtml(content, { maxWidth: 475 });
}

//  Get the projects matching the passed search criteria.
function getProjects(langCd, provinceId, clientId, initiativeId, projectId, mode, previewFlg) {
    var projectArray = $.ajax({
        url: "/initiatives/includes/projectFinder.asp",
        global: false,
        type: "GET",
        data: "langCd=" + langCd + "&pmode=1&provinceId=" + provinceId + "&clientId=" + clientId + "&projectId=" + projectId + "&initiativeId=" + initiativeId + "&mode=" + mode + "&previewFlg=" + previewFlg,
        dataType: "html",
        async: false
    }).responseText;
    eval(projectArray);
    return data;
}

//  Get a project detail for the pop-up bubble.
function getProject(langCd, projectId, clientid, mode) {
    var projectDetailTxt = $.ajax({
        url: "/initiatives/includes/projectFinder.asp",
        global: false,
        type: "GET",
        data: "langCd=" + langCd + "&pmode=2&projectId=" + projectId + "&clientid=" + clientid + "&mode=" + mode,
        dataType: "html",
        async: false
    }).responseText;
    return projectDetailTxt;
}

$(function() {$('#provinceSelectLst').change(function() {
    if ($('#provinceSelectLst').val())
    {
        var arrProvince = $('#provinceSelectLst').val().split(':');
        map.setCenter(new GLatLng(arrProvince[1], arrProvince[2]), parseInt(arrProvince[3]));
    }
    else
        map.setCenter(new GLatLng(59.0, -100.0), 3);
    });
});

(function() {
    var projects = null;
    //    var markerClusterer = null;
    var markers = [];
    var mapBounds = new GLatLngBounds(new GLatLng(23.9061240763, -180.0), new GLatLng(83.7349277973, -11.8746768079));
    var mapMinZoom = 4;
    var mapMaxZoom = 4;
    var opacity = 1;
    var langCd;

   /*
    * Full-screen Window Resize
    */
    function getWindowHeight() {
        if (self.innerHeight) return self.innerHeight;
        if (document.documentElement && document.documentElement.clientHeight)
            return document.documentElement.clientHeight;
        if (document.body) return document.body.clientHeight;
        return 0;
    }

    function getWindowWidth() {
        if (self.innerWidth) return self.innerWidth;
        if (document.documentElement && document.documentElement.clientWidth)
            return document.documentElement.clientWidth;
        if (document.body) return document.body.clientWidth;
        return 0;
    }

    function $(element) {
        return document.getElementById(element);
    }

    var AMC = {
        init: function(langCd, provinceId, clientId, initiativeId, projectId, mode, previewFlg) {
            if (GBrowserIsCompatible()) {
                var showInfoFlg = true;
                map = new GMap2(document.getElementById('map'));

                // Bug in the Google Maps: Copyright for Overlay is not correctly displayed.  IE6 also shows a bad French character.
                var gcr = GMapType.prototype.getCopyrights;
                GMapType.prototype.getCopyrights = function(bounds, zoom) {
                    var copyright = ["&copy;"].concat(gcr.call(this, bounds, zoom));
                    for (var i = 0; i < copyright.length; i++)
                        copyright[i] = copyright[i].toString().replace("é", "&eacute;");
                    return copyright;
                }

                //  If only one project center the map on it and use a small map control.
                if (projectId != '') {
                    var data = getProjects(langCd, provinceId, clientId, initiativeId, projectId, mode, previewFlg);

                    projects = data.projects;
                    map.setCenter(new GLatLng(projects[0].latitude, projects[0].longitude), 9);
                    map.addControl(new GSmallMapControl());
                    showInfoFlg = false;
                }
                else {
                    map.setCenter(new GLatLng(59.0, -100.0), map.getBoundsZoomLevel(mapBounds) + 1);
                    map.addControl(new GMapTypeControl());
                    map.removeMapType(G_HYBRID_MAP);
                    map.addControl(new GLargeMapControl3D());                     
                    map.addControl(new GOverviewMapControl());
                }
               var tilelayer = new GTileLayer(GCopyrightCollection(''), mapMinZoom, mapMaxZoom);
                var mercator = new GMercatorProjection(mapMaxZoom + 1);
                tilelayer.getTileUrl = function(tile, zoom) {
                if (map.getZoom() == 3 || map.getZoom() == 4 || map.getZoom() == 5 || map.getZoom() == 6 || map.getZoom() == 7) {
                        mapMinZoom = map.getZoom();
                        mapMaxZoom = mapMinZoom;
                        if (map.getZoom() == 3) {
                            if (langCd == 'fra')
                                mapBounds = new GLatLngBounds(new GLatLng(24.04065171, -180.0), new GLatLng(83.7259173261, -11.8787274676));
                            else
                                mapBounds = new GLatLngBounds(new GLatLng(24.0937023129, -180.0), new GLatLng(83.7259167666, -11.8787145301));
                        }
                        else if (map.getZoom() == 4) {
                            if (langCd == 'fra')
                                mapBounds = new GLatLngBounds(new GLatLng(23.9355103369, -180.0), new GLatLng(83.7349277973, -11.916128274));
                            else
                                mapBounds = new GLatLngBounds(new GLatLng(23.9061240763, -180.0), new GLatLng(83.7349277973, -11.8746768079));
                        }
                        else if (map.getZoom() == 5) {
                            if (langCd == 'fra')
                                mapBounds = new GLatLngBounds(new GLatLng(18.7597888127, -170.221040679), new GLatLng(76.6126745928, -41.0186074585));
                            else
                                mapBounds = new GLatLngBounds(new GLatLng(32.3852557477, -158.603328004), new GLatLng(78.0414989672, -40.1677642187));
                        }
                        else if (map.getZoom() == 6) {
                            if (langCd == 'fra')
                                mapBounds = new GLatLngBounds(new GLatLng(31.5908408936, -173.531099367), new GLatLng(83.1554440822, 178.155548915));
                            else
                                mapBounds = new GLatLngBounds(new GLatLng(29.9834773321, -172.447614262), new GLatLng(83.202953155, 179.083048203));
                        }
                        else if (map.getZoom() == 7) {
                            if (langCd == 'fra')
                                mapBounds = new GLatLngBounds(new GLatLng(39.2360993728, -165.525565208), new GLatLng(79.672698513, -47.0879516103));
                            else
                                mapBounds = new GLatLngBounds(new GLatLng(39.2360993728, -165.525565208), new GLatLng(79.672698513, -47.0879516103));
                        }
                    }
                    if ((zoom < mapMinZoom) || (zoom > mapMaxZoom)) {
                        return "/grfx/maps/none.gif";
                    }
                    var ymax = 1 << zoom;
                    var y = ymax - tile.y - 1;
                    var x = zoom - 1;
                    if (zoom >= 3 || zoom <= 7) {
                        if (zoom <= 4) {
                            var tileBounds = new GLatLngBounds(
                                   mercator.fromPixelToLatLng(new GPoint((tile.x) * 256, (tile.y + 1) * 256), zoom),
                                   mercator.fromPixelToLatLng(new GPoint((tile.x + 1) * 256, (tile.y) * 256), zoom)
                               );
                            if (mapBounds.intersects(tileBounds)) {
                                return "/grfx/maps/" + zoom + "/" + langCd + "/" + tile.x + "/" + y + ".png";
                            } else {
                                return "/grfx/maps/none.gif";
                            }
                        }
                        else
                            return "/grfx/maps/" + zoom + "/" + langCd + "/" + tile.x + "/" + y + ".png";
                    }
                    else
                        return "/grfx/maps/none.gif";
                }
                // IE 7-: support for PNG alpha channel
                // Unfortunately, the opacity for whole overlay is then not changeable, either or...
                tilelayer.isPng = function() { return true; };
                tilelayer.getOpacity = function() { return opacity; }
                overlay = new GTileLayerOverlay(tilelayer);
                GEvent.addListener(map, "maptypechanged", function() { 
                    var newMapType = map.getCurrentMapType().getName(); 

                    if (newMapType != 'Map' && newMapType != 'Plan')
                        map.removeOverlay(overlay);
                    else
                        map.addOverlay(overlay);
                }) 

                map.addOverlay(overlay);
                var loadingMsg = document.getElementById("loading");
                if (loadingMsg != null)
                    loadingMsg.style.visibility = "hidden";

                var theme = {
                        markerOptions: {icon: new GIcon({ image:            "/grfx/icons/blue_dot.png",
                                                 iconSize:         new GSize(32, 32),
                                                 iconAnchor:       new GPoint(16, 32),
                                                 infoWindowAnchor: new GPoint(16, 16),
                                                 infoShadowAnchor: new GPoint(16, 16)                             
                                                })},
                        clusterOptions: {icon: new GIcon({ image:            "/grfx/icons/icon_marker_cluster.png",
                                                 iconSize:         new GSize(26, 26),
                                                 iconAnchor:       new GPoint(13, 26),
                                                 infoWindowAnchor: new GPoint(13, 13),
                                                 infoShadowAnchor: new GPoint(13, 13)                             
                                                 }),
                                        labelClass: 'maptimize_cluster_0', 
                        labelOffset: null},
                                 
                        createMarker: function(marker) {
                            var options = theme.markerOptions;

                            if (showInfoFlg) {
                                if (langCd == 'fra')
                                    options.title = decodeHexEntity("Cliquer pour voir les d&#233;tails du projet");
                                else
                                    options.title = "Click for project details";
                            }
                            return new GMarker(marker.getGLatLng(), options);
                        },

                        createCluster: function(cluster) {
                            var options = theme.clusterOptions;

                            if (langCd == 'fra')
                                options.title = "Cliquez pour zoomer sur d'autres projets";
                            else
                                options.title = "Click to zoom in on more projects";
                            return new Maptimize.LabeledMarker(cluster.getGLatLng(), options);
                        }
                }
                var maptimizeMap = new Maptimize.Map(map, {theme: theme});
                if (showInfoFlg)
                    GEvent.addListener(maptimizeMap, 'markerClicked', function(marker) {
                        requestContent(langCd, marker.getGMarker(), marker.getId());
                    });

                maptimizeMap.setGroupingDistance(25);
                if (projectId != '') {
                    var conditions = new Maptimize.Condition({ProjectID: projectId});
                    maptimizeMap.setCondition(conditions);
                } else if (initiativeId != '') {
                    var conditions = new Maptimize.Condition({InitiativeID: initiativeId});
                    maptimizeMap.setCondition(conditions);
                }
              maptimizeMap.refresh();
            }

            function toggleClustering() {
                cluster.clusteringEnabled = !cluster.clusteringEnabled;
                cluster.refresh(true); //	true required to force a full update of the markers - otherwise the update would occur next time that the map is zoomed or the active markers change
            }
        },
        showMarkers: function(isInit, showInfoFlg, langCd) {
            showMarkers(isInit, showInfoFlg, langCd);
        }
    };

      /*  Not called */
      function showMarkers(init, showInfoFlg, langCd, clientid, mode) {
        markers = [];
        var icon = new GIcon(G_DEFAULT_ICON, "/grfx/icons/blue_dot.png");
        icon.shadow = null;
        icon.iconSize = new GSize(32, 32);

        var lg = projects.length;
        var j = 1;
	    var markerTtl;

        if (showInfoFlg) {
            if (langCd == 'fra')
                markerTtl = decodeHexEntity("Cliquer pour voir les d&#233;tails du projet");
            else
                markerTtl = "Click for project details";
        }
        for (var i = 0; i < lg; i++) {
            var latlng = new GLatLng(projects[i].latitude, projects[i].longitude);
            var marker = new GMarker(latlng, { icon: icon, title: markerTtl });

            //  If only one project then we are on the project detail page and we do not show the
            // pop-up.
            if (showInfoFlg) {
                var fn = markerClickFn(projects[i], latlng, langCd, clientid, mode);
                GEvent.addListener(marker, "click", fn);
            }
            markers.push(marker);
            j++;
        }
        cluster = new ClusterMarker(map, { markers: markers });
        cluster.clusterMarkerIcon = new GIcon(G_DEFAULT_ICON, "/grfx/icons/icon_marker_cluster.png");
        cluster.clusterMarkerIcon.iconSize = new GSize(26, 26);
        cluster.clusterMarkerIcon.shadow = null;
        if (langCd == 'fra')
            cluster.clusterMarkerTitle = "Cliquez pour zoomer sur d'autres projets";
        else
            cluster.clusterMarkerTitle = "Click to zoom in on more projects";
        cluster.refresh();
        var loadingMsg = document.getElementById("loading");
        if (loadingMsg != null)
            loadingMsg.style.visibility = "hidden";
    }

    function markerClickFn(project, latlng, langCd, clientid, mode) {
        return function() {
            var infoHtml = getProject(langCd, project.projectId, clientid, mode);
            if (infoHtml != '')
                map.openInfoWindowHtml(latlng, infoHtml, { maxWidth: 475 });
        };
    }
    window.AMC = AMC || window.AMC;

})();