﻿// Requires jquery-1.3.2.min.js

var pushPinJSONPath = '/DRHorton/MapService.svc/pushpins';
var communityJSONPath = '/DRHorton/MapService.svc/communities';
var map;
var layer;
var pushpins = new Array();
var pinclusters = new Array();
var hoverTimeout;
var clusterPinHeaderString = "Communities:";
var clusterPinZoomInString = "There are {0} communities near here.";

function GetMap(lat, lng, zoom, divName, clusterHeaderString, clusterZoomInString)      
{
    
    map = new VEMap(divName);
    
    if (clusterHeaderString != '')
        clusterPinHeaderString = clusterHeaderString;
    if (clusterZoomInString != '')
        clusterPinZoomInString = clusterZoomInString;
    
    var latLng = new VELatLong(lat, lng);
    
    map.SetDashboardSize(VEDashboardSize.Small);
    map.LoadMap();
    layer = new VEShapeLayer();
    map.AddShapeLayer(layer);
    layer.SetTitle("PushPins");
    
    var options = new VEClusteringOptions();
    var customIcon = new VECustomIconSpecification();
    options.Icon = customIcon;
    options.Callback = clusteringCallback;            
    layer.SetClusteringConfiguration(VEClusteringType.Grid, options);

    //center and zoom before attaching events so they don't fire unless the
    //user is zooming
    map.SetCenterAndZoom(latLng, zoom);

    map.AttachEvent("onclick", mouseClickHandler);
    map.AttachEvent("onmouseover", loadPushPinData);
    map.AttachEvent("onendzoom", endZoomHandler);
    map.AttachEvent("onendpan", endPanHandler);
    //map.AttachEvent("onmousewheel", mouseWheelHandler);

    loadPushPins();
    
    return map;
}

function mouseWheelHandler() {
//Returning true makes the Mouse Wheel NOT affect the Map
    return true;
}

function starthovertimeout()
{
    
}

function endZoomHandler() 
{
    showPins();
    reloadgrid();
}

function showPins() {
    var rect = map.GetMapView();
    
    var left = rect.TopLeftLatLong.Latitude;
    var right = rect.BottomRightLatLong.Latitude;

    var top = rect.TopLeftLatLong.Longitude;
    var bottom = rect.BottomRightLatLong.Longitude;
    
    var pins = new Array();

    for (i = 0; i < pushpins.length; i++) {
        var pushpin = pushpins[i];
        var veShape = pushpin.veShape;
        var shapeID = veShape.GetID();
        if (shapeID) {
            continue;
        }
        if (pushpin.latitude <= left && pushpin.latitude >= right && pushpin.longitude >= top && pushpin.longitude <= bottom) {
            pins.push(veShape);
        }
    }
    
    layer.AddShape(pins);
}

function endPanHandler() 
{
    showPins();
    reloadgrid();
}

function mouseClickHandler(e) {
    if (e.elementID != null) {
        var shape = map.GetShapeByID(e.elementID);
        // Rob - 11/1/2009 - Added undefined check to eliminate clickable cluster icons
        if (typeof (shape.URL) != "undefined") {
            window.location = shape.URL;
        }
    }
}


function reloadgrid() {
    var view = map.GetMapView();
    var top = view.TopLeftLatLong.Latitude;
    var bottom = view.BottomRightLatLong.Latitude;
    var left = view.TopLeftLatLong.Longitude;
    var right = view.BottomRightLatLong.Longitude;

    try 
    {
        /* Refresh Grid Control */
        RefreshControl(top, right, bottom, left);
    } catch (e) { };
}

function loadPushPinData(e)
{
    if (e.elementID == null)
        return;

    var communityId;
    var IsCluster = false;
    
    var shape = map.GetShapeByID(e.elementID);
    var curID = shape.GetID();
    
    // Check if Shape is Single Item or Cluster
    for (j = 0; j < pinclusters.length; ++j) 
    {
        if (curID == pinclusters[j].shape.GetID()) 
        {
            var kid = pinclusters[j].child;
            var divLH = 12;
            var divH = (kid.length > 10) ? (10 * divLH) : (kid.length * divLH);
            var anchors  = "<div style='position: relative; height: " + (divH+60) + "px; border: solid 0px blue;'>";
                anchors += "<div style='position: relative; border: solid 0px red; height: " + (divH + divLH) + "px; /height: " + divH + "px;' max-height: 150px;>";
                anchors += "<span style='font-size: 10px; font-weight: normal;'><b>" + clusterPinHeaderString + "</b><br />";
            var communitiesCnt = "";
            var description = "&nbsp;";
            
            for (k = 0; k < 10 && k < kid.length; ++k) 
            {
                for (i = 0; i < pushpins.length; i++) {
                    var pushpin = pushpins[i];
                    if (pushpin.veShape.GetID() == kid[k].GetID()) {
                        anchors += "<span style='margin-left: 10px;'>" + (k + 1) + ".&nbsp;<a href = '" + pushpin.url + "'>" + pushpin.communityname + "</a></span><br />";
                        break;
                    }
                }
            }
            if (kid.length > 10)
                anchors += "<span style='margin-left: 10px;'>...</span><br />";

            //Moved closing tags here so that "Click to zoom" link displays correctly on popup
            anchors += "</span></div></div>"; 

            if (kid.length > 1) {
                var latLongArray = FindBoundingRectangle(kid);
                communitiesCnt = "<div style='position: relative; border:solid 0px green; padding-top: 0px; height:30px; font-weight: normal; width: 230px;'><a href='#' onClick='zoomMapForRectangle(" + latLongArray[0].Latitude + ", " + latLongArray[0].Longitude + ", " + latLongArray[1].Latitude + ", " + latLongArray[1].Longitude + "); return false;'>" + clusterPinZoomInString.replace("{0}", kid.length) + "</a></div>";
                anchors += communitiesCnt;
            }

            shape.SetTitle(anchors);
            shape.SetDescription(description);             

            IsCluster = true;
            break;
        }
    }


    // Get's Data for a Single Item Pushpin
    if (!IsCluster) {
        for (i = 0; i < pushpins.length; i++) {
            var pushpin = pushpins[i];
            var veShape = pushpin.veShape;
            var shapeID = veShape.GetID();

            if (shapeID == shape.GetID()) {
                if (pushpin.title == null) {
                    communityId = pushpin.communityid;
                    $.ajaxSetup({ cache: false });
                    $.getJSON(communityJSONPath + "/" + communityId,
                        function(json, textStatus) {
                            if (textStatus != "success") {
                                // Something bad happened
                                alert(textStatus);
                            }

                            var title = "";
                            var description = "";
                            var details = "";
                            var isQuickMoveIns = "";

                            if (json.qc > 0) {
                                isQuickMoveIns = "<a href='" + json.qu + "' class='PinQuickMoveIn'>Quick Move-In Homes (" + json.qc + ")</a>";
                            }

                            if (json.a1 && json.a1 != null && json.a1.length > 0) {
                                details += json.a1 + "<br />";
                            }

                            if (json.a2 && json.a2 != null && json.a2.length > 0) {
                                details += json.a2 + "<br />";
                            }

                            details += json.c + ", " + json.s + "<br />";

                            if (json.ph && json.ph != null && json.ph.length > 0) {
                                details += "<br />" + json.ph + "<br />";
                            }

                            details += json.ht + "<br />";
                            if (json.pw == "pleaseCall") {
                                details += "Please Call<br />";
                            }
                            else {
                                details += "Starting from the " + json.p + "<br />";
                            }

                            if (json.nm != null && json.nm.length > 0) {
                                var pushpinImageUrl = imagePath + "image_not_available.png";
                                if (json.tu != null && json.tu.length > 0) {
                                    pushpinImageUrl = json.tu + "?width=125&height=100";
                                }

                                title = "<div class='pushpinImageWrapper'><a href='" + json.cu + "'><img class='pushpinImage' src='" + pushpinImageUrl + "' /></a></div>";
                                title = title + "<a href='" + json.cu + "'>" + json.nm + "</a>";
                                description = "<div class='pushpinDetailQMIWrapper'><div class='pushpinDetails'>" + details + "</div><div class='pushpinQMIs'>" + isQuickMoveIns + "</div></div>";

                            }

                            pushpin.title = title;
                            pushpin.description = description;

                            $('#mTitle' + communityId + '_Content').html(pushpin.title);
                            $('#mDescription' + communityId + '_Content').html(pushpin.description);

                            shape.SetTitle(pushpin.title);
                            shape.SetDescription(pushpin.description);


                        }
                    );
                }
                break;
            }
        }
    }
}

function loadPushPins() {
    $.ajaxSetup({ cache: false });
    $.getJSON(pushPinJSONPath,
        function(json, textStatus) {
            if (textStatus != "success") {
                // Something bad happened
                alert(textStatus);
            }

            var pins = new Array();

            $.each(json.ps, function(i, pushpin) {
                var latlong = new VELatLong(pushpin.la, pushpin.lo);
                var veShape = new VEShape(VEShapeType.Pushpin, latlong)
                veShape.SetCustomIcon("<div class='pushpinOC' id='mIcon_" + pushpin.id + "'><div class='pushpinLabel'><font color='#FFFFFF'>" + (0 + 1) + "</font></div></div>");
                var title = "<span id='mTitle" + pushpin.id + "_Content'></span>";
                var description = "<span id='mDescription" + pushpin.id + "_Content'><img src='/App_Themes/DRHortonSite/images/wait/wait30trans.gif' alt=' align='absmiddle' /> Loading data....</span>";
                veShape.SetTitle(title);
                veShape.SetDescription(description);
                veShape.URL = pushpin.url;

                pushpin = {
                    communityid: pushpin.id,
                    latitude: pushpin.la,
                    longitude: pushpin.lo,
                    communityname: pushpin.cn,
                    veShape: veShape,
                    title: null,
                    description: null,
                    url: pushpin.url
                };

                pushpins.push(pushpin);

                pins.push(veShape);
            });

            showPins();
            //layer.AddShape(pins);
        }
    );
}

function clusteringCallback(clusters) 
{
    pinclusters = [];
    var anchors = "";
    for (var i = 0; i < clusters.length; ++i)
    {
        var cluster = clusters[i];
        var clusterShape = cluster.GetClusterShape();
        var clusterShapes = cluster.Shapes;
        //var latLong = cluster.LatLong;
        var latLongArray = null;
        var shapesLen = clusterShapes.length;
        
        var kidPins = {
                count: shapesLen,
                child: clusterShapes,
                shape: clusterShape
        }

        pinclusters.push(kidPins);
        
        if (clusterShapes.length > 1)
            latLongArray = FindBoundingRectangle(clusterShapes);

        //var _title = "<div style='position: relative; top: 20px; font-weight: normal; margin-bottom: 55px; /margin-bottom: 100px; width: 230px;'><a href='#' onClick='zoomCluster(" + latLong.Latitude + ", " + latLong.Longitude + ", " + clusterShape.GetID() + "); return false;'>" + anchors + "</a></div>";
        //if (latLongArray != null)
        //    _title = "<div style='position: relative; top: 20px; font-weight: normal; margin-bottom: 55px; /margin-bottom: 100px; width: 230px;'><a href='#' onClick='zoomMapForRectangle(" + latLongArray[0].Latitude + ", " + latLongArray[0].Longitude + ", " + latLongArray[1].Latitude + ", " + latLongArray[1].Longitude + "); return false;'>" + anchors + "</a></div>";

        var url = "javascript:zoomMapForRectangle(" + latLongArray[0].Latitude + ", " + latLongArray[0].Longitude + ", " + latLongArray[1].Latitude + ", " + latLongArray[1].Longitude + ")";
        var title = "<span id='mCluster__" + i + "'></span>";
        var description = "<span id='mClusterDescript__" + i + "'><img src='/App_Themes/DRHortonSite/images/wait/wait30trans.gif' alt=' align='absmiddle' /> Loading data....</span>";

        clusterShape.SetCustomIcon("<div class='pushpinCluster' id='pushpinCluster__"+i+"'><div class='pushpinClusterLabel'><font color='#FFFFFF'>" + cluster.Shapes.length + "</font></div></div>");
        clusterShape.SetTitle(title);
        clusterShape.SetDescription(description);
        clusterShape.URL = url;
    }
}

function FindBoundingRectangle(shapes)
{
    if (shapes.length <= 1)
        return null;

    var rightTopLat, rightTopLong, leftBottomLat, leftBottomLong;

    for (var x = 0; x < shapes.length; x++)
    {
        var shape = shapes[x];
        var latLong = shape.GetIconAnchor();

        if (x == 0) {
            rightTopLat = latLong.Latitude;
            leftBottomLat = latLong.Latitude;
            rightTopLong = latLong.Longitude;
            leftBottomLong = latLong.Longitude;
            continue;
        }
        
        if (latLong.Latitude > rightTopLat)
            rightTopLat = latLong.Latitude;
        else if (latLong.Latitude < leftBottomLat)
            leftBottomLat = latLong.Latitude;

        if (latLong.Longitude < rightTopLong)
            rightTopLong = latLong.Longitude;
        else if (latLong.Longitude > leftBottomLong)
            leftBottomLong = latLong.Longitude;
    }

    var latLongArray = new Array(new VELatLong(rightTopLat, rightTopLong), new VELatLong(leftBottomLat, leftBottomLong));
    return latLongArray;
}

function zoomCluster(latitude, longitude, shapeID)
{
    try
    {
        var latLong = new VELatLong(latitude, longitude);
        var zoomLevel = map.GetZoomLevel();
        
        zoomLevel = zoomLevel + 2;
        
        if (zoomLevel > 19)
            zoomLevel = 19;

        map.SetCenterAndZoom(latLong, zoomLevel);
    }
    catch (ex)
    {
        alert("Exception: " + ex);
    }
}

function zoomMapForRectangle(topRightLat, topRightLong, bottomLeftLat, bottomLeftLong)
{
    var latLongArray = new Array(new VELatLong(topRightLat, topRightLong), new VELatLong(bottomLeftLat, bottomLeftLong));
    map.SetMapView(latLongArray);
}
