﻿var map;
var pageCount = 0;
var currentSortColumn = 'CommunityName';
var currentFilter = '';
var currentPageNum = 1;
var centroidLat;
var centroidLng;
var commPointCollection;
var wasZoomed = false;
var initZoomLevel = 7;
var marketCode;
var mqPoint;
var mqMapInit;
var chMQPoiCollection;
var chMapInit;
var chCenter;
var updateMapFlag = true;
var loading = true;
var loadingString = "loading...";
var homeLoadingString = "Retrieving Home Info...";
var failLoadingMsg = "LOADING...";
var chOrigZoomLevel = 4;
var chStateZoomLevel = 4;
var chCenterLat = 31.170992;
var chCenterLng = -100.079858;
var chMinLat = 0;
var chMinLng = 0;
var chMaxLat = 0;
var chMaxLng = 0;
var chSearchParams = "";
var chMaxPoints = 20;
var chDisplayMapType = "true";
var points = {};
var sourcePoints = {};
var pointGroup = {};
var cityChildrenPois = {};
var stateId;
var marketId;
var cityName;
var latitude = 30.30;
var longitude = -97.70;
var radius = 5;
var CommunityPois = [];
var cityPois = [];
var marketPointCollection = [];
var statePointCollection = [];

var uniquePoints, mapSize, isInitializing;

//Set Maximum number of matches here
var MAX_MATCHES = 100;
//Set default search radius here
//var DEFAULT_RADIUS = 2;
//Set default width for corridor search here
var DEFAULT_CORRIDOR_WIDTH = 5.0;
//Set default unit for distance measurement here
var DEFAULT_UNIT = "Mi";
//Set Maximum number of shapepoints per maneuver here
var MAX_SHAPE_POINTS = 25;
//Set number of results to be displayed on a page here when using paging with search results
var PAGE_SIZE = 15;
//Set Scroll Distance for search result highlight here
//This is the height of one result on the results table (px)
var SCROLL_DISTANCE = 28;

var categoryid, type, poiJson;
var originValues = [];

//UTILITY
// Initializes a new instance of the StringBuilder class
// and appends the given value if supplied
function StringBuilder(value) {
    this.strings = [];
    this.append(value);
}

// Appends the given value to the end of this instance.
StringBuilder.prototype.append = function(value) {
    var argv = this.append.arguments;
    var argc = argv.length;
    for (var i = 0; i < argc; i++) {

        if (argv[i]) {
            this.strings.push(argv[i]);
        }
    }
};

// Clears the string buffer
StringBuilder.prototype.clear = function() {
    this.strings.length = 1;
};

// Converts this instance to a String.
StringBuilder.prototype.toString = function() {
    return this.strings.join("");
};

//========================================================================================================v
// Override the MapQuest utility function that has a problem with single quotes (apostrophes)
MQA.Util.stripHTMLTags = function(s) {
    return s.replace('/<\/?[^>]+>/gi', '').replace('\'', '&apos;').replace('"', '&quot;');
};
// Override the MapQuest slide function to disconnect infoWindow map panning
MQA.TileMap.prototype.slideMapByOffset = function(PTXY) { };


function replaceListener(item, eventName, methodName) {
    MQA.EventManager.removeListener(item, eventName, methodName);
    MQA.EventManager.addListener(item, eventName, methodName);
}

//========================================================================================================^
function getMapLatLngScale(offsetInPixels) {
    var tl = new MQPoint(0, 0);
    var br = new MQPoint(offsetInPixels, offsetInPixels);
    var iconTl = new MQA.Icon("/Images/Com/facetSearch/borders/blinker-tl.gif", 2, 2);
    var iconBr = new MQA.Icon("/Images/Com/facetSearch/borders/blinker-br.gif", 2, 2);

    tl = new MQA.Poi(map.pixToLL(tl), iconTl);
    br = new MQA.Poi(map.pixToLL(br), iconBr);
    tl.shadow.height = 0;
    tl.shadow.width = 0;
    br.shadow.height = 0;
    br.shadow.width = 0;
    //    map.addPoi(tl);
    //    map.addPoi(br);
    //  alert("lat"+ (tl.latLng.lat - br.latLng.lat)+ ", lng"+ (br.latLng.lng - tl.latLng.lng));
    return { "lat": (tl.latLng.lat - br.latLng.lat), "lng": (br.latLng.lng - tl.latLng.lng) };
}
//======================================================================================v
//NOTES:use this for formating map flyout
if (OriginPOIVal !== undefined) {
    orginValues = ["<div id=\"divMapPoint\" style=\"padding-right:25px;\">", "<strong><a href=\"javascript:LoadCityClusterInfo()\" />", OriginPOIVal, "</strong>", "</div>"];
}

//  proxy variables
//  since it is my server, I can leave these blank, its relative to the page
var proxyServerName = "";
var proxyServerPort = "";
// this is the important one, it tells the JSAPI where to send the XML request (the location of the proxy on my own server)
var proxyServerPath = ""; //"/JSAPIProxyPage/JSReqHandler";

//mq server variables
var mqServer = "geocode.access.mapquest.com";
var mqPort = "80";
var mqPath = "mq";
var myExec = new MQExec(mqServer, mqPath, mqPort, proxyServerName, proxyServerPath, proxyServerPort);


var myAddress = new MQAddress();
var myLocColl = new MQLocationCollection("MQGeoAddress");
var myLL = new MQA.LatLng(0, 0);
function geocodeIt() {

    myExec.clientid = '33242';
    myExec.password = 'bN9EJdwL';
    myExec.geocode(myAddress, myLocColl);
    myRetAddr = myLocColl.get(0);
    myLL.setLatLng(myRetAddr.getMQLatLng().getLatitude(), myRetAddr.getMQLatLng().getLongitude());
}
//======================================================================================v

function sortLatLng(a, b) {
    if (a.latLng.lat > b.latLng.lat) {
        return -1;
    } else {
        if (a.latLng.lat < b.latLng.lat) {
            return 1;
        } else {
            if (a.latLng.lng > b.latLng.lng) {
                return 1;
            }
        }
    }
    return -1;
}
function sortPoint(a, b) {
    if (a.x < b.x) {
        return -1;
    } else {
        if (a.x > b.x) {
            return 1;
        } else {
            if (a.y > b.y) {
                return 1;
            }
        }
    }
    return -1;
}
var _lastZoom = 2;
var _previousTab = "";

var _zooming;
function onMapZoomEnd() { //1
    var pageState = getPageState();
    $j("#mapWindow")[0].style.display = "none";
    $j("li.map-zoom").addClass("invisible");
    var zoomlevel = map.getZoomLevel();
    if ((_lastZoom == zoomlevel) && (_previousTab == pageState.ct)) {
        //zoom level and tab did not change, just had a few dots removed
        $j("#mapWindow")[0].style.display = "";
        $j("li.map-zoom").removeClass("invisible");
        return;
    }
    else {
        checkClusters();
        _lastZoom = zoomlevel;
        _previousTab = pageState.ct;
    }
}
function clusterByProximity(MapPois, nameSpace) {
    var zoomText = "";
    var localZoom = map.getZoomLevel();
    if (undefined === nameSpace) {
        nameSpace = "errorNameSpaceUnknown";
    }
    var latLng = getMapLatLngScale(18);
    uniquePoints = {};
    var clusteredPoints = {};
    var i = 0;
    var poiSingleCollection = new MQA.ShapeCollection();
    poiSingleCollection.setName(nameSpace + "single");

    var poiMultiCollection = new MQA.ShapeCollection();
    poiMultiCollection.setName(nameSpace + "multi");

    var pointArray = [];
    var multiArray = [];

    var maxMapPois = MapPois.length;

    for (var iBuildUniquePoints = 0; iBuildUniquePoints < maxMapPois; iBuildUniquePoints++) { //3
        var desireLatLng = MapPois[iBuildUniquePoints].getLatLng();

        var minLat = desireLatLng.lat - latLng.lat;
        var maxLat = desireLatLng.lat + latLng.lat;
        var minLng = desireLatLng.lng - latLng.lng;
        var maxLng = desireLatLng.lng + latLng.lng;
        var testMore = true;
        for (var iTestUniquePoints = 0; ((iTestUniquePoints < maxMapPois) && testMore); iTestUniquePoints++) {
            //an optimization to speed up this loop would be to only test against items already in the multiarray also test items larger than this one
            if (iBuildUniquePoints != iTestUniquePoints) {
                var testLatLng = MapPois[iTestUniquePoints].getLatLng();
                if ((testLatLng.lat < maxLat) && (testLatLng.lat > minLat) && (testLatLng.lng < maxLng) && (testLatLng.lng > minLng)) {
                    var pindex = (iBuildUniquePoints < iTestUniquePoints) ? iBuildUniquePoints : iTestUniquePoints;
                    for (var iMultiReck = multiArray.length - 1; iMultiReck >= 0; iMultiReck--) {
                        if (multiArray[iMultiReck].myIndex == pindex) {
                            // make sure we don't set a non parent index to be our parent
                            pindex = multiArray[iMultiReck].primaryIndex;
                        }
                    }
                    multiArray.push({ "point": MapPois[iBuildUniquePoints], "myIndex": iBuildUniquePoints, "primaryIndex": pindex });
                    testMore = false;
                }
            }
        }
        if (testMore) {
            pointArray.push(MapPois[iBuildUniquePoints]);
        }
    }

    var singlePointLength = pointArray.length;
    for (i = 0; i < singlePointLength; i++) {//3
        var point = pointArray[i];
        /****************************************************************************************************
        // uncomment this to improve map rendering speed adjust render window by going below 0 and above map.height and width
        //---------------------------------------------------------------------------------------------------*/
        //            if ((point.y < 0) || (point.y > map.height) || (point.x < 0) || (point.x > map.width))
        //                continue;  //skip points that render off the map
        /****************************************************************************************************/
        //            var sectionX = Math.floor(point.x / radius);
        //            var sectionY = Math.floor(point.y / radius);
        //            point.x = sectionX * radius;
        //            point.y = sectionY * radius;
        var uniqueKey = point.getKey();
        var newCommunityText = "";
        if ((undefined !== sourcePoints[uniqueKey]) && (sourcePoints[uniqueKey].length > 0)) {
            newCommunityText = sourcePoints[uniqueKey];
        } else {
            if (undefined === _communities[uniqueKey]) {
                if ((undefined !== _chidToComid[uniqueKey]) && (undefined !== _communities[_chidToComid[uniqueKey]]))
                    newCommunityText = _communities[_chidToComid[uniqueKey]].lbl;
            }
            else {
                newCommunityText = _communities[uniqueKey].lbl;
            }
        }
        points[uniqueKey] = newCommunityText;

        if ((!isNaN(parseInt(sourcePoints[uniqueKey]))) &&
             ((sourcePoints[uniqueKey].substr(sourcePoints[uniqueKey].length - 1, 1) == "P") ||
              (sourcePoints[uniqueKey].substr(sourcePoints[uniqueKey].length - 1, 1) == "I"))) {
            //
        } else {
            if ((undefined !== _communities[uniqueKey]) && (_communities[uniqueKey]["mp"] != 1)) {
                points[uniqueKey] = '<span class="singleCom">Getting info for </span>' + _communities[uniqueKey].lbl;
            }
        }
        //replaceListener(point, "mousedown", goThere);
        poiSingleCollection.add(point);
    }

    multiPointLength = multiArray.length;
    for (var i = 0; i < multiPointLength; i++) {//3
        var point = multiArray[i].point;
        uniqueKey = point.getKey();
        var newCommunityText = "";
        if ((undefined !== sourcePoints[uniqueKey]) && (sourcePoints[uniqueKey].length > 0)) {
            newCommunityText = sourcePoints[uniqueKey];
        } else {
            if (undefined === _communities[uniqueKey]) {
                if ((undefined !== _chidToComid[uniqueKey]) && (undefined !== _communities[_chidToComid[uniqueKey]]))
                    newCommunityText = _communities[_chidToComid[uniqueKey]].lbl;
            }
            else {
                newCommunityText = _communities[uniqueKey].lbl;
            }
        }
        var myNeighbor = MapPois[multiArray[i].primaryIndex];
        var uniqueKey = myNeighbor.getKey();
        if (multiArray[i].myIndex == multiArray[i].primaryIndex) {
            var oldCommunityText;
            zoomText = "";
            //            if (localZoom != 16) {
            //                zoomText = "<div class=\"fo_zoom_in\" onclick=\"zoomInBestFit('" + uniqueKey + "'); return false;\"><span>Zoom into map</span></div><hr>"
            //            }
            points[uniqueKey] = "<div class=\"fo_zoom_in_wrap\">" + zoomText + newCommunityText + "</div>";

            var imgSrc = "/images/com/icons/red_dot_cluster.png";
            var icon = new MQA.Icon(imgSrc, 26, 25);
            var poi = new MQA.Poi(new MQLatLng(myNeighbor.latLng.lat, myNeighbor.latLng.lng), icon);
            poi.setKey(uniqueKey);
            replaceListener(poi, "mouseover", onPoiMouseover);
            replaceListener(poi, "mouseout", onPoiMouseout);
            //replaceListener(poi, "mousedown", zoomInBestFit);
            pointGroup[uniqueKey] = [];
            pointGroup[uniqueKey].push(poi);

            clusteredPoints[uniqueKey] = [];

            //            poiMultiCollection.add(poi);
        }
        else {
            points[uniqueKey] = points[uniqueKey].substr(0, points[uniqueKey].length - 6) + "<hr>" + newCommunityText + "</div>";
            pointGroup[uniqueKey].push(point);
        }
    } //4

    //This code will change the cluster lat lng so it is the average of the included points
    for (var indexKey in clusteredPoints) {
        var itemLength = pointGroup[indexKey].length;
        var totalLat = 0;
        var totalLng = 0;
        for (i = 0; i < itemLength; i++) {
            totalLat += pointGroup[indexKey][i].latLng.lat;
            totalLng += pointGroup[indexKey][i].latLng.lng;
        }
        poi = pointGroup[indexKey][0];
        poi.latLng.lat = (totalLat / itemLength);
        poi.latLng.lng = (totalLng / itemLength);
        poiMultiCollection.add(poi);
    }
    //End of cluster lat lng calculator

    renderPoiCollection(poiSingleCollection);
    renderPoiCollection(poiMultiCollection);
}

function zoomInBestFit(myArrayKey) {
    if (!myArrayKey.split) //checking that this is a string if not then this was a mouseDown event and I should get the key from the sender
        myArrayKey = this.getKey();

    $j('#dialog').jqmHide();
    var maxZoom = map.getZoomLevel() + 4;
    var minZoom = 0;

    var poiBestFitCollection = new MQA.ShapeCollection();

    for (var i = pointGroup[myArrayKey].length - 1; i >= 0; i--) {
        var uniqueKey = pointGroup[myArrayKey][i].getKey();
        if (undefined === cityChildrenPois[uniqueKey]) {
            if ((i == 0) && (_communities[uniqueKey])) {
                pointGroup[myArrayKey][i].latLng.lat = _communities[uniqueKey].lat;
                pointGroup[myArrayKey][i].latLng.lng = _communities[uniqueKey].lng;
            }
            poiBestFitCollection.add(pointGroup[myArrayKey][i]);
            minZoom = 0;
        } else {
            myItemKey = pointGroup[myArrayKey][i].getKey();
            for (var j = cityChildrenPois[myItemKey].length - 1; j >= 0; j--) {
                poiBestFitCollection.add(cityChildrenPois[myItemKey][j]);
            }
            minZoom = 6;
        }
    }

    if (minZoom > maxZoom)
        maxZoom += 4;

    var bounds = poiBestFitCollection.getBoundingRect();
    map.zoomToRect(bounds, false, minZoom, maxZoom);
}

function goThere(e) {
    //for mouseDown on poi dots we want to grab the url of the location they would have gone to if they hovered and then selected the link to the single location in the flyout
    var myArrayKey = this.getKey();
    //if this begins with a number and ends with an M then it will be true so true for 1M false for 1 or KLM
    if ((!isNaN(parseInt(myArrayKey))) && (myArrayKey.substr(myArrayKey.length - 1, 1) == "M")) {
        $j('#dialog').jqmHide();
        map.setCenter(this.latLng, map.getZoomLevel() + 1);
    } else {

        if (!_HomeCards[myArrayKey]) {
            var linkLocation = points[myArrayKey];
            var startIndex = linkLocation.indexOf("href=") + 6;
            var stringLength = linkLocation.indexOf('"', startIndex) - startIndex;

            top.location = linkLocation.substr(startIndex, stringLength);
        } else {
            top.location = _HomeCards[myArrayKey].vtlURL;
        }
    }

}

function checkClusters() {
    points = {};
    pointGroup = {};
    removeAllPoiCollections();

    var localZoomLevel = map.getZoomLevel();
    if (localZoomLevel < 3) {
        stateDots();
    } else {
        var SearchContext = (typeof (facetContextJSON) != "undefined") ? facetContextJSON.context.ctx : "nonSearch";
        if ((SearchContext == "Market") || (SearchContext == "nonSearch") ||
        (SearchContext == "City")) {
            if ((localZoomLevel > 5) || (SearchContext == "nonSearch")) {
                communityDots();
                if (SearchContext != "nonSearch") {
                    loadMarketMapPoints(0, facetContextJSON.context.mkid);
                }
            } else {
                if (localZoomLevel == 3) {
                    loadMarketMapPoints(0, -1);
                } else {
                    cityDots();
                    if (SearchContext != "nonSearch") {
                        loadMarketMapPoints(0, facetContextJSON.context.mkid);
                    }
                }
            }
        } else {
            if (SearchContext == "State") {
                loadMarketMapPoints(facetContextJSON.context.stcd, 0);
            } else {  //nationalContext
                stateDots();
            }
        }
    }
}

function communityDots() {
    if (CommunityPois.length) {
        clusterByProximity(CommunityPois, "community");
    } else {
        //when communities aren't define we are on a state or national page so don't try to load them
    }
}
function cityDots() {
    if (cityPois.length) {
        clusterByProximity(cityPois, "city");
    } else {
        LoadCityClusterInfo(true);
    }
}

function stateDots() {
    if (statePointCollection.length > 0) {
        clusterByProximity(statePointCollection, "state");
    } else {
        loadStateMapPoints("", map.getZoomLevel(), true);
    }
}

//======================================================================================
function MapSetup() {
    //Build Map Object
    map = new MQA.TileMap(document.getElementById('mapWindow'));
    map.setBestFitMargin(10);
    map.setZoomLevel(16);
    //map.getDeclutter().setDeclutterMode(2);
    // Create a new Zoom control.
    var LZControl = new MQA.ZoomControl(map);
    map.addControl(LZControl, new MQA.MapCornerPlacement(MQA.MapCorner.TOP_LEFT, new MQA.Size(0, 0)));
    //Add view controls
    map.addControl(new CustomViewControl(), new MQA.MapCornerPlacement(MQA.MapCorner.TOP_LEFT, new MQA.Size(532, 0)));

    //Place MapQuest and Copyright logos
    map.setLogoPlacement(MQA.MapLogo.SCALES, new MQA.MapCornerPlacement(MQA.MapCorner.TOP_LEFT, new MQA.Size(65, 5))); //RIGHT, new MQA.Size(0, 23)));
    map.setLogoPlacement(MQA.MapLogo.MAPQUEST_COPYRIGHT, new MQA.MapCornerPlacement(MQA.MapCorner.BOTTOM_RIGHT, new MQA.Size(0, 0)));

    map.logos[MQA.MapLogo.MAPQUEST].style.display = "none";
    map.logos[MQA.MapLogo.NAVTEQ_COPYRIGHT].style.display = "none";
    map.logos[MQA.MapLogo.ICUBED_COPYRIGHT].style.display = "none";
    replaceListener(map, "zoomend", onMapZoomEnd);
    //replaceListener(map, "moveend", myMapMoveEnd);
}
//function myMapMoveEnd()
//{
//    //alert("mapMoved");
//}

function parseFacetResults(communityResults) {
    var newCommunityResults = {};
    for (var i = communityResults.length - 1; i >= 0; i--) {
        newCommunityResults[communityResults[i].cid] = { 'chid': communityResults[i].chid };
        _chidToComid[communityResults[i].chid] = communityResults[i].cid;
    }
    return newCommunityResults;
}
var _tempCallCount = 0;
var _facetedResultsHash = {};
var _chidToComid = {};
function syncMap(communityResults) {
    var pageState = getPageState();
    $j("#mapWindow")[0].style.display = "none";
    $j("#mapWrapper").show(100);
    $j("#divSliderLinks").show();

    _lastZoom = 0;
    _previousTab = "";
    initSlider("#mapWindow");

    _facetedResultsHash = {};
    CommunityPois = [];

    if (map === undefined) {
        MapSetup();
    }
    else {
        map.setZoomLevel(16);
        removeAllPoiCollections();
    }
    if ((undefined !== communityResults) && (communityResults.length > 0)) {
        _facetedResultsHash = parseFacetResults(communityResults);
    }

    var SearchContext = (typeof (facetContextJSON) != "undefined") ? facetContextJSON.context.ctx : "nonSearch";
    if ((SearchContext == "Market") || (SearchContext == "nonSearch") ||
        (SearchContext == "City")) {
        //map._onZoomEnd = map.onZoomEnd;
        //map.onZoomEnd = function(e) { if (isInitializing) { zooming(); } _tempCallCount++; this._onZoomEnd(e); };
        var poi;
        var icon;
        var addToMap = true;
        var found = false;
        var poiSingleCollection = new MQA.ShapeCollection();
        poiSingleCollection.setName("single");
        var childPoi = 0;
        for (var thisPoi in _communities) {
            var uniqueKey = thisPoi;
            addToMap = true;
            if (_communities[thisPoi]["mp"] == 1) {
                if (_communities[thisPoi].oldLbl) {
                    _communities[thisPoi].lbl = _communities[thisPoi].oldLbl;
                } else {
                    _communities[thisPoi].oldLbl = _communities[thisPoi].lbl;
                }
                //turn Numbers back on
                //icon = new MQA.Icon("/images/com/mapdots/c" + _communities[thisPoi]["mpid"] + ".png", 26, 25);
                icon = new MQA.Icon("/images/com/mapdots/multidot.png", 26, 25);

                addToMap = false; //not adding to the map unless there is at least one matching home
                for (var i = 1; i < _communities[thisPoi].com.length; i++) {
                    found = false;
                    childPoi = _communities[thisPoi].com[i];
                    if (undefined !== _facetedResultsHash[childPoi]) {
                        addToMap = true;
                        found = true;
                        if (undefined !== _facetedResultsHash[childPoi].chid) {
                            var chidType = _facetedResultsHash[childPoi].chid.substr(_facetedResultsHash[childPoi].chid.length - 1, 1);
                            if (pageState.ct == "Q") {
                                if (chidType != "I") {
                                    addToMap = false;
                                    found = false;
                                }
                            }
                        }
                    }
                    if (!found) {
                        var startIndex = _communities[thisPoi].lbl.indexOf("<li id=\"" + childPoi + "\"");
                        var endIndex = _communities[thisPoi].lbl.indexOf("</li>", startIndex);
                        if ((startIndex == -1) || (endIndex == -1)) {

                        } else {
                            var lblLength = _communities[thisPoi].lbl.length;
                            _communities[thisPoi].lbl = _communities[thisPoi].lbl.substr(0, startIndex) + _communities[thisPoi].lbl.substr(endIndex + 5, lblLength);
                        }
                    }

                }
            } else {
            //turn Numbers back on
            //icon = new MQA.Icon("/images/com/mapdots/" + _communities[thisPoi]["mpid"] + ".png", 21, 22);
            icon = new MQA.Icon("/images/com/mapdots/singledot.png", 21, 22);
            if (undefined !== _facetedResultsHash[thisPoi]) {
                    if (undefined !== _facetedResultsHash[thisPoi].chid) {
                        var chidType = _facetedResultsHash[thisPoi].chid.substr(_facetedResultsHash[thisPoi].chid.length - 1, 1);
                        if (pageState.ct == "H") {
                            //chidType == ("P" ||"I")
                            uniqueKey = _facetedResultsHash[thisPoi].chid;
                            sourcePoints[uniqueKey] = _communities[thisPoi].lbl;
                        }
                        if (pageState.ct == "Q") {
                            //if (chidType == "I") {
                            uniqueKey = _facetedResultsHash[thisPoi].chid;
                            sourcePoints[uniqueKey] = _communities[thisPoi].lbl;
                            //} else {
                            //    addToMap = false;
                            //}
                        }
                    }
                } else {
                    addToMap = false;
                }
            }
            if (addToMap) {
                sourcePoints[thisPoi] = _communities[thisPoi]["lbl"];
                poi = new MQA.Poi(new MQA.LatLng(_communities[thisPoi]["lat"], _communities[thisPoi]["lng"]), icon);
                replaceListener(poi, "mouseover", onPoiMouseover);
                replaceListener(poi, "mouseout", onPoiMouseout);
                //replaceListener(poi, "mousedown", goThere);

                CommunityPois.push(poi);
                if (undefined === cityChildrenPois[_communities[thisPoi]["c"]]) {
                    cityChildrenPois[_communities[thisPoi]["c"]] = [];
                }
                cityChildrenPois[_communities[thisPoi]["c"]].push(poi);
                poi.setKey(uniqueKey);
                poiSingleCollection.add(poi);
                //map.addPoi(poi2);
            }
        }
        if (poiSingleCollection.getSize() > 0) {
            var bounds = poiSingleCollection.getBoundingRect();
            map.zoomToRect(bounds, false, 0, 9);
            if (SearchContext != "nonSearch") {
                loadMarketMapPoints(0, facetContextJSON.context.mkid);
            }
        } else {
            if (SearchContext != "nonSearch") {
                loadMarketMapPoints(facetContextJSON.context.stcd, 0);
            }
            else {
                $j('#mapContentContainer').hide();
            }
        }
    } else if (SearchContext == "State") {
        loadMarketMapPoints(facetContextJSON.context.stcd, 0);
    } else if (SearchContext == "National") {
        //loadStateMapPoints();
        loadMarketMapPoints(0, -2);
    }
}
//================================================================================================^

//================================================================================================v
//GENERIC


//Sync
function syncResults(filteredIds) {
    if (filteredIds !== undefined) {
        pageCount = Math.ceil(filteredIds.length / 15);
        currentFilter = filteredIds;
        loadCommMapPoints(filteredIds);
    }
}

function setUpdateStatus() {
    //setResultsUpdateStatus();
    //setMapUpdateStatus();
}

function loadStateMapPoints(excludeName, desiredZoom, forceReclustering) {

    var dataObj, reqUrl;
    if (excludeName === undefined) {
        excludeName = "";
    }
    dataObj = { "exclude": excludeName };
    reqUrl = "/services/SearchMethods.asmx/GetStateMapPoi";

    $j.ajax({
        type: "POST",
        data: JSON.stringify(dataObj),
        url: reqUrl,
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        success: function(data, textStatus) {
            parseStateMapPoints(data.d, forceReclustering);
            if (excludeName == "") {
                var minZoom = 1;
                var maxZoom = 3;
                if (desiredZoom !== undefined) {
                    minZoom = desiredZoom - 1;
                    maxZoom = desiredZoom;
                }
                map.bestFit(false, minZoom, maxZoom);
            }
            $j("#mapWindow")[0].style.display = "";
            $j("li.map-zoom").removeClass("invisible");
            //removeAllPoiCollections();
        },
        error: onMarketMapFail
    });
}

function loadMarketMapPoints(stateId, excludeId) {
    $j("#modalBlockOut2").show(0);
    var dataObj, reqUrl;
    if ((stateId) && (stateId != 0)) {
        if (undefined === excludeId) {
            excludeId = 0;
        }
        dataObj = { "stCode": stateId, "exclude": excludeId };
        reqUrl = "/services/SearchMethods.asmx/GetStMktMapPoi";
    }
    else {
        var zoomlevel = map.getZoomLevel();

        if (zoomlevel <= 2) {
            dataObj = { "exclude": "" };
            reqUrl = "/services/SearchMethods.asmx/GetStateMapPoi"
        }
        else {
            var marketToExclude = (excludeId) ? excludeId : facetContextJSON.context.mkid;
            dataObj = { "exclude": marketToExclude };
            reqUrl = "/services/SearchMethods.asmx/GetMktMapPoi"
        }
    }
    var mynamespaceprefix = "";
    if (excludeId == -1)
        mynamespaceprefix = "USA";
    $j.ajax({
        type: "POST",
        data: JSON.stringify(dataObj),
        url: reqUrl,
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        success: function(data, textStatus) {
            parseMarketMapPoints(data.d, mynamespaceprefix);
            if (((excludeId === 0) && // if excludeId != 0 then this is a market so we don't want to rezoom
            (stateId !== 0) //if the stateid != 0 then this has the bounds for the markets in the state and we should rezoom
            ) || (excludeId == -2)) {
                var maxZoom = 5;
                if (_lastZoom)
                    maxZoom = _lastZoom;
                var mapCollection = new MQA.ShapeCollection();
                var tempSingleCollection = map.getShapeCollection("marketsingle");
                if (tempSingleCollection) { mapCollection.append(tempSingleCollection); }
                var tempMultiCollection = map.getShapeCollection("marketmulti");
                if (tempMultiCollection) { mapCollection.append(tempMultiCollection); }

                if (mapCollection != null) {
                    var bounds = mapCollection.getBoundingRect();
                    map.zoomToRect(bounds, false, 0, maxZoom);
                    //loadMarketMapPoints(0);
                } else {
                    map.bestFit(false, 0, maxZoom);
                }
                //window.setTimeout(function() {
                loadMarketMapPoints(0, -1);
                //return true; }, 1000);

                //                if (data.d.length > 0) {
                //                    var point = data.d[0];
                //                    window.setTimeout(function() {loadMarketMapPoints(0, point.Code); return true; }, 1000);
                //                }
            }
            $j("#mapWindow")[0].style.display = "";
            $j("li.map-zoom").removeClass("invisible");
            $j("#modalBlockOut2").hide(0);
            //removeAllPoiCollections();

        },
        error: onMarketMapFail
    });
}

function onMarketMapFail(e) {
    $j("#mapWrapper").hide(600);
    $j("#divSliderLinks").hide();
    $j("#modalBlockOut2").hide(0);
}
function parseStateMapPoints(states, forceReclustering) {
    var pageState = getPageState();
    var poiLL;
    var mapPoint;
    statePointCollection = []; //new MQA.ShapeCollection();
    //statePointCollection.setName("statePointCollection");
    var imgSrc = "/images/com/icons/red_dot_cluster.png";
    var icon = new MQA.Icon(imgSrc, 26, 25);
    for (var i = 0; i < states.length; i++) {
        mapPoint = states[i];
        mqPoint = new MQA.Poi(new MQA.LatLng(mapPoint.Lat, mapPoint.Lng), icon);
        var uniqueKey = mapPoint.Code + mapPoint.StateCode;
        mqPoint.setKey(uniqueKey);
        var tabText = "New Home Communities";
        if (pageState.ct == "H") {
            tabText = "New Homes";
        } else if (pageState.ct == "Q")
        { tabText = "Quick Move-in Homes"; }
        sourcePoints[uniqueKey] = '<div id="divMarketPopup"><strong><a href="' + mapPoint.Url + '" >View ' + tabText + ' in ' + mapPoint.Name + '</a></strong></div>';


        replaceListener(mqPoint, "mouseover", onPoiMouseover);
        replaceListener(mqPoint, "mouseout", onPoiMouseout);
        statePointCollection.push(mqPoint);
    }
    if (forceReclustering)
        clusterByProximity(statePointCollection, "state");
}

function parseMarketMapPoints(markets, mynamspace) {
    var pageState = getPageState();
    var poiLL;
    var mapPoint;
    marketPointCollection = []; //new MQA.ShapeCollection();
    //marketPointCollection.setName("marketPointCollection");
    var imgSrc = "/images/com/icons/red_dot_cluster.png";
    var icon = new MQA.Icon(imgSrc, 26, 25);
    for (var i = 0; i < markets.length; i++) {
        mapPoint = markets[i];
        mqPoint = new MQA.Poi(new MQA.LatLng(mapPoint.Lat, mapPoint.Lng), icon);
        var uniqueKey = mapPoint.Code + mapPoint.StateCode;

        mqPoint.setKey(uniqueKey);
        var tabText = "New Home Communities";
        if (pageState.ct == "H") {
            tabText = "New Homes";
        } else if (pageState.ct == "Q")
        { tabText = "Quick Move-in Homes"; }
        sourcePoints[uniqueKey] = '<div id="divMarketPopup"><strong><a href="' + mapPoint.Url + '">View ' + tabText + ' in ' + mapPoint.Name + '</a></strong></div>';


        replaceListener(mqPoint, "mouseover", onPoiMouseover);
        replaceListener(mqPoint, "mouseout", onPoiMouseout);
        marketPointCollection.push(mqPoint);
    }
    clusterByProximity(marketPointCollection, mynamspace + "market");
    //renderPoiCollection(marketPointCollection);
}
//Narendra Market cluster end
//#2 Centroid start
function setMarketCentroid() {
    //alert('loading marketCode centroidLat');
    $j.ajax({
        type: "POST",
        data: "{'marketId': '" + marketId + "'}",
        url: "/Services/SearchMethods.asmx/GetMarketCentroid",
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        success: onCentroidLoadSuccess,
        error: onCentroidLoadFailed
    });
}

//Centroid end

//City Cluster start

function LoadCityClusterInfo(forceReclustering) {
    currentPage = 0;
    $j.ajax({
        type: "POST",
        data: "{'marketId': '" + marketId + "'}",
        url: "/services/SearchMethods.asmx/GetCityClusterPois",
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        success: function(data, textStatus) {
            parseCityCommunityData(data.d, forceReclustering);
            loadMarketMapPoints(0, facetContextJSON.context.mkid);
            $j("#mapWindow")[0].style.display = "";
            $j("li.map-zoom").removeClass("invisible");
        }
    });
}

function parseCityCommunityData(result, forceReclustering) {

    // Add or replace the Collection to the map object.
    cityPois = buildCityClusterResult(result);
    if (forceReclustering)
        clusterByProximity(cityPois, "city");
}

function buildCityClusterResult(items) {
    var pageState = getPageState();
    var resultLength = items.length;

    var cityPointColn = []; // = new MQA.ShapeCollection();
    //cityPointColn.setName("cityClusterPoints");
    //for (var i = currentPage * PAGE_SIZE; i < resultLength && i < (currentPage * PAGE_SIZE + PAGE_SIZE); i++) {
    for (var i = 0; i < resultLength; i++) {
        // Create a new object point based on the array item.
        var point = items[i];
        // Assign Latitude and centroidLng to the MapQuest Point.
        var poi = new MQA.Poi(new MQA.LatLng(point.Latitude, point.Longitude));
        // Assign the String Builder string to the point.
        //cityPointColn[point.Name] = buildCityClusterHTML(point);
        var tabText = "New Home Communities";
        if (pageState.ct == "H") {
            tabText = "New Homes";
        } else if (pageState.ct == "Q")
        { tabText = "Quick Move-in Homes"; }
        sourcePoints[point.Name] = "<a href=\"" + point.Url + "\">" + " View " + point.ComunityCount + " " + tabText + " in " + point.Name + "</a>";

        poi.setKey(point.Name);
        // Set the Icon's properties.
        var imgSrc = "/images/com/icons/red_dot_cluster.png";
        var icon = new MQA.Icon(imgSrc, 26, 25);
        // Associate the Icon to the Point.
        poi.setIcon(icon);
        replaceListener(poi, "mouseover", OnCityPointMouseover);
        replaceListener(poi, "mouseout", onCityPointMouseout);

        // Add point to the collection.
        cityPointColn.push(poi);
    }
    return cityPointColn;
}

var _cancelHide = false;
var _containInBrowseWidth = true;
function OnCityPointMouseover(e) {
    _cancelHide = true;

    var html;
    html = points[this.key];
    displayCard(html, e);
}
function onCityPointMouseout(e) {
    _cancelHide = false;
    var _t = setInterval(function() {
        if (!_cancelHide) {
            clearInterval(_t);
            $j('#dialog').jqmHide();
        }
    }, 100);
}

//City Cluster end
//COMMUNITY POIS
function loadCommMapPoints(filter) {
    $j.ajax({
        type: "POST",
        data: "{'filter':'" + filter + "', 'marketCode':'" + marketCode + "'}",
        url: "/Services/SearchMethods.asmx/GetCommunityMapPoints",
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        success: onMapSuccess,
        error: onMapFailed
    });
}

function onMapPointMouseOver(e) {
    var info = map.getInfoWindow();
    if (this.getKey) {
        if (this != info.getOpener()) {

            if (!info.isHidden()) {
                info.hide();
                info.onClickedClosed(e);
            }
        }
    }
    else {
        if (!info.isHidden()) {
            info.hide();
            info.onClickedClosed(e);
        }
    }

    this.showInfoWindow();
    return;
}

function onMapPointMouseOut(e) {
    var info = map.getInfoWindow();
    info.hide();
    info.onClickedClosed(e);
    return;
}

function onMapPointClose(e) {
    var info = map.getInfoWindow();
    info.hide();
    info.onClickedClosed(e);
    return;
}


function reCenter() {
    var poiLL = new MQA.LatLng(centroidLat, centroidLng);
    map.panToLatLng(poiLL);
}

function onPoiMouseout(e) {
    _cancelHide = false;
    var _t = setInterval(function() {
        if (!_cancelHide) {
            clearInterval(_t);
            $j('#dialog').jqmHide();
        }
    }, 100);
}

function onError(result, context, methodName) {
    var x = 1;
}
//=========================================================================^
//Home/Inventory Card
var _HomeCards = {};
function getHomeCard(chid, e) {
    if (!_HomeCards[chid]) {
        if (points[chid] != homeLoadingString) {
            loadHomeInfo(chid, e);
        }
        displayCard(homeLoadingString, e);
    }

    var home = _HomeCards[chid];
    var sbHTML = new StringBuilder();

    if (home === undefined) {
        return;
    }

    var isInventory = true;
    if (home.key.substr(home.key.length - 1, 1) == "P") {
        isInventory = false;
    }

    var blankImage = "clr.gif";
    sbHTML.append("<div class=\"fo_2\">");
    sbHTML.append("<div class=\"fo_header_home\" ><div class=\"fo_prop_search\"><a class=\"subtitle\" href=\"", home.vtlURL, "\" onClick=\"dcsMultiTrack('WT.z_navtype','Selection','WT.z_navigation','Search Map Click');\" style=\"display:block;\">", home.plmktnm, "</a><span class=\"fo_com_name\">", home.cnm, "</span></div></div>");
    sbHTML.append("<div class=\"qmifo_content\"><div class=\"fo_thumb\">");
    sbHTML.append("<img src=\"", home.img, "?w=146&h=89\" alt=\"community photo\" style=\"width:146px;height:89px\"/>");
    if (isInventory) {
        sbHTML.append("<span class=\"flyqmihomesitetxt\">Homesite ", home.lId, "</span>");
    }
    sbHTML.append("</div><div class=\"fo_info\">");


    var fromText = (isInventory) ? "" : "From ";
    if (home.price !== undefined) {
        if (isInventory && home.waspri != null) {
            sbHTML.append("<p class=\"flyqmiprice-holder\"><span class=\"flyqmi-price-strike\">WAS ", home.waspri, "</span><br><span class=\"flyqmi-homeprice\">NOW ", home.price, "</span></p>");
        }
        else {
            sbHTML.append("<div class=\"fo_grey_bubble\"><div class=\"bubble_con\">", fromText, home.price, "</div></div>");
        }
    }
    sbHTML.append("<table cellspacing=\"0\" cellpadding=\"0\" border=\"0\"><tbody>");
    if (home.sgft !== undefined) {
        sbHTML.append("<tr><td class=\"fo_infotext\">", home.sgft, "</td><td>Square Feet</td></tr>");
    }
    if (home.bedrm !== undefined) {
        sbHTML.append("<tr><td class=\"fo_infotext\">", home.bedrm, "</td><td>Bedrooms</td></tr>");
    }
    if (home.bathrm !== undefined) {
        sbHTML.append("<tr><td class=\"fo_infotext\">", home.bathrm, "</td><td>Bathrooms</td></tr>");
    }
    if (home.gagebay !== undefined) {
        sbHTML.append("<tr><td class=\"fo_infotext\">", home.gagebay, "</td><td>", home.gartxt, "&nbsp;Garage</td></tr>");
    }
    if (home.story !== undefined) {
        sbHTML.append("<tr><td class=\"fo_infotext\">", home.story, "</td><td>Story</td></tr>");
    }

    sbHTML.append("</tbody></table></div></div><div class=\"fo_icons\">");


    var sbLcUrl = new StringBuilder();
    sbLcUrl.append("http://sales.liveperson.net/hc/65896788/?cmd=file&file=visitorWantsToChat&site=65896788&byhref=1&SESSIONVAR!skill=", home.mkcd, "&imageUrl=http://", document.domain, "/images/com/livechat/small16/");
    var lcUrl = sbLcUrl.toString();
    sbHTML.append("<span id=\"lcWrapperSpan\"><img src=\"http://sales.liveperson.net/hc/65896788/?cmd=repstate&site=65896788&&ver=1&imageUrl=http://", document.domain, "/images/com/livechat/small16/&skill=", home.mkcd, "\" id=\"liveChatFlyOutImg\" border=\"0\" onload='smallImageTest(this);' /><span style=\"padding-left: 5px;\"><a href=\"", lcUrl, "\" target=\"chat65896788\" onClick=\"javascript:window.open('/LogRedirect.aspx?np=", escape(lcUrl), "&DIVID=", home.divcd, "&COMID=", home.cno, "&ACTION={5}&WT.z_event=Hard Lead&WT.z_event_type=Chat Now!','chat65896788','width=472,height=320');return false;\">Chat Now</a></span><br /></span>");
    sbHTML.append("<img src=\"/Images/Com/Icons/fo_request_icon.gif\" alt=\"request info\" />&nbsp;&nbsp;<a href=\"#\" class=\"flyreqinf\" onclick=\"Lennar.Global.openRFIModal('", home.cnbr, "', '", home.pnbr, "', null, 'fav", home.cid, "', '", Lennar.Global.actorStatus, "'); return false;\">Request Info</a><br />");
    sbHTML.append("<img src=\"/Images/Com/Icons/icon_directions.gif\" title=\"Directions\" style=\"padding-right: 5px;\"><a href=\"", home.ddurl, "\">Directions</a>");

    if (home.hasPhotour) {
        sbHTML.append("<img src=\"/Images/Com/Icons/icon_photo.gif\" title=\"Photo Tour\" style=\"padding-right: 5px;\"><a class=\"photoTourLink\" href=\"", home.vtlURL, "/photo-tour\">Photo Tour</a></div>");
    }

    if (home.pltr.length > 0) {

        sbHTML.append("<img src=\"/Images/Com/Icons/icon_video.gif\" title=\"Virtual Tour\" style=\"padding-right: 5px;\"><a href=\"javascript:void(0);\" onclick=\"Lennar.Global.openVideoTourWindow('", home.pltr, "');\">Virtual Tour</a><br />");
    }

    sbHTML.append("</div><div class=\"fo_footer\"><div class=\"fo_activities\">");

    if (isInventory) {
        sbHTML.append("<img src=\"/Images/Com/Icons/fo_key.gif\" alt=\"Quick Move-In\" title=\"Quick Move-In\"/>&nbsp;<span class=\"indicator2\">", home.date, "</span>&nbsp;");
    }

    sbHTML.append("</div><div style=\"float: right; padding-top:5px;\"><a href=\"", home.vtlURL, "\" onClick=\"dcsMultiTrack('WT.z_navtype','Selection','WT.z_navigation','Search Map Click');\" style=\"float:right;\"><img src=\"/images/com/buttons/fo_btn_view_plan.png\" alt=\"View Home\"></a></div>");
    sbHTML.append("</div></div>");

    //sbHTML.append("Test Worked <a href=\"",home.vtlURL,"\">View Home</a>");
    return sbHTML.toString();
}
//function showHomeCard(chid) {
//    $j("#divCommCard").css('visibility', 'visible');
//    $j("#divCommImage").css('visibility', 'visible');
//    $j("#divPropInfo").css('padding-top', '12px');
//    if (!_HomeCards[chid]) {
//        loadHomeInfo(chid);
//    }

//}
function loadHomeInfo(chid, senderE) {
    $j.ajax({
        type: "POST",
        data: "{'chid': '" + chid + "'}",
        url: "/Services/SearchMethods.asmx/GetHomeDetails",
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        success: function(e) { onLoadHomeSuccess(e, senderE); },
        error: function(e) { onLoadHomeFail(e, senderE); }
    });
}
function onLoadHomeSuccess(e, senderE) {
    var response = JSON.parse(e.d);
    var chid;
    for (var item in response) {
        chid = response[item].key;
        _HomeCards[chid] = response[item];

    }
    getHomeCard(chid, senderE);
}

////COMMUNITY CARD
//function showCommunityCard(communityId) {
//    $j("#divCommCard").css('visibility', 'visible');
//    $j("#divCommImage").css('visibility', 'visible');
//    $j("#divPropInfo").css('padding-top', '12px');
//    if (!_communityCards[communityId]) {
//        loadCommunityInfo(communityId);
//    }
//}

function loadCommunityInfo(communityId, senderE) {
    $j.ajax({
        type: "POST",
        data: "{'communityId': '" + communityId + "'}",
        url: "/Services/SearchMethods.asmx/GetCommunityJson",
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        success: function(e) { onLoadCommunitySuccess(e, senderE) },
        error: function(e) { onLoadCommunityFail(e, senderE); }
    });
}

function onLoadCommunitySuccess(e, senderE) {
    var response = JSON.parse(e.d);
    var parsedResponse = response;
    var cid;
    for (var item in parsedResponse) {
        cid = parsedResponse[item].cid;
        _communityCards[cid] = parsedResponse[item];

    }
    getCommunityCard(cid, senderE);
}

function onLoadCommunityFail(e, senderE) {
    displayCard(failLoadingMsg, senderE);
}

function getCommunityCard(communityId, e) {
    if (!_communityCards[communityId]) {
        if (points[communityId] != loadingString)
            loadCommunityInfo(communityId, e);
        points[communityId] = loadingString;
        displayCard(loadingString, e);
    }

    var community = _communityCards[communityId];
    var sbHTML = new StringBuilder();

    if (community === undefined) {
        return;
    }

    var blankImage = "clr.gif";
    sbHTML.append("<div class=\"fo_1\" >");
    sbHTML.append("<div class=\"fo_header\" ><div class=\"fo_prop_search\"><a class=\"subtitle\" href=\"", community.vtlURL, "\" onClick=\"dcsMultiTrack('WT.z_navtype','Selection','WT.z_navigation','Search Map Click');\" style=\"display:block;\">", community.cnm, "</a>", "</div></div>");
    sbHTML.append("<div class=\"fo_content\"><div class=\"fo_thumb\">");
    sbHTML.append("<img src=\"", community.img, "?w=146&h=89\" style=\"width:146px;height:89px;\" alt=\"community photo\" />");
    sbHTML.append("</div><div class=\"fo_info\">");

    if (community.pri.length > 0) {
        sbHTML.append(community.pri, "<br />");
    }
    if ((community.versqft) && (community.versqft.length > 0)) {
        sbHTML.append(community.versqft, "<br />");
    }
    if (community.MIct > 0) {
        sbHTML.append("<a onClick=\"dcsMultiTrack('WT.z_navtype','Selection','WT.z_navigation','Search Map Click');\" href=\"", community.vtlURL, "?qm=1\">", community.MIct, " Quick Move-In Homes</a><br />");
    }
    sbHTML.append(community.add, "<br/>", community.cty, ", ", community.sco);

    sbHTML.append("</div></div><div class=\"fo_icons\">");


    var sbLcUrl = new StringBuilder();
    sbLcUrl.append("http://sales.liveperson.net/hc/65896788/?cmd=file&file=visitorWantsToChat&site=65896788&byhref=1&SESSIONVAR!skill=", community.mkcd, "&imageUrl=http://", document.domain, "/images/com/livechat/small16/");
    var lcUrl = sbLcUrl.toString();
    sbHTML.append("<span id=\"lcWrapperSpan\"><img src=\"http://sales.liveperson.net/hc/65896788/?cmd=repstate&site=65896788&&ver=1&imageUrl=http://", document.domain, "/images/com/livechat/small16/&skill=", community.mkcd, "\" id=\"liveChatFlyOutImg\" border=\"0\" onload='smallImageTest(this);' /><span style=\"padding-left: 5px;\"><a href=\"", lcUrl, "\" target=\"chat65896788\" onClick=\"javascript:window.open('/LogRedirect.aspx?np=", escape(lcUrl), "&DIVID=", community.dno, "&COMID=", community.cno, "&ACTION={5}&WT.z_event=Hard Lead&WT.z_event_type=Chat Now!','chat65896788','width=472,height=320');return false;\">Chat Now</a></span><br /></span>");

    sbHTML.append("<img src=\"/Images/Com/Icons/fo_request_icon.gif\" alt=\"request info\" />&nbsp;&nbsp;<a href=\"#\" class=\"flyreqinf\" onclick=\"Lennar.Global.openRFIModal('", community.cno, "', null, null, 'fav", community.cid, "', '", Lennar.Global.actorStatus, "');  return false;\">Request Info</a><br />");
    if (community.video.length > 0) {

        sbHTML.append("<img src=\"/Images/Com/Icons/icon_video.gif\" title=\"Virtual Tour\" style=\"padding-right: 5px;\"><a href=\"javascript:void(0);\" onclick=\"Lennar.Global.openVideoTourWindow('", community.video, "');\">Virtual Tour</a><br />");
    }
    if (community.hasPhotour) {
        sbHTML.append("<img src=\"/Images/Com/Icons/icon_photo.gif\" title=\"Photo Tour\" style=\"padding-right: 5px;\"><a class=\"photoTourLink\" href=\"", community.vtlURL, "/photo-tour\">Photo Tour</a><br />");
    }

    sbHTML.append("<img src=\"/Images/Com/Icons/icon_directions.gif\" title=\"Directions\" style=\"padding-right: 5px;\"><a href=\"", community.ddurl, "\">Directions</a><br />");


    sbHTML.append("</div><div class=\"fo_footer\"><div class=\"fo_activities\">");
    if (community.acad) { sbHTML.append("<img src=\"/Images/Com/Icons/typeActive.gif\" alt=\"Active Adult\" title=\"Active Adult\"/>&nbsp;<span>Active Adult</span>&nbsp;"); }
    if (community.golf) { sbHTML.append("<img src=\"/Images/Com/Icons/typeGolf.gif\" alt=\"Golf\" title=\"Golf\"/>&nbsp;<span>Golf</span>&nbsp;"); }
    if (community.sola) { sbHTML.append("<img src=\"/Images/Com/Icons/typeSolar.gif\" alt=\"Solar\" title=\"Solar\"/>&nbsp;<span>Solar</span>&nbsp;"); }
    if (community.urban) { sbHTML.append("<img src=\"/Images/Com/Icons/typeUrban.gif\" alt=\"Urban\" title=\"Urban\"/>&nbsp;<span>Urban</span>&nbsp;"); }
    if (community.midrise) { sbHTML.append("<img src=\"/Images/Com/Icons/typeMidrise.gif\" alt=\"Urban\" title=\"Mid Rise\"/>&nbsp;<span>Mid Rise</span>&nbsp;"); }
    if (community.highrise) { sbHTML.append("<img src=\"/Images/Com/Icons/typeHighrise.gif\" alt=\"Urban\" title=\"High Rise\"/>&nbsp;<span>High Rise</span>&nbsp;"); }
    if (community.multifam) { sbHTML.append("<img src=\"/Images/Com/Icons/typeMulti.gif\" alt=\"" + community.ctypetxt + "\" title=\"" + community.ctypetxt + "\"/>&nbsp;<span>" + community.ctypetxt + "</span>&nbsp;"); }
    if (community.singFam) { sbHTML.append("<img src=\"/Images/Com/Icons/typeSingle.gif\" alt=\"" + community.ctypetxt + "\" title=\"" + community.ctypetxt + "\"/>&nbsp;<span>" + community.ctypetxt + "</span>&nbsp;"); }
    sbHTML.append("</div><div style=\"float: right;\"><a href=\"", community.vtlURL, "\" onClick=\"dcsMultiTrack('WT.z_navtype','Selection','WT.z_navigation','Search Map Click');\" style=\"float:right;\"><img style=\"width:119px; height:29px; *margin-bottom:5px;\" src=\"/images/com/buttons/fo_btn_view_comm.png\" alt=\"View Community\"></a></div>");

    sbHTML.append("</div></div>");
    return sbHTML.toString()

    ;
}



//End Community Card

//Function to open a new internet browser
function MM_openBrWindow(theURL, winName, features) {
    window.open(theURL, winName, features);
}

function smallImageTest(sender) {
    if (sender !== null) {
        if (sender.fileSize < 200) {
            $j('#' + sender.id).parent().css('display', 'none');
        }
    }
}
function heightTest(arg) {
    var LiveChat = document.getElementById('dvLiveChat');
    var ClickToCall = document.getElementById('dvClickToCall');

    if (arg !== null) {
        if (arg.clientHeight < 2) {
            if (LiveChat !== null) {
                LiveChat.style.paddingRight = 0;
            }
        }
        else {
            if (LiveChat !== null) {
                if (navigator.userAgent.indexOf('Firefox') > -1) {
                    if (ClickToCall !== null) {
                        ClickToCall.style.paddingLeft = "5.5px";
                    }
                }
                else if (navigator.userAgent.indexOf('MSIE') > -1) {
                    LiveChat.style.paddingRight = 4;
                }
                else if (navigator.userAgent.indexOf('Safari') > -1) {
                    if (ClickToCall !== null) {
                        ClickToCall.style.paddingLeft = "5.5px";
                    }
                }
            }
        }
    }
}



//=========================================================================v
function keepOpen() {
    _cancelHide = true;
}
function allowClose() {
    _cancelHide = false;
}
function onPoiMouseout(e) {
    _cancelHide = false;
    var _t = setInterval(function() {
        if (!_cancelHide) {
            clearInterval(_t);
            $j('#dialog').jqmHide();
        }
    }, 100);
}

function onError(result, context, methodName) {
    var x = 1;
}
//=========================================================================^
var poiCollections = [];
//=========================================================================v
function renderPoiCollection(poiCollection) {
    if (map.getShapeCollection(poiCollection.collectionName) == null) {
        map.addShapeCollection(poiCollection);
        poiCollections.push(poiCollection);
    }
    else {
        map.replaceShapeCollection(poiCollection, poiCollection.collectionName);
    }
    $j("#mapWindow")[0].style.display = "";
    $j("li.map-zoom").removeClass("invisible");
}
//=========================================================================^
function removeAllPoiCollections() {
    for (var i = 0; i < poiCollections.length; i++) {
        map.removeShapeCollection(poiCollections[i].collectionName);
    }
}
//==========================================================================v
function BuildInfoContentHTML(point) {
    var pageState = getPageState();
    var container = document.createElement("div");
    var htmlElement = document.createElement("div");
    htmlElement.setAttribute("class", "modal");
    //Na Add img in the info title
    //var typeString = poiTypeLookup.GetTypeString(point.A);

    if (point.A != "") {

        //var poiType = document.createElement("b");
        var imgSrc = "/Images/Com/Mapping/" + point.A; //+ ".gif";
        img = document.createElement("img");
        img.src = imgSrc;
        img.id = "img_" + point.I;
        img.setAttribute("height", "15px");
        img.setAttribute("weidth", "15px");
        img.setAttribute("style", "text-align:center");
        htmlElement.appendChild(img);
    }

    if (point.N != "") {
        var poiName = document.createElement("b");
        if (point.D != "") {
            //htmlElement.appendChild(document.createTextNode(" (" + point.D + "mi.)"));
            var tabText = "New Home Communities";
            if (pageState.ct == "H") {
                tabText = "New Homes";
            } else if (pageState.ct == "Q")
            { tabText = "Quick Move-in Homes"; }
            poiName.appendChild(document.createTextNode(" View " + point.D + " " + tabText + " in " + point.N));

            htmlElement.appendChild(poiName);
        }
        //htmlElement.appendChild(document.createElement("br"));
    }
    container.appendChild(htmlElement);

    return container.innerHTML;
}
//===========================================================================^
/*
* Function to handle the click event on a poi and table result
* Pre-Condtion: The event must exist.
* Post-Condition: The appropriate action is taken based on the object that triggered the event.
*
* @param        e - a javascript event
* @author       Seisan Consulting   2-16-2006
*/
/*function onPoiClick(e) {
var poiid = false;
var poi = null;
//If the key is defined then a Poi has triggered this event
alert("click");
if (this.getKey()) {
//retrieve the correct table rows from the results table based on the key of the poi that triggered the event
poiid = this.getKey();

poi = map.getByKey(poiid);
alert("you clicked" + poiid);

if (poi !== null) {
poi.showInfoWindow();
}
}
else {
//The result on the result table has triggered the event
var obj = getEventCurrentTarget(e);
poiid = obj.id;
poiid = poiid.substring(poiid.lastIndexOf("_") + 1);
//Retrieve the poi based on the key read from the table row that triggered the event
//poi = map.getPoiByKey(poiid);
poi = map.getByKey(poiid);


if (poi !== null) {
poi.showInfoWindow();
}
}

}
*/


var _cancelHide = false;
var _containInBrowseWidth = true;
function onPoiMouseover(e) {
    _cancelHide = true;

    var html = this.key;
    if ((!isNaN(parseInt(html))) &&
        (this.icon.imageURL != '/images/com/icons/red_dot_cluster.png') &&
         ((html.substr(html.length - 1, 1) == "P") ||
          (html.substr(html.length - 1, 1) == "I"))) {
        html = getHomeCard(this.key, e);
        displayCard(html, e);
    } else {
        html = points[this.key];
        if ((html.substr(0, 22) == '<span class="singleCom') || (html == loadingString)) {
            html = loadingString;
            html = getCommunityCard(this.key, e);
            displayCard(html, e);
        } else {
            displayCard(html, e);
        }
    }

}

function displayCard(html, e) {
    if (html === undefined)
        html = loadingString;
    var browserLacksDomTargetSupport = typeof (e.domEvent.target) == "undefined";
    $j('#ttest_cell')[0].innerHTML = "<nobr>" + html + "</nobr>";
    $j('#ttest_cell')[0].style.width = "";
    $j('#ttest_cell')[0].style.height = "";
    $j('#ttest_cell')[0].style.whiteSpace = "normal";

    var maxWidth = $j('#ttest_cell')[0].childNodes[0].clientWidth;
    var maxHeight = $j('#ttest_cell')[0].childNodes[0].clientHeight;

    if (typeof (maxWidth) == "undefined" && typeof (maxHeight) == "undefined") {
        $j('#ttest_cell')[0].style.whiteSpace = "nowrap";
    }
    else {
        if (typeof (maxWidth) != "undefined") {
            $j('#ttest_cell')[0].style.width = maxWidth + "px";
        }
        if (typeof (maxHeight) != "undefined") {
            $j('#ttest_cell')[0].style.height = maxHeight + "px";
        }
    }

    var recheck = false;
    var myWidth = $j('#ttest_cell').width() + 40;
    var myHeight = $j('#ttest_cell').height();
    if (myWidth < 200) {
        recheck = true;
        myWidth = 200;
    }
    if (myWidth > 604) { //800) {
        recheck = true;
        myWidth = 604; //800;
    }
    if (recheck) {
        $j('#ttest_cell')[0].innerHTML = html;
        $j('#ttest_cell')[0].style.whiteSpace = "normal";
        $j('#ttest_cell')[0].style.width = myWidth + "px";
        myHeight = $j('#ttest_cell').height();
    }
    $j('#pop_content')[0].innerHTML = html;
    $j('#pop_dialog_table').attr('style', 'width: ' + myWidth + 'px !important');

    // Calculate the dimensions of the browser window
    var browseHeight = window.innerHeight;
    var browseWidth = window.innerWidth;
    if (document.all) {
        browseHeight = document.body.parentNode.clientHeight;  //TO GET THE USED HEIGHT: document.body.clientHeight;
        browseWidth = document.body.parentNode.clientWidth;  //TO GET THE USED WIDTH: document.body.clientWidth;
    }

    var pointerOffsetX = browserLacksDomTargetSupport ? -4 : -1;
    var pointerOffsetY = browserLacksDomTargetSupport ? -4 : -1;

    var mapOffsetObj = $j('#mapWindow').offset();
    var mapOffsetX = mapOffsetObj.left; //$j('#mapWindowWrapper')[0].offsetLeft;
    var mapOffsetY = mapOffsetObj.top; //$j('#mapWindowWrapper')[0].offsetTop;

    // Determine the map window dimensions
    var mapWidth = map.width;
    var mapHeight = map.height;
    var iconHeight = 17;
    var iconWidth = 17;
    if (this.icon) {
        var iconHeight = this.icon.height;  //(parentNode.offsetParent.childNodes[0].clientHeight);
        var iconWidth = this.icon.width; //(parentNode.offsetParent.childNodes[0].clientWidth);
    }
    // Calculate the dialog dimensions
    var dialogHeight = myHeight + 10 + 15;
    var dialogWidth = myWidth;

    // Calculate the dialog position within the browser window from the event source
    var topPos = browserLacksDomTargetSupport ? (e.domEvent.clientY - e.domEvent.offsetY - e.domEvent.srcElement.offsetTop) : (e.domEvent.clientY - e.domEvent.layerY);
    var leftPos = browserLacksDomTargetSupport ? (e.domEvent.clientX - e.domEvent.offsetX - e.domEvent.srcElement.offsetLeft) : (e.domEvent.clientX - e.domEvent.layerX);

    var middlePos = topPos - (dialogHeight / 2);
    var bottomPos = topPos - dialogHeight;
    var centerPos = leftPos - (dialogWidth / 2);
    var rightPos = leftPos - dialogWidth;

    // Get the relative map position from the center of the icon
    leftPos = leftPos; //  - mapOffsetX;
    topPos = topPos;  //- mapOffsetY;
    mapX = leftPos + (iconWidth / 2);
    mapY = topPos + (iconHeight / 2);

    var posX = centerPos;
    var posY = middlePos;

    $j('#popup-pointer-btm')[0].style.visibility = "hidden";
    $j('#popup-pointer-rt')[0].style.visibility = "hidden";
    $j('#popup-pointer-lt')[0].style.visibility = "hidden";
    $j('#popup-pointer-top')[0].style.visibility = "hidden";
    $j('#popup-close')[0].style.left = (dialogWidth - 22) + "px";

    var scrollLeft = 0;
    if (self.pageXOffset) // all except Explorer
    {
        scrollLeft = self.pageXOffset;
    }
    else if (document.documentElement && document.documentElement.scrollLeft) {
        // IE6 +4.01 and user has scrolled
        scrollLeft = document.documentElement.scrollLeft;
    }
    else if (document.body && document.body.scrollLeft) {
        // IE5 or DTD 3.2
        scrollLeft = document.body.scrollLeft;
    }
    //mapX += scrollLeft;

    // Accomodate window scrolling
    var scrollTop = 0;
    if (self.pageYOffset) // all except Explorer
    {
        scrollTop = self.pageYOffset;
    }
    else if (document.documentElement && document.documentElement.scrollTop) {
        // IE6 +4.01 and user has scrolled
        scrollTop = document.documentElement.scrollTop;
    }
    else if (document.body && document.body.scrollTop) {
        // IE5 or DTD 3.2
        scrollTop = document.body.scrollTop;
    }
    //mapY += scrollTop;    

    //alert("MapX: " + mapX + " mapWidth: " + mapWidth + " mapOffsetX: " + mapOffsetX + " scrollLeft: " + scrollLeft + " MapY: " + mapY + " mapHeight: " + mapHeight + " mapOffsetY: " + mapOffsetY + " scrollTop: " + scrollTop);
    //alert("X:" + (mapX + scrollLeft - mapOffsetX) + " Y: " + (mapY + scrollTop - mapOffsetY));
    
    // Calculate the horizontal alignment based on a virtual grid of thirds
    var horizontalPos = 'center';
    if ((mapX + scrollLeft - mapOffsetX) < (mapWidth / 2.5)) {
        horizontalPos = 'left';
        posX = leftPos + iconWidth + 12;
        posY += 16;
        $j('#popup-pointer-lt')[0].style.visibility = "visible";
        $j('#popup-pointer-lt')[0].style.top = 0;
        $j('#popup-pointer-lt')[0].style.paddingTop = ((myHeight / 2) + 3) + "px";
        $j('#popup-pointer-lt')[0].style.height = (myHeight / 2) + 18 + "px";

        $j('#popup-pointer-lt').children('div')[0].style.marginTop = -((myHeight / 2) + 1) + "px";
        $j('#popup-pointer-lt').children('div')[0].style.background = "transparent url(/images/com/icons/arrows.png) -84px " + (myHeight / 2) + "px no-repeat";
        $j('#popup-pointer-lt').children('div')[0].style.height = myHeight + 18 + "px";        
    }
    else if (((mapX + scrollLeft - mapOffsetX) > (mapWidth - (mapWidth / 2.5))) && ((posX - (dialogWidth / 2)) >= 0)) {
        horizontalPos = 'right';
        posX = rightPos - Math.ceil(iconWidth / 2) + 2;
        posY += 16;
        $j('#popup-pointer-rt')[0].style.visibility = "visible";
        $j('#popup-pointer-rt')[0].style.left = (dialogWidth - 2) + "px";
        $j('#popup-pointer-rt')[0].style.top = 0;
        $j('#popup-pointer-rt')[0].style.paddingTop = ((myHeight / 2) + 3) + "px";
        $j('#popup-pointer-rt')[0].style.height = (myHeight / 2) + 18 + "px";

        $j('#popup-pointer-rt').children('div')[0].style.marginTop = -((myHeight / 2) + 1) + "px";
        $j('#popup-pointer-rt').children('div')[0].style.background = "transparent url(/images/com/icons/arrows.png) -56px " + (myHeight / 2) + "px no-repeat";
        $j('#popup-pointer-rt').children('div')[0].style.height = myHeight + 18 + "px";        
    }
    if (posX < 0 && (posX + dialogWidth) <= browseWidth && horizontalPos != 'left') {
        if (horizontalPos == 'center') {
            posY += 16;
        }
        horizontalPos = 'left';
        posX = leftPos + iconWidth + 12;
        $j('#popup-pointer-rt')[0].style.visibility = "hidden";
        $j('#popup-pointer-lt')[0].style.visibility = "visible";
        $j('#popup-pointer-lt')[0].style.top = 0;
        $j('#popup-pointer-lt')[0].style.paddingTop = ((myHeight / 2) + 3) + "px";
        $j('#popup-pointer-lt')[0].style.height = (myHeight / 2) + 18 + "px";

        $j('#popup-pointer-lt').children('div')[0].style.marginTop = -((myHeight / 2) + 1) + "px";
        $j('#popup-pointer-lt').children('div')[0].style.background = "transparent url(/images/com/icons/arrows.png) -84px " + (myHeight / 2) + "px no-repeat";
        $j('#popup-pointer-lt').children('div')[0].style.height = myHeight + 18 + "px";
    }
    if (((posX < 0 && horizontalPos == 'right') || ((leftPos + iconWidth + 12 + dialogWidth) > browseWidth && horizontalPos == 'left')) && rightPos > 0 && (centerPos + (dialogWidth / 2)) < browseWidth) {
        horizontalPos = 'center';
        posX = centerPos;
        $j('#popup-pointer-rt')[0].style.visibility = "hidden";
        $j('#popup-pointer-lt')[0].style.visibility = "hidden";
    }
    if ((mapY + scrollTop - mapOffsetY) < 0 || (mapY + scrollTop - mapOffsetY) > mapHeight) {
        horizontalPos = 'center';
        posX = centerPos;
        $j('#popup-pointer-rt')[0].style.visibility = "hidden";
        $j('#popup-pointer-lt')[0].style.visibility = "hidden";
    }

    // Calculate the vertical alignment based on a virtual grid of thirds
    var verticalPos = 'middle';
    if ((mapY + scrollTop - mapOffsetY) < mapHeight / 2) {
        verticalPos = 'top';
        if (horizontalPos == 'center') {
            posY = topPos + iconHeight + 13;
            $j('#popup-pointer-top')[0].style.visibility = "visible";
            $j('#popup-pointer-top')[0].style.left = ((dialogWidth / 2) + (iconWidth / 2) - 4) + "px";
        }
    }
    else if ((mapY + scrollTop - mapOffsetY) > mapHeight / 2) {
        verticalPos = 'bottom';
        if (horizontalPos == 'center') {
            posY = bottomPos - iconHeight + 19;
            $j('#popup-pointer-btm')[0].style.visibility = "visible";
            $j('#popup-pointer-btm')[0].style.left = ((dialogWidth / 2) + (iconWidth / 2) - 4) + "px";
        }
    } else if (horizontalPos == 'center') {
        verticalPos = 'top';
        posY = topPos + iconHeight + 13;
        $j('#popup-pointer-top')[0].style.visibility = "visible";
        $j('#popup-pointer-top')[0].style.left = ((dialogWidth / 2) + (iconWidth / 2) - 4) + "px";
    }


    // NOTE: Need to re-evaluate the flyout position with respect to the scroll offset

    // Set the dialog position
    $j('#dialog')[0].style.top = posY + scrollTop + pointerOffsetY - mapOffsetY + "px";
    $j('#dialog')[0].style.left = posX + scrollLeft + pointerOffsetX - mapOffsetX + "px";
    if (html == loadingString) {
        onPoiMouseout(e);
    }
    // Show the dialog
    $j('#dialog').jqmShow();
    $j("#dialog .photoTourLink").click(function() {
        Lennar.Global.openPhotoTourModal($j(this).attr('href'));
        return false;
    });
}

function scrollToSearchResult(poiid) {

}

function ShowMap() {
    $j("#mapArea").show();
    syncMap();
}

function HideMap() {
    $j("#mapArea").hide();
    if (map !== undefined) {
        removeAllPoiCollections();
    }
}

//Slider to expand/collapse map
var _sliderHeight = "349px";
var _renderMap = true;
var _offset = 185;

function initSlider(slideElement) {
    $j(slideElement).each(function() {
        var current = $j(this);
        current.attr("box_h", current.height());
    });

    $j(slideElement).css("height", _sliderHeight);
    $j("#divSliderLinks").html('<img src="/images/com/mapping/largermap.png"/>');
    $j("#divSliderLinks img").css("cursor", "pointer").click(function() { openSlider(slideElement) })
}

function openSlider(slideElement) {
    _offset = 350;
    _renderMap = true; //show updating image
    setMapUpdateStatus();
    var open_height = $j(slideElement).attr("box_h") + "px";
    $j(slideElement).animate({ "height": open_height }, { duration: "slow" });

    $j("#divSliderLinks").html('<img src="/images/com/mapping/smallermap.png"/>');
    $j("#divSliderLinks img").css("cursor", "pointer").click(function() { closeSlider(slideElement) })
    setTimeout("reRenderMap(624);", 500);
}

function closeSlider(slideElement) {
    _offset = 185;
    _renderMap = true; //show updating image    
    setMapUpdateStatus();
    $j(slideElement).animate({ "height": _sliderHeight }, { duration: "slow" });

    $j("#divSliderLinks").html('<img src="/images/com/mapping/largermap.png"/>');
    $j("#divSliderLinks img").css("cursor", "pointer").click(function() { openSlider(slideElement) })
    setTimeout("reRenderMap(349);", 500);
}

function reRenderMap(newHeight) {
    $j("#mapWrapper").toggleClass("tallMap");
    var myMapSize = map.getSize();
    $j("#mapArea").parent("td").css("height", (newHeight) + "px");
    $j("#mapArea").css("height", (newHeight) + "px");

    myMapSize.height = newHeight;
    map.setSize(myMapSize);
    _renderMap = false;
    setMapUpdateStatus();
}

function setMapUpdateStatus() {
    if (_renderMap) {
        $j("#mmapWindow").hide();
        //$j("#mapWindowWrapper").html("<div style=\"background-color:#FFF; color:#000; width:662px; height:" + _offset + "px; text-align:center; padding-top:" + (_offset - 15) + "px; \"><img src=\"/images/com/mapping/loading.png\" alt=\"updating\" id=\"imgUpdating\" style=\"width:96px; height:33px;\" />");
    } else {

        $j("#mmapWindow").show();
    }
}

