﻿// 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) { }


// Initializes a new instance of the StringBuilder class
// and appends the given value if supplied
function StringBuilder(value) {
    this.strings = new Array("");
    this.append(value);
}

// Appends the given value to the end of this instance.
StringBuilder.prototype.append = function(value) {
    if (value) {
        this.strings.push(value);
    }
}

// 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("");
}

// Define Global variables.
var map;
var chMQPoiCollection;
var chMapInit;
var chCenter;
var updateMapFlag = true;
var loading = true;
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;

//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 = [];

if(typeof(communityUrl) != 'undefined' )
{
    if ((typeof(communityPrice) != 'undefined') && (communityPrice.length > 1))
        orginValues = ["<div id=\"divMapPoint\" style=\"padding-right:25px;\">", "<strong><a href=\"", communityUrl, "\">", communityName, "</a>", " from ", formatPrice(communityPrice), "</strong>", "</div>"];
    else
        orginValues = ["<div id=\"divMapPoint\" style=\"padding-right:25px;\">", "<strong><a href=\"", communityUrl, "\">", communityName, "</a>", "</strong>", "</div>"];
}

points = {
    "origin": (typeof(orginValues) != 'undefined') ? orginValues.join("") : ""
    }

var poiTypeLookup = {
    Grocery: 3012,
    Restaurant: 3016,
    Police: 3051,
    Healthcare: 3043,
    Shopping: 3020,
    College: 3044,
    School: 3045,
    Golf: 3037,
    Park: 3034,
    AirPort: 3010,
    BusStation: 3027,
    Subway: 3004,
    CivicCenter: 3038,
    AmusementPark: 3039,
    GetTypeString: function(typeCode) {
        switch (typeCode) {
            case poiTypeLookup.Grocery:
                return "Grocery Store";
                break;
            case poiTypeLookup.Restaurant:
                return "Restaurant";
                break;
            case poiTypeLookup.Police:
                return "Police Station";
                break;
            case poiTypeLookup.Healthcare:
                return "Hospital/Medical";
                break;
            case poiTypeLookup.Shopping:
                return "Shopping";
                break;
            case poiTypeLookup.College:
                return "Higher Education";
                break;
            case poiTypeLookup.School:
                return "School/Govt Bldg";
                break;
            case poiTypeLookup.Golf:
                return "Golf Course";
                break;
            case poiTypeLookup.Park:
                return "Park/Recreation";
                break;
            case poiTypeLookup.AirPort:
                return "Airport";
                break;
            case poiTypeLookup.BusStation:
                return "Park & Ride";
                break;
            case poiTypeLookup.Subway:
                return "Commuter Rail Station";
                break;
        }
    },
    GetCategoryString: function(typeCode) {
        switch (typeCode) {
            case poiTypeLookup.Grocery:
                return "Food &amp; Dining";
                break;
            case poiTypeLookup.Restaurant:
                return "Food &amp; Dining";
                break;
            case poiTypeLookup.Police:
                return "Police";
                break;
            case poiTypeLookup.Healthcare:
                return "Healthcare";
                break;
            case poiTypeLookup.Shopping:
                return "Shopping";
                break;
            case poiTypeLookup.College:
                return "Education";
                break;
            case poiTypeLookup.School:
                return "Education";
                break;
            case poiTypeLookup.Golf:
                return "Outdoor Activities";
                break;
            case poiTypeLookup.Park:
                return "Outdoor Activities";
                break;
            case poiTypeLookup.AirPort:
                return "Transportation";
                break;
            case poiTypeLookup.BusStation:
                return "Transportation";
                break;
            case poiTypeLookup.Subway:
                return "Transportation";
                break;
        }
    }
};
var oldTab;

var iterator = 0;

function changePage(pageNum) {
    currentPage = pageNum;
    onPoiSuccess();
}

function isFirst(reset)
{
if (reset)
    iterator = 0;
else
    return ++iterator;
}
var poiTypePresent = {
    FoodDining: false,
    Police: false,
    Healthcare: false,
    Shopping: false,
    Education: false,
    Outdoor: false,
    Transportation: false,
    setSource: function(poiArray) {
    
        for (var i = 0; i < poiArray.length; i++) {
            switch (poiArray[i].DT) {
                case poiTypeLookup.Grocery:
                    this.FoodDining = true;
                    break;
                case poiTypeLookup.Restaurant:
                    this.FoodDining = true;
                    break;
                    
                case poiTypeLookup.Police:
                    this.Police = true;
                    break;
                    
                case poiTypeLookup.Healthcare:
                    this.Healthcare = true;
                    break;
                    
                case poiTypeLookup.Shopping:
                    this.Shopping = true;
                    break;
                    
                case poiTypeLookup.College:
                    this.Education = true;
                    break;
                case poiTypeLookup.School:
                    this.Education = true;
                    break;
                    
                case poiTypeLookup.Golf:
                    this.Outdoor = true;
                    break;
                case poiTypeLookup.Park:
                    this.Outdoor = true;
                    break;
                    
                case poiTypeLookup.AirPort:
                    this.Transportation = true;
                    break;
                case poiTypeLookup.BusStation:
                    this.Transportation = true;
                    break;
                case poiTypeLookup.Subway:
                    this.Transportation = true;
                    break;
            }
        }
    },
    reset: function() {
        this.FoodDining = false;
        this.Police = false;
        this.Healthcare = false;
        this.Shopping = false;
        this.Education = false;
        this.Outdoor = false;
        this.Transportation = false;
    }
};
function poiSortCategory() {
    var _sortedItems = [];
    if (null == poiJson)
        getPOIs(lat, lng);
         
    var toSort = poiJson;
    if (null != toSort) {
        var FoodDining = [];
        var _tempFoodDining = [];
        var Police = [];
        var Healthcare = [];
        var Shopping = [];
        var Education = [];
        var _tempEducation = [];
        var Outdoor = [];
        var _tempOutdoor = [];
        var Transportation = [];
        var _temp1Transportation = [];
        var _temp2Transportation = [];

        for (var i = 0; i < toSort.length; i++) {
            switch (toSort[i].DT) {
                case poiTypeLookup.Grocery:
                    FoodDining.push(toSort[i]);
                    break;
                case poiTypeLookup.Restaurant:
                    _tempFoodDining.push(toSort[i]);
                    break;
                case poiTypeLookup.Police:
                    Police.push(toSort[i]);
                    break;
                case poiTypeLookup.Healthcare:
                    Healthcare.push(toSort[i]);
                    break;
                case poiTypeLookup.Shopping:
                    Shopping.push(toSort[i]);
                    break;
                case poiTypeLookup.College:
                    Education.push(toSort[i]);
                    break;
                case poiTypeLookup.School:
                    _tempEducation.push(toSort[i]);
                    break;
                case poiTypeLookup.Golf:
                    Outdoor.push(toSort[i]);
                    break;
                case poiTypeLookup.Park:
                    _tempOutdoor.push(toSort[i]);
                    break;
                case poiTypeLookup.AirPort:
                    Transportation.push(toSort[i]);
                    break;
                case poiTypeLookup.BusStation:
                    _temp1Transportation.push(toSort[i]);
                    break;
                case poiTypeLookup.Subway:
                    _temp2Transportation.push(toSort[i]);
                    break;
            }
        }
        if (_tempFoodDining.length > 0)
            FoodDining = FoodDining.concat(_tempFoodDining);
        if (_temp1Transportation.length > 0)
            Transportation = Transportation.concat(_temp1Transportation);
        if (_temp2Transportation.length > 0)
            Transportation = Transportation.concat(_temp2Transportation);
        if (_tempOutdoor.length > 0)
            Outdoor = Outdoor.concat(_tempOutdoor);
        if (_tempEducation.length > 0)
            Education = Education.concat(_tempEducation);
            
        
        if (Education.length > 0)
            _sortedItems.push(Education);
        if (FoodDining.length > 0)
            _sortedItems.push(FoodDining);
        if (Healthcare.length > 0)
            _sortedItems.push(Healthcare);
        if (Outdoor.length > 0)
            _sortedItems.push(Outdoor);
        if (Police.length > 0)
            _sortedItems.push(Police);
        if (Shopping.length > 0)
            _sortedItems.push(Shopping);
        if (Transportation.length > 0)
            _sortedItems.push(Transportation);
    }
    return _sortedItems;
}

function pickTab(type) {
    currentPage = 0;
    if (null != oldTab)
        oldTab.className = "";
    oldTab = type;
    oldTab.className = "on";
 
    loadMap(false);
}

function loadMap(initializing) {
    if (initializing) {

        //Build Map Object
        var mapwindow = document.getElementById('mapWindow');
        map = new MQA.TileMap(mapwindow);
        map.setZoomLevel(12);
        //Add zoom controls
        // Create a new Large Zoom control.
        var LZControl = new MQA.ZoomControl(map);
        map.addControl(LZControl, new MQA.MapCornerPlacement(MQA.MapCorner.TOP_LEFT, new MQA.Size(5, 5)));

        //Add view controls
        map.addControl(new CustomViewControl(), new MQA.MapCornerPlacement(MQA.MapCorner.TOP_LEFT, new MQA.Size(245, 5)));

        //Place MapQuest and Copyright logos
        map.setLogoPlacement(MQA.MapLogo.SCALES, new MQA.MapCornerPlacement(MQA.MapCorner.TOP_LEFT, new MQA.Size(70, 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";

        //Build Origin Poi and Add to the Map
        var imgSrc = "/App_Themes/LogicOfLennar/images/red_dot.png";
        var icon = new MQA.Icon(imgSrc, 17, 17);

        var poi = new MQA.Poi(new MQA.LatLng(latitude, longitude), icon);
        poi.setKey("origin");

        poi.setValue("infoWindowOffset", new MQA.Point(11, -1));

        MQA.EventManager.addListener(poi, "mouseover", onPoiMouseover);
        MQA.EventManager.addListener(poi, "mouseout", onPoiMouseout);

        map.addPoi(poi);
    }

    onPoiSuccess();
}

function updateMap() {
    $("#mapWindow")[0].style.display = "none";
    var parent = document.getElementById("divResults");
    removeAllChildren(parent);
    var printUrl = $("[ID $='btnPrint']")[0].href;
    var parmIndex = printUrl.indexOf('&lat');
    if (parmIndex > 0)
        $("[ID $='btnPrint']")[0].href = printUrl.substr(0, parmIndex) + "&lat=" + map.getCenter().getLatitude() + "&lng=" + map.getCenter().getLongitude();
    else
        $("[ID $='btnPrint']")[0].href += "&lat=" + map.getCenter().getLatitude() + "&lng=" + map.getCenter().getLongitude();
        
    getPOIs(map.getCenter().getLatitude(), map.getCenter().getLongitude());
}
function resetMap() {
    $("#mapWindow")[0].style.display = "none";
    var ShowAllTab = document.getElementById("All");
    pickTab(ShowAllTab);
    var parent = document.getElementById("divResults");
    removeAllChildren(parent);
    getPOIs(latitude, longitude);
}

function getPOIs(lat, lng) {

    currentPage = 0;
//    alert("requesting poi'd for lat:" + lat + ", long:" + lng);
    var dataObj = { "lat": lat, "lng": lng, "radius": DEFAULT_RADIUS, "maxCategoryMatches": MAX_MATCHES };

    $.ajax({
        type: "POST",
        data: JSON.stringify(dataObj),
        url: "/findhome/poi.aspx/GetPois",
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        success: function(data, textStatus) {
//        alert(data.d.length+" points returned")
            poiJson = data.d;
            fieldName = "D";
            onPoiSuccess();
        }
    });
    
}

function filterJson() {
    if ((oldTab == null)||(oldTab.id === 'All')) return poiJson;
    var items = [];
    var resultLength = poiJson.length;
    for (var i = 0; i < resultLength; i++) {
        var point = poiJson[i];
        if ((oldTab.id === 'FoodDining' && (point.DT == poiTypeLookup.Grocery || point.DT == poiTypeLookup.Restaurant)) ||
            (oldTab.id === 'Police' && (point.DT == poiTypeLookup.Police)) ||
            (oldTab.id === 'HealthCare' && (point.DT == poiTypeLookup.Healthcare)) ||
            (oldTab.id === 'Shopping' && (point.DT == poiTypeLookup.Shopping)) ||
            (oldTab.id === 'Education' && (point.DT == poiTypeLookup.College || point.DT == poiTypeLookup.School)) ||
            (oldTab.id === 'Outdoor' && (point.DT == poiTypeLookup.Golf || point.DT == poiTypeLookup.Park)) ||
            (oldTab.id === 'Transportation' && (point.DT == poiTypeLookup.AirPort || point.DT == poiTypeLookup.BusStation || point.DT == poiTypeLookup.Subway))) {
            items.push(point);
        }
    }

    return items;
}

function buildPoiResultTable(items) {
    var resultLength = items.length;
    var poiCollection = new MQA.ShapeCollection();
    poiCollection.setName("mapPois");
    
    //Build results table
    var tbl = document.createElement("table");
    tbl.cellPadding = 0;
    tbl.cellSpacing = 0;
    tbl.border = 0;
    tbl.className = "resultstable";

    var tr, td, th, img, a, b, distance, time, imgSrc;
    var spacer;

    var rowItt = 0;
    var cellItt = 0;

    tr = tbl.insertRow(rowItt++);
    cellItt = 0; //reset Cell itterator
    tr.id = "trhead";

    td = tr.insertCell(cellItt++);
    td.className = "poi_name";
    td.innerHTML = "<a href=\"#\" onclick=\"sortJson('N'); return false;\">Name</a>";

    td = tr.insertCell(cellItt++);
    td.className = "poi_type";
    td.innerHTML = "<a href=\"#\" onclick=\"sortJson('DT'); return false;\">Type</a>";

    td = tr.insertCell(cellItt++);
    td.className = "poi_add";
    td.innerHTML = "<a href=\"#\" onclick=\"sortJson('A'); return false;\">Address</a>";

    td = tr.insertCell(cellItt++);
    td.className = "poi_phn";
    td.innerHTML = "<a href=\"#\" onclick=\"sortJson('P'); return false;\">Phone</a>";

    td = tr.insertCell(cellItt++);
    td.className = "poi_dis";
    td.innerHTML = "<a href=\"#\" onclick=\"sortJson('D'); return false;\">Distance</a>";

    for (var i = currentPage * PAGE_SIZE; i < resultLength && i < (currentPage * PAGE_SIZE + PAGE_SIZE); i++) {

        // Create a new object point based on the array item.
        var point = items[i];
        // Assign Latitude and Longitude to the MapQuest Point.
        var poi = new MQA.Poi(new MQA.LatLng(point.Lat, point.Lng));
        // Assign the String Builder string to the point.
        points[point.I] = BuildInfoContentHTML(point)
        poi.setKey(point.I);
        
        // Set the Icon's properties.
        var imgSrc = "/App_Themes/LogicOfLennar/images/mq_icons/" + point.DT + ".gif";
        icon = new MQA.Icon(imgSrc, 20, 20);
        // Associate the Icon to the Point.
        poi.setIcon(icon);

        MQA.EventManager.addListener(poi, "mouseover", onPoiMouseover);
        MQA.EventManager.addListener(poi, "mouseout", onPoiMouseout);
        // Add point to the collection.
        poiCollection.add(poi);



        //Build each Table row and add in events for mouseover and mouseout
        tr = tbl.insertRow(rowItt++);
        cellItt = 0; //reset Cell itterator
        tr.id = "tr1_" + point.I;

        td = tr.insertCell(cellItt++);
        td.id = "td1_" + point.I;

        img = document.createElement("img");
        img.src = imgSrc;
        img.id = "img_" + point.I;
        td.appendChild(img);
        td.className = "poi_name";
        td.appendChild(document.createTextNode(point.N));

        td = tr.insertCell(cellItt++);
        td.id = "td2_" + point.I;
        //Get Type Text
        td.appendChild(document.createTextNode(poiTypeLookup.GetTypeString(point.DT)));
        td.className = "poi_type";

        var address = new StringBuilder();
        address.append(GetAddressString(point));

        td = tr.insertCell(cellItt++);
        td.id = "td3_" + point.I;
        td.className = "poi_add";
        td.appendChild(document.createTextNode(address.toString()));

        td = tr.insertCell(cellItt++);
        td.id = "td2_" + point.I;
        //Get Type Text
        td.appendChild(document.createTextNode(point.P));
        td.className = "poi_type";

        //Display the Distance and Time from the Origin
        td = tr.insertCell(cellItt++);
        td.className = "poi_dis";

        td.id = "td5_" + point.I;
        spacer = false;
        b = document.createElement("b");
        b.id = "a1_" + point.I;

        b.appendChild(document.createTextNode(point.D + " Miles"));
        td.appendChild(b);


    }

    tr = tbl.insertRow(rowItt++);
    td = tr.insertCell(0);
    td.colSpan = 6;
    td.innerHTML = buildPager(resultLength);
    if ((oldTab == null) || (oldTab.id == "Education")||(oldTab.id == "All")) {
        if ((communityName != null) && (communityDBid != null)) {
            tr = tbl.insertRow(rowItt++);
            td = tr.insertCell(0);
            td.colSpan = 6;

            td.innerHTML = "School data is representative and proximity of a school may not be an indicator of eligibility for attendance. Please <a href=\"#\" onclick='showModal(\"community\",\"" + communityName + "\",\"" + communityDBid + "\",\"\",\"\");'>contact us</a> to determine schools in the district.";
        }
    }
    
    //Append the results to the page
    var parent = document.getElementById("divResults");
    removeAllChildren(parent);
    parent.appendChild(tbl);
    return poiCollection;
}

var fieldName = "D";

function keepOpen() {
    _cancelHide = true;
}
function allowClose() {
    _cancelHide = false;
}
function onPoiMouseout(e) {
    _cancelHide = false;
    var _t = setInterval(function() {
        if (!_cancelHide) {
            clearInterval(_t);
            $('#dialog').jqmHide();
        }
    }, 100);
}

function onError(result, context, methodName) {
    var x = 1;
}

function sortJson(field) {
    if(fieldName == field)
        poiJson = poiJson.sort(reverseSortComparison);
    else
    {
        fieldName = field;
        poiJson = poiJson.sort(sortComparison);
    }

    var items = filterJson();
    
    renderPoiCollection(buildPoiResultTable(items));

    // Set the best fit for the map.
    if (items.length > 0)
        map.bestFit(false)
        
}

function reverseSortComparison(r1,r2){
    return sortComparison(r2,r1);
}

function sortComparison(r1, r2) {

    var v1 = r1[fieldName];
    var v2 = r2[fieldName];
    if (fieldName == "DT") {
        v1 = poiTypeLookup.GetTypeString(v1);
        v2 = poiTypeLookup.GetTypeString(v2);
    }
    if (fieldName == "A") {
        v1 = v1 + " " + r1.C + ", " + r1.S;
        v2 = v2 + " " + r2.C + ", " + r2.S;
    }
    if (v1 === v2 || (v1 == null && v2 == null))
        return 0;
    else if (v1 == null) {
        return 1;
    }
    else if (v2 == null) {
        return -1;
    }
    else {
        if (isNaN(parseFloat(v1)) || isNaN(parseFloat(v2)))
            return (v1 < v2) ? -1 : 1;
        else
            return parseFloat(v1) - parseFloat(v2);
    }
}

function buildPager(resultCount) {
    var ret = [];

    if (PAGE_SIZE < resultCount) {
        ret.push("Page");
        if (currentPage > 0) {
            ret.push("<a href=\"#\" class=\"pgEmpty\" onclick=\"changePage(0); return false;\"><img src=\"/App_Themes/LogicOfLennar/images/pager/firstpage.gif\" border=\"0\"/></a>");
            ret.push("<a href=\"#\" class=\"pgEmpty\" onclick=\"changePage(" + (currentPage - 1) + "); return false;\"><img src=\"/App_Themes/LogicOfLennar/images/pager/prevpage.gif\" border=\"0\"/></a>");
        }
        for (var i = 0; i * PAGE_SIZE < resultCount; i++) {
            if (currentPage != i) {
                //display link to page
                ret.push("<a href=\"#\" onClick=\"changePage(" + i + "); return false;\">" + (i + 1) + "</a>");
            } else {
            ret.push("<a href=\"#\" class=\"current\" onClick=\"changePage(" + i + "); return false;\">" + (i + 1) + "</a>");
            }
        }
        if (((currentPage+1) * PAGE_SIZE) < resultCount) {
            ret.push("<a href=\"#\" class=\"pgEmpty\" onclick=\"changePage(" + (currentPage + 1) + "); return false;\"><img src=\"/App_Themes/LogicOfLennar/images/pager/nxtpage.gif\" border=\"0\"/></a>");
            ret.push("<a href=\"#\" class=\"pgEmpty\" onclick=\"changePage(" + (Math.ceil(resultCount / PAGE_SIZE) - 1) + "); return false;\"><img src=\"/App_Themes/LogicOfLennar/images/pager/lastpage.gif\" border=\"0\"/></a>");
        }
    }
    return "<div class=\"pager\">" + ret.join('') + "</div>";
}

function onPoiSuccess() {
    //Hide tabs that don't have any points
    poiTypePresent.setSource(poiJson);
    if (!poiTypePresent.Education)
        $('#Education').parent().css("display", "none");
    else
        $('#Education').parent().css("display", "");

    if (!poiTypePresent.FoodDining)
        $('#FoodDining').parent().css("display", "none");
    else
        $('#FoodDining').parent().css("display", "");
        
    if (!poiTypePresent.Healthcare)
        $('#HealthCare').parent().css("display", "none");
    else
        $('#HealthCare').parent().css("display", "");
        
    if (!poiTypePresent.Outdoor)
        $('#Outdoor').parent().css("display", "none");
    else
        $('#Outdoor').parent().css("display", "");
        
    if (!poiTypePresent.Police)
        $('#Police').parent().css("display", "none");
    else
        $('#Police').parent().css("display", "");
        
    if (!poiTypePresent.Shopping)
        $('#Shopping').parent().css("display", "none");
    else
        $('#Shopping').parent().css("display", "");
        
    if (!poiTypePresent.Todo)
        $('#ToDo').parent().css("display", "none");
    else
        $('#ToDo').parent().css("display", "");
        
    if (!poiTypePresent.Transportation)
        $('#Transportation').parent().css("display", "none");
    else
        $('#Transportation').parent().css("display", "");
        
    
    // Filter the current category
    var items = filterJson();

    // Add or replace the Collection to the map object.
    
    renderPoiCollection(buildPoiResultTable(items));

    // Set the best fit for the map.
    if (items.length > 0)
        map.bestFit(false);
    else
        map.setCenter(new MQA.LatLng(latitude, longitude));

    $("#mapWindow")[0].style.display = "";
}

function renderPoiCollection(poiCollection) {
    if (map.getShapeCollection(poiCollection.collectionName) == null) {
        map.addShapeCollection(poiCollection);
    }
    else {
        map.replaceShapeCollection(poiCollection, poiCollection.collectionName);
    }
}
function GetAddressStringLine2(point)
{
    var spacer = false;
    var sb = new StringBuilder();
    if (point.C != "") {
        sb.append(point.C);
        spacer = true;
    }

    if (point.S != "") {
        if (spacer) {
            sb.append(", ");
        }
        sb.append(point.S);
        spacer = true;
    }

    return sb.toString();
}
function GetAddressStringParms(A, C, S) {
    var point = {"A":A, "C": C, "S":S};
    return GetAddressString(point);
}
function GetAddressString(point) {
    var spacer = false;
    var sb = new StringBuilder();
    
    if (point.A != "") {
        sb.append(point.A);
        spacer = true;
    }
    if (point.C != "") {
        if (spacer) {
            sb.append(", ");
        }
        sb.append(point.C);
        spacer = true;
    }

    if (point.S != "") {
        if (spacer) {
            sb.append(", ");
        }
        sb.append(point.S);
        spacer = true;
    }

    return sb.toString();
}

function formatPrice(price) {
    var length = String(price).length;
    var sbPrice = new StringBuilder();

    switch (length) {
        case 4:
            sbPrice.append("$");
            sbPrice.append(price.substring(0, 1));
            sbPrice.append("k");
            break;
        case 5:
            sbPrice.append("$");
            sbPrice.append(price.substring(0, 2));
            sbPrice.append("k");
            break;
        case 6:
            sbPrice.append("$");
            sbPrice.append(price.substring(0, 3));
            sbPrice.append("k");
            break;
        case 7:
            sbPrice.append("$");
            sbPrice.append(price.substring(0, 1));
            sbPrice.append(".");
            sbPrice.append(price.substring(1, 2));
            sbPrice.append("m");
            break;
    }

    return sbPrice.toString();
}

function heightTest(arg) {}

function BuildInfoContentHTML(point) {
    var container = document.createElement("div");
    var htmlElement = document.createElement("div");
    htmlElement.setAttribute("class", "modal");
    if (point.N != "") {
        var poiName = document.createElement("b");
        poiName.appendChild(document.createTextNode(point.N));
        htmlElement.appendChild(poiName);
        if (point.D != "") {
            htmlElement.appendChild(document.createTextNode(" (" + point.D + "mi.)"));
        }
        htmlElement.appendChild(document.createElement("br"));
    }
    var typeString = poiTypeLookup.GetTypeString(point.DT);
    if (!(typeString === undefined)) {
        var poiType = document.createElement("b");
        poiType.appendChild(document.createTextNode(typeString));
        htmlElement.appendChild(poiType);
        htmlElement.appendChild(document.createElement("br"));
    }
    if (point.A != "" || point.N != "") {
        htmlElement.appendChild(document.createTextNode(point.A));
        htmlElement.appendChild(document.createElement("br"));
        htmlElement.appendChild(document.createTextNode(GetAddressStringLine2(point)));
    }
    if (point.P != "") {
        htmlElement.appendChild(document.createElement("br"));
        var poiPhone = document.createElement("span");
        poiPhone.className = "poiCardPhone";
        
        htmlElement.appendChild(document.createTextNode( point.P));
    }
    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
    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(poi);
        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;
    html = points[this.key];
    
    $('#ttest_cell')[0].innerHTML = html;
    $('#ttest_cell')[0].style.width = "";
    $('#ttest_cell')[0].style.height = "";
    $('#ttest_cell')[0].style.whiteSpace = "normal";

    var maxWidth = $('#ttest_cell')[0].childNodes[0].clientWidth;
    var maxHeight = $('#ttest_cell')[0].childNodes[0].clientHeight;

    if (typeof (maxWidth) == "undefined" && typeof (maxHeight) == "undefined") {
        $('#ttest_cell')[0].style.whiteSpace = "nowrap";
    }
    else {
        if (typeof (maxWidth) != "undefined") {
            $('#ttest_cell')[0].style.width = maxWidth + "px";
        }
        if (typeof (maxHeight) != "undefined") {
            $('#ttest_cell')[0].style.height = maxHeight + "px";
        }
    }

    var recheck = false;
    var myWidth = $('#ttest_cell').width() + 40;
    var myHeight = $('#ttest_cell').height();
    if (myWidth < 200) {
        recheck = true;
        myWidth = 200;
    }
    if (myWidth > 800) {
        recheck = true;
        myWidth = 800;
    }
    if (recheck) {
        $('#ttest_cell')[0].innerHTML = html;
        $('#ttest_cell')[0].style.whiteSpace = "normal";
        $('#ttest_cell')[0].style.width = myWidth + "px";
        myHeight = $('#ttest_cell').height();
    }
    $('#pop_content')[0].innerHTML = html;
    $('#pop_dialog_table')[0].style.width = myWidth + "px";

    // 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 = typeof (e.domEvent.target) == "undefined" ? -4 : -1;
    var pointerOffsetY = typeof (e.domEvent.target) == "undefined" ? -4 : -1;

    var mapOffsetObj = $('#mapWindow').offset();
    var mapOffsetX = mapOffsetObj.left; //$('#mapWindowWrapper')[0].offsetLeft;
    var mapOffsetY = mapOffsetObj.top; //$('#mapWindowWrapper')[0].offsetTop;
    //alert("xoffset:"+ mapOffsetX + "yoffset:" + mapOffsetY + "offset("+mapOffsetObj.left +","+ mapOffsetObj.top +")");
    // Determine the map window dimensions
    var mapWidth = map.width;
    var mapHeight = map.height;

    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 = typeof (e.domEvent.target) == "undefined" ? (e.domEvent.clientY - e.domEvent.offsetY - e.domEvent.srcElement.offsetTop) : (e.domEvent.clientY - e.domEvent.layerY);
    var leftPos = typeof (e.domEvent.target) == "undefined" ? (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;

    $('#popup-pointer-btm')[0].style.visibility = "hidden";
    $('#popup-pointer-rt')[0].style.visibility = "hidden";
    $('#popup-pointer-lt')[0].style.visibility = "hidden";
    $('#popup-pointer-top')[0].style.visibility = "hidden";
    $('#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;

    // Calculate the horizontal alignment based on a virtual grid of thirds
    var horizontalPos = 'center';
    if (mapX < mapWidth / 3) {
        horizontalPos = 'left';
        posX = leftPos + iconWidth + 12;
        posY += 16;
        $('#popup-pointer-lt')[0].style.visibility = "visible";
        $('#popup-pointer-lt')[0].style.top = ((myHeight / 2) + 3) + "px";
    }
    else if ((mapX > (mapWidth / 3) * 2) && ((posX - (dialogWidth / 2)) >= 0)) {
        horizontalPos = 'right';
        posX = rightPos - Math.ceil(iconWidth / 2) + 2;
        posY += 16;
        $('#popup-pointer-rt')[0].style.visibility = "visible";
        $('#popup-pointer-rt')[0].style.left = (dialogWidth - 2) + "px";
        $('#popup-pointer-rt')[0].style.top = ((myHeight / 2) + 3) + "px";
    }
    if (posX < 0 && (posX + dialogWidth) <= browseWidth && horizontalPos != 'left') {
        if (horizontalPos == 'center') {
            posY += 16;
        }
        horizontalPos = 'left';
        posX = leftPos + iconWidth + 12;
        $('#popup-pointer-rt')[0].style.visibility = "hidden";
        $('#popup-pointer-lt')[0].style.visibility = "visible";
        $('#popup-pointer-lt')[0].style.top = ((myHeight / 2) + 3) + "px";
    }
    if (((posX < 0 && horizontalPos == 'right') || ((leftPos + iconWidth + 12 + dialogWidth) > browseWidth && horizontalPos == 'left')) && rightPos > 0 && (centerPos + (dialogWidth / 2)) < browseWidth) {
        horizontalPos = 'center';
        posX = centerPos;
        $('#popup-pointer-rt')[0].style.visibility = "hidden";
        $('#popup-pointer-lt')[0].style.visibility = "hidden";
    }

    // 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;

    // Calculate the vertical alignment based on a virtual grid of thirds
    var verticalPos = 'middle';
    if (mapY < mapHeight / 2) {
        verticalPos = 'top';
        if (horizontalPos == 'center') {
            posY = topPos + iconHeight + 13;
            $('#popup-pointer-top')[0].style.visibility = "visible";
            $('#popup-pointer-top')[0].style.left = ((dialogWidth / 2) + (iconWidth / 2) - 5) + "px";
        }
    }
    else if (mapY > mapHeight / 2) {
        verticalPos = 'bottom';
        if (horizontalPos == 'center') {
            posY = bottomPos - iconHeight + 19;
            $('#popup-pointer-btm')[0].style.visibility = "visible";
            $('#popup-pointer-btm')[0].style.left = ((dialogWidth / 2) + (iconWidth / 2) - 5) + "px";
        }
    } else if (horizontalPos == 'center') {
        verticalPos = 'top';
        posY = topPos + iconHeight + 13;
        $('#popup-pointer-top')[0].style.visibility = "visible";
        $('#popup-pointer-top')[0].style.left = ((dialogWidth / 2) + (iconWidth / 2) - 5) + "px";
    }


    // NOTE: Need to re-evaluate the flyout position with respect to the scroll offset

    // Set the dialog position
    $('#dialog')[0].style.top = posY + scrollTop + pointerOffsetY - mapOffsetY +"px";
    $('#dialog')[0].style.left = posX + scrollLeft + pointerOffsetX - mapOffsetX + "px";

    // Show the dialog
    $('#dialog').jqmShow();
}

function scrollToSearchResult(poiid) {
    //alert('Scrolling to Search Result');
}




