var ScH;
var ScW;
function LoadMap() {
    var markerId = getQSParameterByName("marker");
    Map = new CL_MAPS.BingMap();
    Map.LoadMap("myMap", "40.044", "-95.54", 4, 11); //div id, lat, long, zoom, zoomClose
    Map.LoadJsonPoints(CL_POINTS);
    if (markerId.length > 0) {
        Map.ZoomToMarkerById(markerId);
    }
}
function getQSParameterByName(name) {
    name = name.replace(/[\[]/, "\\\[").replace(/[\]]/, "\\\]");
    var regexS = "[\\?&]" + name + "=([^&#]*)";
    var regex = new RegExp(regexS);
    var results = regex.exec(window.location.href);
    if (results == null)
        return "";
    else
        return results[1];
}
$(document).ready(function() {
    ScH = $(document).height();
    ScW = $(document).width();
    $("#popup_overlay").click(function() { popMap(); });
    $(".ZoomLink").live('click', function() {
        Map.ZoomToMarkerByMapId($(this).attr("id"));
        return false;
    });
    $(".ResetMap").click(function() {
        Map.ResetLocationZoom();
    });
    $(".HideAllLayers").click(function() {
        Map.HideAllLayers();
        $(".map_nav").addClass("map_nav_empty");
        return false;
    });
    $(".ShowAllLayers").click(function() {
        Map.ShowAllLayers();
        $(".map_nav").removeClass("map_nav_empty");
        return false;
    });
    $(".typeCheckbox, .map_nav").click(function() {
        var ThisRef = $(this).attr("id");
        if ($(this).hasClass("map_nav_empty") == true) {
            $(this).removeClass("map_nav_empty");
            Map.ShowTypeLayer(this.id);
            return false;
        } else {
            $(this).addClass("map_nav_empty");
            Map.HideTypeLayer(this.id);
            return false;
        }
    });
});
CL_MAPS = {
    ImgDir: "",
    ClusterIcon: "cluster.png",
    ShapeListId: "ShapeLayers",
    BingMap: function() {
        //Initialize class variables
        this.map = null;
        this.Latitude = null;
        this.Longitude = null;
        this.ZoomLevel = null;
        this.ZoomCLose = null;
        this.points = [];
        this.shapes = new Object();
        this.shapesById = new Object();
        this.MarkerLayer = new VEShapeLayer();
        this.Layers = new Array();
        this.clusterOptions = new VEClusteringOptions();
        this.clusterIcon = new VECustomIconSpecification();

        //Load and Setup Map
        this.LoadMap = function(mapId, latitude, longitude, zoom, zoomClose) {
            //Setup Map
            this.Latitude = latitude;
            this.Longitude = longitude;
            this.ZoomLevel = zoom;
            this.ZoomClose = zoomClose;
            this.map = new VEMap(mapId);
            this.map.SetDashboardSize(VEDashboardSize.Small);
            this.map.LoadMap(new VELatLong(latitude, longitude), zoom, null, false);
            this.map.ShowMiniMap();
            this.map.HideScalebar();
            //Setup Clustering
            this.SetupClustering();

            //Setup Marker Layer
            this.MarkerLayer.SetTitle("Markers");
            this.MarkerLayer.SetDescription("All Markers");
            this.MarkerLayer.SetClusteringConfiguration(VEClusteringType.Grid, this.clusterOptions);
        };

        this.SetupClustering = function() {
            this.clusterIcon.CustomHTML = "<img src='" + CL_MAPS.ImgDir + CL_MAPS.ClusterIcon + "' class='cluster' alt='Multiple Locations'/>";
            this.clusterOptions.Icon = this.clusterIcon;
            this.clusterOptions.Callback = this.GenerateClusterPopup;
        };

        //Load multiple points from a JSON object
        this.LoadJsonPoints = function(points) {
            var point;
            for (var i = 0; i < points.length; i++) {
                point = points[i];
                this.LoadPoint(point.Name, point.ID, point.Summary, point.Latitude, point.Longitude, point.FeatureTypeID, point.FeatureType, point.Icon)
            }
            this.LoadTypeLayers();
        };

        //Load a point and add it to the proper shape layer
        this.LoadPoint = function(name, id, summary, latitude, longitude, featureTypeID, featureType, icon) {
            var icon = "<img src='" + CL_MAPS.ImgDir + icon + "' alt='" + name + "' />";
            var latlng = new VELatLong(latitude, longitude);
            var shape = new VEShape(VEShapeType.Pushpin, latlng);
            shape.SetCustomIcon(icon);
            shape.SetTitle(name);
            shape.SetDescription(summary);

            if (this.Layers[featureTypeID] == null) {
                this.CreateNewLayer(featureTypeID, featureType, icon)
            }
            this.Layers[featureTypeID].AddShape(shape);
            this.points.push(latlng);
            this.shapes[shape.GetID()] = shape;
            this.shapesById[id] = shape;
        };

        //Create a new layer which will contain all shapes of a given type
        this.CreateNewLayer = function(id, title, icon) {
            this.Layers[id] = new VEShapeLayer();
            this.Layers[id].SetTitle(title);
            this.Layers[id].SetClusteringConfiguration(VEClusteringType.Grid, this.clusterOptions);
        };

        this.LoadTypeLayers = function() {
            for (var i = 1; i < this.Layers.length; i++) {
                if (this.Layers[i] != null) {
                    this.map.AddShapeLayer(this.Layers[i]);
                }
            }
        };

        this.ShowTypeLayer = function(typeId) {
            this.Layers[typeId].Show();
        };

        this.HideTypeLayer = function(typeId) {
            this.Layers[typeId].Hide();
        };

        this.ShowAllLayers = function() {
            this.map.ShowAllShapeLayers();
        }

        this.HideAllLayers = function() {
            this.map.HideAllShapeLayers();
        }

        this.ResetLocationZoom = function() {
            this.map.SetCenterAndZoom(new VELatLong(this.Latitude, this.Longitude), this.ZoomLevel);
        }

        //Creates a list of locations in the popup of a clustered icon
        this.GenerateClusterPopup = function(clusters) {
            for (var i = 0; i < clusters.length; i++) {
                var cluster = clusters[i];
                var clusterShape = cluster.GetClusterShape();
                var cShapes = cluster.Shapes; //Get all shapes contained inside the cluster
                clusterShape.SetCustomIcon(cShapes[0].GetCustomIcon()); //Set the icon to the icon of the first shape
                var desc = "";
                var north = 1000;
                var west = -1000;
                var south = -1000;
                var east = 1000;
                for (var j = 0; j < cShapes.length; j++) {
                    var cur = cShapes[j];
                    var id = cur.GetID();
                    //Build up a list
                    desc = desc + "<a id='" + id + "' href='#' class='ZoomLink'>" + cur.GetTitle() + "</a><br/>";

                    if (cur.GetPoints()[0].Latitude < north)
                        north = cur.GetPoints()[0].Latitude;
                    if (cur.GetPoints()[0].Latitude > south)
                        south = cur.GetPoints()[0].Latitude;
                    if (cur.GetPoints()[0].Longitude > west)
                        west = cur.GetPoints()[0].Longitude;
                    if (cur.GetPoints()[0].Longitude < east)
                        east = cur.GetPoints()[0].Longitude;
                }
                desc = desc + "<br/><a href='javascript:ZoomToSquare(" + north + ", " + south + "," + east + "," + west + ")'>Zoom In</a>";
                clusterShape.SetDescription(desc); //Set the list to the description field
            }
        };

        this.ZoomToMarkerByMapId = function(id) {
            var shape = this.shapes[id];
            this.ZoomToMarker(shape);
        };

        this.ZoomToMarkerById = function(id) {
            var shape = this.shapesById[id];
            this.ZoomToMarker(shape);
        };

        this.ZoomToMarker = function(shape) {
            this.map.HideInfoBox(); //hide all info boxes
            if (shape != null) {
                this.map.SetCenterAndZoom(shape.GetIconAnchor(), this.ZoomClose);
                this.map.ShowInfoBox(shape);
            }
        };
        this.ZoomToSquare = function(north, south, east, west) {
            var points = new Array();
            points[0] = new VELatLong(north, east);
            points[1] = new VELatLong(south, west);
            this.map.SetMapView(points);
        };
    }
}

//Images for popup
function mainFnc(x) {
    var TheVal = $(x).html();
    var PosY = (TheVal * 100) - 100;
    //if (PosY >= 0) {
    if (PosY > 0) {
        var TheY = "-" + PosY + "px";
    } else {
        var TheY = PosY + "px";
    }
    $(x).siblings(".holder_images").children(".holder_images_inner").animate({ top: TheY }, "slow");

    return false;
}

function ZoomToSquare(north, south, east, west) {
    Map.ZoomToSquare(north, south, east, west);
}

function popMap() {
    ScH = $(document).height();
    ScW = $("body").innerWidth();
    $("body").append("<div class='map_pop'><div class='close'></div><iframe id='iframePOP' frameborder='0' height='485' marginheight='0' marginwidth='0' scrolling='no' src='http://www.contractlumber.com/Scripts/MapPop.php5?id=JustPop' width='1040' style='background-color: #FFB52A; border: 0; height: 485px; width: 1040px;'></iframe></div><div class='blockout'></div>");
    $("#map #myMap").addClass("myMappop");
    $(".blockout").height(ScH).width(ScW);
    ScH = $(window).height();
    var VertPos = (ScH - $(".map_pop").height()) / 2;
    $(".map_pop").css({ top: VertPos });
    $(".blockout, .close").click(function() {
        $(".blockout").remove();
        $(".map_pop").remove();
    });
}
