﻿// map objects
var map;
var mgr;
var mapId;

jQuery.noConflict();
jQuery(document).ready(function()
{
    var f = function() { attachToSmartMap(true); };
    setTimeout(f, 5000);
});

function attachToSmartMap(firstLoad)
{
    // trying to match something like: dnn_ctr768_JetkeySmartMap_GMap1
    var matches = jQuery("div").filter(function()
    {
        return this.id.match(/dnn_ctr[0-9]+_JetkeySmartMap_GMap[0-9]+$/i);
    });

    if (jQuery(matches).size() == 1)
    {
        mapId = jQuery(matches).eq(0).attr("id");

        // save the reference to the existing map to a global variable
        map = eval(mapId);
    }

    if (firstLoad)
    {
        // add Google Earth plug-in support to the map
        map.addMapType(G_SATELLITE_3D_MAP);
        
        map.savePosition();
        mgr = new MarkerManager(map);

        // place the menu options
        var showAll = "<a href=\"javascript:void(0);\" onclick=\"showAll();\" title=\"Show All\">Show All</a>";
        var clearAll = "<a href=\"javascript:void(0);\" onclick=\"removeAll();\" title=\"Remove All\">Remove All</a>";
        var zoomToFit = "<a href=\"javascript:void(0);\" onclick=\"setBounds();\" title=\"Zoom to Fit\">Zoom to Fit</a>";
        var sep = "<span class=\"sep\">|</span>";
        var mapDiv = jQuery("#" + mapId);
        mapDiv.before("<div class=\"mapOptionsBar\">" + showAll + sep + clearAll + sep + zoomToFit + "</div>");
        
//        GEvent.addListener(map, "zoomend", function(oldLevel, newLevel)
//        {
//            showZoom();
//        });

        // Adapted from KML Map Loader by Mark A. Greenwood, 2008
        // http://www.dcs.shef.ac.uk/~mark/blog/blog_files/software/web/kmlmaploader/KMLMapLoader.js
        GEvent.addListener(map, "infowindowopen", function()
        {
            var divs = this.getContainer().getElementsByTagName("div");

            for (var n = 0; n < divs.length; ++n)
            {
                if (divs[n].id == "iw_kml")
                {
                    var imgs = divs[n].getElementsByTagName("img");

                    for (var j = 0; j < imgs.length; ++j)
                    {
                        var index = imgs[j].src.indexOf("/mapsatt");

                        if (index != -1) imgs[j].src = "http://maps.google.com" + imgs[j].src.substr(index);
                    }

                    this.updateCurrentTab(function(tab) { });
                }
            }
        });
        
        //showZoom();
    }
}

function createSmartMapMarker(latLng, html, markerFileUrl)
{
    var customIcon = new GIcon();
    customIcon.image = markerFileUrl;
    customIcon.iconSize = new GSize(20, 34);
    customIcon.iconAnchor = new GPoint(10, 34);
    customIcon.infoWindowAnchor = new GPoint(10, 0);

    var marker = new GMarker(latLng, customIcon);

    if (html && html != "")
    {
        GEvent.addListener(marker, "click", function()
        {
            marker.openInfoWindowHtml("<div class=\"markerWindow\">" + html + "</div>");
        });
    }

    return marker;
}

function addSmartMapMarker(marker, zoomLevel)
{
    mgr.addMarker(marker, zoomLevel);
}

function createSmartMapPolyline(color, width, opacity, encodedPoints, encodedLevels, zoomFactor, numLevels)
{
    var polyline = GPolyline.fromEncoded({color: color, 
                                          weight: width, 
                                          opacity: opacity, 
                                          points: encodedPoints, 
                                          levels: encodedLevels, 
                                          zoomFactor: zoomFactor,
                                          numLevels: numLevels
                                          });

    return polyline;
}

function addSmartMapPolyline(polyline)
{
     map.addOverlay(polyline);
}

function addSmartMapBottom(bottomHtmlVariableName)
{
    var bottom = jQuery("div[id*='sidebarBottom']");

    bottom.css("height", "400px");    
    bottom.addClass("gpx");
    bottom.append(bottomHtmlVariableName);
}

function removeSmartMapBottom(bottomHtmlVariableName)
{
    jQuery("table#" + bottomHtmlVariableName).remove();

    // if there are not more items in the bottom area, remove the height style
    var bottom = jQuery("div[id*='sidebarBottom']");
    
    if (jQuery(":has(table)", bottom).length <= 0)
    {
        bottom.css("height", ""); 
    }
}

function toggleSmartMapOverlay(overlayId)
{
    // make sure the reference to the map has been set
    if (!map)
    {
        attachToSmartMap(false);
    }

    // show the loading graphic
    document.getElementById("loading").style.display = "block";

    var checkbox = jQuery("input[type='checkbox'][id='cb" + overlayId + "']");
    var span = jQuery("span[id='sp" + overlayId + "']");

    // show the overlay if the checkbox was checked.  hide it otherwise.
    if (checkbox.attr("checked"))
    {
        eval("addSmartMapOverlay_" + overlayId + "();");
        span.attr("title", "Zoom to this overlay");
    }
    else
    {
        eval("removeSmartMapOverlay_" + overlayId + "();");
        span.attr("title", "Add this overlay to the map");
    }

    // refresh the marker manager
    mgr.refresh();

    // reset the bounds of the map based on which overlays are still visible
    setBounds();

    // hide the loading graphic
    document.getElementById("loading").style.display = "none";
}

function setBounds()
{
    // build the bounds variable
    var boundsVar = ""; //"bounds";
    var overlaysVisible = false;

    // iterate through each overlay
    jQuery("input[type='checkbox'][id^='cb']").each(function()
    {
        //var overlayId = jQuery(this).attr("id").replace(/cb/, "");
        //var i = jQuery(this).attr("index");

        var found = (jQuery(this).attr("checked"));

        boundsVar += (found ? "1" : "0");

        if (found)
        {
            overlaysVisible = true;
        }
    });
    
    // check if there are any markers or polylines anywhere on the map.
    // if not, center and zoom on initial values
    if (!overlaysVisible)
    {
        map.returnToSavedPosition();
    }
    else
    {
        getBoundsData(boundsVar);
    }

    // show the current zoom level
    //showZoom();
}

function getBoundsData(boundsVar)
{
    // get the max/min lat/lng
    jQuery.ajax({
        type: "GET",
        url: getBoundsUrl,
        cache: true,
        dataType: "script",
        data: "b=" + boundsVar + "&i=" + tabModuleId.toString(),
        success: boundsCallback
    });
}

function boundsCallback(data, textStatus)
{
    var bounds = eval(data);

    centerAndZoom(bounds);
}

function centerAndZoom(mapBounds)
{
    if (!mapBounds)
    {
        map.returnToSavedPosition();
        return;
    }

    var minLat = mapBounds[0];
    var maxLat = mapBounds[1];
    var minLng = mapBounds[2];
    var maxLng = mapBounds[3];

    if (minLat == 0 && maxLat == 0 && minLng == 0 && maxLng == 0)
    {
        map.returnToSavedPosition();
        return;
    }

    // reset the center point and zoom level
    map.setCenter(new GLatLng(0, 0), 0);

    // get the sw and ne corners of the rectangle
    var sw = new GLatLng(minLat, minLng);
    var ne = new GLatLng(maxLat, maxLng);

    // create the bounding box
    var bounds = new GLatLngBounds(sw, ne);

    // set the center point and zoom level based on the bounding box
    map.setZoom(map.getBoundsZoomLevel(bounds));
    map.setCenter(bounds.getCenter());
}

//function getOverlayBounds(overlayId)
//{
//    var checkbox = jQuery("input[type='checkbox'][id='cb" + overlayId + "']");
//    var count = jQuery("input[type='checkbox'][id^='cb']").length;
//    var index = checkbox.attr("index");
//       
//    var boundsVar = "bounds";

//    for (var i = 0; i < count; i++)
//    {
//        boundsVar += (i == index ? "1" : "0");
//    }

//    return eval(boundsVar);
//}

function zoomToOverlay(overlayId)
{
    // only do this if the checkbox is checked
    var checkbox = jQuery("input[type='checkbox'][id='cb" + overlayId + "']");

    if (checkbox.attr("checked"))
    {
        var count = jQuery("input[type='checkbox'][id^='cb']").length;
        var index = checkbox.attr("index");

        var boundsVar = "";

        for (var i = 0; i < count; i++)
        {
            boundsVar += (i == index ? "1" : "0");
        }

        getBoundsData(boundsVar);
    }
    else
    {
        checkbox.click();
    }
}

function showAll()
{
    jQuery("input[type='checkbox'][id^='cb']").each(function()
    {
        // call the click event on checkboxes that are not checked
        if (!jQuery(this).attr("checked"))
        {
            jQuery(this).click();
        }
    });
}

function removeAll()
{
    jQuery("input[type='checkbox'][id^='cb']").each(function()
    {
        // call the click event on checkboxes that are checked
        if (jQuery(this).attr("checked"))
        {
            jQuery(this).click();
        }
    });
}

function showZoom()
{
    //jQuery("#zl").html("Zoom: " + map.getZoom());
}