﻿//Global Variables
var fromPrice;
var toPrice;
var sortedArray = new Array();
var commNameArray = new Array();
var commPriceArray = new Array();
var priceArrayUnique = new Array();
var noBossCommsArray = new Array();
var nameArrow = arrowAsc;
var priceArrow = arrowAsc;
var sort = "";
var bossSort = "A";
var currentBrowserScrollHeight = 351;
var myPreviousFromPrice = 0;
var myPreviousToPrice = 0;


// Initialize metro area page
var map;
var communityData = new Array();
var divOfferLightBox;
var isOLoaded = false;
var pageTrackingCode = "UT_Metro";
var innerCommTableHeight = "359px";

var divTestimonialLightBox;
function InitPage() {
    //Initialize inline form
    InitializeInlineForm();
    
    $(window).unload(function() {
        removeMarkers();
        google.maps.event.clearInstanceListeners(map);
    });

    //check if there are no banner for offer
    //if none hide div
    if ($("div.offerBanner").children().length == 0) $("div.offerBanner").hide();
    else {
        divOfferLightBox = new YAHOO.widget.Overlay("divOfferLightBox", { visible: false, width: "0px", height: "0px" });
        divOfferLightBox.render();

        $("a#lnkOffer").click(function() {
            var offerKey = $(this).attr("rel");
            OpenOfferOverlay(offerKey);
        });
    }
    
    divTestimonialLightBox = new YAHOO.widget.Overlay("divTestimonialLightBox", { visible: false, width: "500px", height: "400px" });
    divTestimonialLightBox.render();
    
    //Retrieve Browser Type
    userBrowser = BrowserType();
    //Browser Fixes
    //Calculate community list title
    var offsetHeight = $("#communityListTableTitle").attr("offsetHeight") - 20;
    var communityDivHeight;
    switch (userBrowser) {
        case "msie":
            currentBrowserScrollHeight = 345;
            communityDivHeight = $("#CommunityDiv").height() - offsetHeight;
            innerCommTableHeight = (365 - offsetHeight) + "px";
            $("#CommunityDiv").css({ height: communityDivHeight + "px" });
            break;
        case "mozilla":
            currentBrowserScrollHeight = 348;
            $("#divSelect").css({ 'padding-bottom': '19px' });
            $("#divDrop").css({ 'margin-top': '11px' });
            $(".chkboxes").css({ 'padding-left': '3px' });
            $(".chkboxes").css({ 'padding-bottom': '5px' });
            communityDivHeight = 390 - offsetHeight;
            $("#CommunityDiv").css({ height: communityDivHeight + "px" });
            innerCommTableHeight = (373 - offsetHeight) + "px";
            $(".divChooseSearchQuickAvail").css({ marginTop: "0px"});
            break;
        case "safari":
            currentBrowserScrollHeight = 345;
            $("#divSelect").css({ 'padding-bottom': '12px' });
            $("#divDrop").css({ 'margin-top': '9px' });
            $(".chkboxes").css({ 'padding-left': '3px' });
            $(".chkboxes").css({ 'padding-bottom': '7px' });
            communityDivHeight = 390 - offsetHeight;
            $("#CommunityDiv").css({ height: communityDivHeight + "px" });
            innerCommTableHeight = (367 - offsetHeight) + "px";
            if (navigator.userAgent.indexOf("Mac OS") > -1) {
                currentBrowserScrollHeight = 428;
                communityDivHeight = 390 - offsetHeight;
                $("#CommunityDiv").css({ height: communityDivHeight + "px" });
                innerCommTableHeight = (367 - offsetHeight) + "px";
            }
            $(".divChooseSearchQuickAvail").css({ marginTop: "0px" });
            break;
        case "opera":
            $("#divSelect").css({ 'padding-bottom': '10px' });
            $("#divDrop").css({ 'margin-top': '11px' });
            $(".chkboxes").css({ 'padding-left': '3px' });
            $(".chkboxes").css({ 'margin-bottom': '3px' });
            break;
    }


    if (!fakeMetro) {

        var data = YAHOO.lang.JSON.parse(jSon);

        communityData = data.Communities;


        createBorder($("#col1"), $("#hidColumn1").html(), "auto", 10, false, "#F2F3EC", "#000000");
        if ($("#hidColumn2").html() != null) {
            createBorder($("#col2"), $("#hidColumn2").html(), "auto", 10, false, "#F2F3EC", "#000000");
        }
        if ($("#hidColumn3").html() != null) {
            createBorder($("#col3"), $("#hidColumn3").html(), "auto", 10, false, "#F2F3EC", "#000000");
        }

        // Get min and max prices for all boss communities for initialization of the
        //Slider
        var commMinPriceArray = new Array();
        var commMaxPriceArray = new Array();
        for (var i = 0; i < communityData.length; i++) {
            var bossComm = communityData[i].WsmetroBosscommunities;
            var minInBoss = new Array();
            var maxInBoss = new Array();
            if (bossComm.length != 0) {
                for (var j = 0; j < bossComm.length; j++) {
                    if (bossComm[j].MinPrice != 0) {
                        minInBoss.push(bossComm[j].MinPrice);
                    }

                    maxInBoss.push(bossComm[j].MaxPrice);
                }
            }
            else {
                noBossCommsArray.push(communityData[i]);
            }

            if (minInBoss.length > 0) {
                commMinPriceArray.push(Math.min.apply(Math, minInBoss));
                commMinPriceArray.push(Math.max.apply(Math, minInBoss));
            }
            if (maxInBoss.length > 0) {
                commMaxPriceArray.push(Math.max.apply(Math, maxInBoss));
            }
            commNameArray[i] = communityData[i].Name;
        }
        commPriceArray = commMinPriceArray;
        commPriceArray.sort(sorterWSByPrice);
        for (var i = 0; i < commPriceArray.length; i++) {
            if (i > 0) {
                if (commPriceArray[i - 1] != commPriceArray[i]) {
                    priceArrayUnique.push(commPriceArray[i]);
                }
            } else {
                priceArrayUnique.push(commPriceArray[i]);
            }

        }


        //alert(priceArrayUnique);
        var min = Math.min.apply(Math, commMinPriceArray);
        var max = Math.max.apply(Math, commMaxPriceArray);
        min = Math.floor(min / 1000) * 1000;
        max = Math.ceil(max / 1000) * 1000;

        fromPrice = min;
        toPrice = max;
        MapInit(false);
        $("#selectMin").change(function() {

            var st = "";
            if ($(this).val() == "@")
                fromPrice = min;
            else
                fromPrice = parseInt($(this).val());

            if ($("#selectMax").val() == "@")
                toPrice = max;
            else
                toPrice = parseInt($("#selectMax").val());

            if (fromPrice <= toPrice) {
                TableInit(sortByPrice);
                MapInit(true);
                myPreviousFromPrice = fromPrice;
                myPreviousToPrice = toPrice;
            } else {
                alert(validationMessage);
                fromPrice = myPreviousFromPrice;
                toPrice = myPreviousToPrice;
                $("#selectMin").val(fromPrice);
                $("#selectMax").val(toPrice);
            }
        });
        $("#selectMax").change(function() {
            var st = "";
            if ($("#selectMin").val() == "@")
                fromPrice = min;
            else
                fromPrice = parseInt($("#selectMin").val());
            if ($(this).val() == "@")
                toPrice = max;
            else
                toPrice = parseInt($(this).val());
            if (fromPrice <= toPrice) {
                TableInit(sortByPrice);
                MapInit(true);
                myPreviousFromPrice = fromPrice;
                myPreviousToPrice = toPrice;
            } else {
                alert(validationMessage);
                fromPrice = myPreviousFromPrice;
                toPrice = myPreviousToPrice;
                $("#selectMin").val(fromPrice);
                $("#selectMax").val(toPrice);
            }
        });
        sortByName();
        var prePrice = 0;
        var currPrice = 0;
        for (var i = min; i < max; i = i + (max - min) / 10) {
            currPrice = convetToPricedFromText(Math.round(i));
            if (currPrice != prePrice) {
                if (i == min)
                    $("#selectMin").append("<option value=" + Math.round(i) + " selected>" + currPrice + "</option>");
                else
                    $("#selectMin").append("<option value=" + Math.round(i) + ">" + currPrice + "</option>");
                $("#selectMax").append("<option value=" + i + ">" + currPrice + "</option>");
            }
            prePrice = currPrice;
        }
        var priceMax = convetToPricedFromText(max);
        $("#selectMax").append("<option value=" + Math.round(i) + " selected>" + priceMax + "</option>");
    }

    var isOfferOpen = false;
    //Open overlay if action is set 11/17/2010
    var action = $.urlParam("action");
    switch (action) {
        case "open_offer":
            if (offerKey != -1) {
                OpenOfferOverlay(offerKey);
                isOfferOpen = true;
            }
            break;
        default:
            break;
    }

    //Check if exact offer id is passed
    var offer = $.urlParam("offerID");
    if (offerKey != -1 && offerKey == offer && !isOfferOpen)
        OpenOfferOverlay(offerKey);
}

function addCommas(nStr) {
    nStr += '';
    x = nStr.split('.');
    x1 = x[0];
    x2 = x.length > 1 ? '.' + x[1] : '';
    var rgx = /(\d+)(\d{3})/;
    while (rgx.test(x1)) {
        x1 = x1.replace(rgx, '$1' + ',' + '$2');
    }
    return x1 + x2;

}
//functions for lightbox
function OpenOfferOverlay(offerKey) {
    Reposition_Curtain();

    var divCurtain = YAHOO.util.Dom.get("divCurtain");
    YAHOO.util.Dom.setStyle(divCurtain, "display", "block");

    $("#ifrOffer").show();

    divOfferLightBox.cfg.setProperty("height", "580px");
    divOfferLightBox.cfg.setProperty("width", "655px");

    divOfferLightBox.show();

    $("#ifrOffer").attr("src", lfSource + offerKey);

    Reposition_OfferOverlay();
}

var Reposition_OfferOverlay = function() {
    divOfferLightBox.center();
}

function CloseOfferOverlay() {
    var divCurtain = YAHOO.util.Dom.get("divCurtain");
    YAHOO.util.Dom.setStyle(divCurtain, "display", "none");

    divOfferLightBox.cfg.setProperty("height", "0px");
    divOfferLightBox.cfg.setProperty("width", "0px");

    divOfferLightBox.hide();
}

function OpenTestimonialOverlay(offerKey) {
    Reposition_Curtain();

    var divCurtain = YAHOO.util.Dom.get("divCurtain");
    YAHOO.util.Dom.setStyle(divCurtain, "display", "block");

    divTestimonialLightBox.cfg.setProperty("height", "400px");

    divTestimonialLightBox.show();

    Reposition_TestimonialOverlay();
}

var Reposition_TestimonialOverlay = function() {
    divTestimonialLightBox.center();
}

function CloseTestimonialOverlay() {
    var divCurtain = YAHOO.util.Dom.get("divCurtain");
    YAHOO.util.Dom.setStyle(divCurtain, "display", "none");

    divTestimonialLightBox.cfg.setProperty("height", "0px");

    divTestimonialLightBox.hide();
}

//End Lightbox code
function MapInit(isLoaded) {
    var singleChecked = YAHOO.util.Dom.get("cbxHTSingle").checked;
    var townChecked = YAHOO.util.Dom.get("cbxHTTownhome").checked;
    var condoChecked = YAHOO.util.Dom.get("cbxHTCondo").checked;
    var quickDeliveryChecked = YAHOO.util.Dom.get("cbxHTQuick").checked;
    //GUnload();
    InitMap("map", fromPrice, toPrice, singleChecked, townChecked, condoChecked, quickDeliveryChecked, isLoaded);
}

function TableInit(isSortByPrice) {
    var CommunityDiv = YAHOO.util.Dom.get("CommunityDiv");


    var numComms = YAHOO.util.Dom.get("num-communities");
    var singleChecked = YAHOO.util.Dom.get("cbxHTSingle").checked;
    var townChecked = YAHOO.util.Dom.get("cbxHTTownhome").checked;
    var condoChecked = YAHOO.util.Dom.get("cbxHTCondo").checked;
    var quickDeliveryChecked = YAHOO.util.Dom.get("cbxHTQuick").checked;

    //check for isSortByPrice
    if (isSortByPrice == undefined && sort == "P")
        isSortByPrice = 1;

    var tableRows = "";
    var count = 0;

    for (var i = 0; i < sortedArray.length; i++) {
        var showComm = false;
        var greenHomeText = "";
        if (sortedArray[i].IsGreen)
            greenHomeText = "<div class='greenHome'>" + gHT + "</div>";
        var link = sortedArray[i].ShortcutUrl;
        if (link == "") {
            var str = "";
            link = manualLinkPrefix.replace("/" + shortcutPrePath + "/", "/") + "Community.aspx?CommunityID=" + sortedArray[i].WebsiteCommunityKey;
        }
        else {
            link = manualLinkPrefix + link;
        }

        var bossComms = sortedArray[i].WsmetroBosscommunities;
        if (bossComms.length == 1) {
            if ((bossComms[0].MinPrice <= toPrice && bossComms[0].MaxPrice >= fromPrice) || bossComms[0].MinPrice == 0) {
                if (singleChecked == true && bossComms[0].ProductTypeName == "Single Family")
                    showComm = true;

                if (townChecked == true && bossComms[0].ProductTypeName == "Townhome")
                    showComm = true;

                if (condoChecked == true && bossComms[0].ProductTypeName == "Condominum")
                    showComm = true;

                if (showComm) {
                    var productName = bossComms[0].ProductTypeName;
                    if (culture == "es-ES")
                        productName = bossComms[0].ProductTypeNameEs;
                    if (quickDeliveryChecked == true) {
                        if (bossComms[0].ActiveInventoryCount > 0) {                            
                            tableRows = tableRows + "<tr><td class='contentDisplayNameOne'><a href='" + link + "' onmouseover='OpenBubble(sortedArray[" + i + "]);'>" + sortedArray[i].Name + "</a>" + greenHomeText + "<div class='cityDiv'>" + sortedArray[i].City + ", " + sortedArray[i].State + "</div></td><td  class='contentProductName HomeTypePadding' style='text-align:center;width:106px'>" + productName + "</td><td class='PricedFromPadding contentMinPrice' style='text-align: center;width:90px;'>" + convetToPricedFromText(bossComms[0].MinPrice) + "</td></tr>";
                            count++;
                        }
                    }
                    else {                        
                        tableRows = tableRows + "<tr><td class='contentDisplayNameOne' valign='middle'><a href='" + link + "' onmouseover='OpenBubble(sortedArray[" + i + "]);'>" + sortedArray[i].Name + "</a>" + greenHomeText + "<div class='cityDiv'>" + sortedArray[i].City + ", " + sortedArray[i].State + "</div></td><td class='contentProductName HomeTypePadding' style='text-align:center;width:106px'>" + productName + "</td><td class='PricedFromPadding contentMinPrice' style='text-align: center;width:90px;'>" + convetToPricedFromText(bossComms[0].MinPrice) + "</td></tr>";
                        count++;
                    }
                    tableRows += "<tr class='spacerTr'><td colspan='3'></td></tr>";
                }
            }

        }
        else {
            var parentRow = "<tr><td colspan='3'><a href='" + link + "' onmouseover='OpenBubble(sortedArray[" + i + "]);'>" + sortedArray[i].Name + "</a>" + greenHomeText + "<div class='cityDiv'>" + sortedArray[i].City + ", " + sortedArray[i].State + "</div></td></tr>";
            var childRow = "";
            var childCount = 0;
            var childIndex = 0;
            for (var j = 0; j < bossComms.length; j++) {
                if ((bossComms[j].MinPrice <= toPrice && bossComms[j].MaxPrice >= fromPrice) || bossComms[j].MinPrice == 0) {

                    if (singleChecked == true && bossComms[j].ProductTypeName == "Single Family")
                        showComm = true;

                    if (townChecked == true && bossComms[j].ProductTypeName == "Townhome")
                        showComm = true;

                    if (condoChecked == true && bossComms[j].ProductTypeName == "Condominum")
                        showComm = true;

                    if (showComm) {

                        var productName = bossComms[j].ProductTypeName;
                        if (culture == "es-ES")
                            productName = bossComms[j].ProductTypeNameEs;
                        if (quickDeliveryChecked == true) {
                            if (bossComms[j].ActiveInventoryCount > 0) {                                
                                childRow = childRow + "<tr class='commTableNameChild'><td class='contentDisplayNameChild'>" + bossComms[j].DisplayName + "</td><td class='contentProductName'>" + productName + "</td><td class='contentMinPrice'>" + convetToPricedFromText(bossComms[j].MinPrice) + "</td></tr>";
                                childCount++;
                                childIndex = j;
                            }
                        } else {
                        
                            childRow = childRow + "<tr class='commTableNameChild'><td class='contentDisplayNameChild'>" + bossComms[j].DisplayName + "</td><td class='contentProductName'>" + productName + "</td><td class='contentMinPrice'>" + convetToPricedFromText(bossComms[j].MinPrice) + "</td></tr>";
                            childCount++;
                            childIndex = j;
                        }
                    }
                }
                showComm = false;
            }
            var productName = "";
            if (bossComms.length > 0) {
                productName = bossComms[childIndex].ProductTypeName;
                if (culture == "es-ES")
                    productName = bossComms[childIndex].ProductTypeNameEs;
            }
            if (bossComms.length == 0 && isSortByPrice != 1 && !quickDeliveryChecked) {
                tableRows = tableRows + "<tr><td class='contentDisplayNameOne'><a href='" + link + "' onmouseover='OpenBubble(sortedArray[" + i + "]);'>" + sortedArray[i].Name + "</a>" + greenHomeText + "<div class='cityDiv'>" + sortedArray[i].City + ", " + sortedArray[i].State + "</div></td><td  class='contentProductName HomeTypePadding' style='text-align:center;width:106px'>" + "" + "</td><td class='PricedFromPadding contentMinPrice' style='text-align: center;width:90px;'>" + convetToPricedFromText(0) + "</td></tr>";
                tableRows += "<tr class='spacerTr'><td colspan='3'></td></tr>";
                count++;
            }
            if (childCount == 1) {
                tableRows = tableRows + "<tr><td valign='middle' class='contentDisplayNameOne'><a href='" + link + "' onmouseover='OpenBubble(sortedArray[" + i + "]);'>" + sortedArray[i].Name + "</a>" + greenHomeText + "<div class='cityDiv'>" + sortedArray[i].City + ", " + sortedArray[i].State + "</div></td><td class='contentProductName' >" + productName+ "</td><td class='PricedFromPadding contentMinPrice'>" + convetToPricedFromText(bossComms[childIndex].MinPrice) + "</td></tr>";
                tableRows += "<tr class='spacerTr'><td colspan='3'></td></tr>";
                count++;
            }
            if (childCount > 1) {
                tableRows = tableRows + parentRow + childRow;
                count++;
            }
        }
    }
    if (isSortByPrice == 1 && !quickDeliveryChecked) {
        for (var i = 0; i < noBossCommsArray.length; i++) {
            var link = noBossCommsArray[i].ShortcutUrl;
            if (link == "") {
                var str = "";
                link = manualLinkPrefix.replace("/" + shortcutPrePath + "/", "/") + "Community.aspx?CommunityID=" + noBossCommsArray[i].WebsiteCommunityKey;
            }
            else {
                link = manualLinkPrefix + link;
            }
            tableRows = tableRows + "<tr><td class='contentDisplayNameOne'><a href='" + link + "' onmouseover='OpenBubble(noBossCommsArray[" + i + "]);'>" + noBossCommsArray[i].Name + "</a>" + greenHomeText + "<div class='cityDiv'>" + noBossCommsArray[i].City + ", " + noBossCommsArray[i].State + "</div></td><td  class='contentProductName HomeTypePadding' style='text-align:center;width:106px'>" + "" + "</td><td class='PricedFromPadding contentMinPrice' style='text-align: center;width:90px;'>" + convetToPricedFromText(0) + "</td></tr>";
            tableRows += "<tr class='spacerTr'><td colspan='3'></td></tr>";
            count++;
        }
    }
    var tableHeader = "<tr id='tableHeaderTr'><td class='DisplayNameTitle'><img width='8px' height='6px' src='" + nameArrow + "' id='commArrow' /><a href='javascript:void(0)' style='padding-left: 5px;' onclick='sortByName();'>" + commListTitleCommunity + "</a></td><td class='HomeTypeTitle'>" + commListTitleHomeType + "</td><td align='left' class='PricedFromTitle'><img width='8px' height='6px' src='" + priceArrow + "' id='priceArrow' /><a href='javascript:void(0)' style='padding-left: 5px;' onclick='sortByPrice();'>" + commListTitlePricedFrom + "</a></td></tr>";
    var headTable = "<div style='padding-left:5px;padding-right:10px;'><table width='100%'>" + tableHeader + "</table></div>";
    var contentTable = "<div id='contentTable' style='width:325px;margin-left:3px;padding-left:5px;padding-right:5px;overflow-y: auto;overflow-x:hidden;max-height: " + innerCommTableHeight + ";height:" + innerCommTableHeight + "'><table class='communityTableContent'>" + tableRows + "</table></div>";
    //Clear the container
    CommunityDiv.innerHTML = "";
    if (count > 0) {
        CommunityDiv.innerHTML = headTable + contentTable;
        checkScrollBar();
        CommNum = count;

        if (count == 1)
            numComms.innerHTML = CommNum + " " + commListCriteriaMatchSingle;
        else
            numComms.innerHTML = CommNum + " " + commListCriteriaMatchMultiple;
    }
    else {
        CommunityDiv.innerHTML = commListCriteriaMatchNone;
        checkScrollBar();
        YAHOO.util.Dom.get("num-communities").innerHTML = "";
    }




}

function checkScrollBar() {
    //Scroll Bar Table alignment
    var trClassName = "commTableName";
    if ($("#contentTable").length > 0) {
        if ($("#contentTable").find("TABLE").height() < currentBrowserScrollHeight) {
            //if ($("#contentTable").height() < currentBrowserScrollHeight) {
            //var trClassName = "commTableNoScroll";

            $(".PricedFromTitle").addClass("PricedFromTitleNoScroll");
            $(".PricedFromTitle").removeClass("PricedFromTitle");
            //$(".PricedFromPadding").addClass("PricedFromPaddingNoScroll");

            //$(".DisplayNameTitle").addClass("DisplayNameTitleNoScroll");
            //$(".DisplayNameTitle").removeClass("DisplayNameTitle");


            $(".HomeTypeTitle").addClass("HomeTypeTitleNoScroll");
            $(".HomeTypeTitle").removeClass("HomeTypeTitle");

            //$(".HomeTypePadding").addClass("HomeTypePaddingNoScroll");


        }
        if (culture == "es-ES") {

            $("#tableHeaderTr TD").css("fontSize", "7pt");
            $("#tableHeaderTr TD").css("paddingBottom", "0px");

        }
        $("#contentTable tr:not(.commTableNameChild)").addClass(trClassName);
    }

}
function OpenBubble(data) {
    var imgUrlPrefix = "";


    if (document.location.href.toLowerCase().indexOf("/build/") != -1) {
        imgUrlPrefix = "../";
    }

    if (currentlyActiveMarkerIndex != null) {
        resetMarker(currentlyActiveMarkerIndex);

        if (typeof (UnFocusCommunityRow) != 'undefined') {
            for (var i = 0; i < markerArray[currentlyActiveMarkerIndex].commArray.length; i++) {
                UnFocusCommunityRow(markerArray[currentlyActiveMarkerIndex].commArray[i].Name);
            }
        }
    }

    currentlyActiveMarkerIndex = lookupMarkerIndex(data);

    google.maps.event.trigger(markerArray[currentlyActiveMarkerIndex].gMarker, 'mouseover', true, data.Name);
    if (currentlyOpenInfoWindowIndex != null)
        closeOpenInfoWindow(currentlyOpenInfoWindowIndex);

    if (!map.getBounds().contains(markerArray[currentlyActiveMarkerIndex].gMarker.getPosition()))
        map.panTo(markerArray[currentlyActiveMarkerIndex].gMarker.getPosition());
}

function resetMarkers() {

    var imgUrlPrefix = "";


    if (document.location.href.toLowerCase().indexOf("/build/") != -1) {
        imgUrlPrefix = "../";
    }
    for (var i = 0; i < markerArray.length; i++) {
        var communities = markerArray[i].commArray;
        var isGreen = false;
        for (var j = 0; j < communities.length; j++) {
            if (communities[j].IsGreen)
                isGreen = true;
        }
        markerArray[i].gMarker.setIcon(imgUrlPrefix + singleHomeImage);
        if (isGreen)
            markerArray[i].gMarker.setIcon(imgUrlPrefix + singleHomeImageGreen);
    }
}
function lookupMarker(data) {
    for (var i = 0; i < markerArray.length; i++) {
        for (var j = 0; j < markerArray[i].commArray.length; j++) {
            if (markerArray[i].commArray[j].GeoLatitude == data.GeoLatitude && markerArray[i].commArray[j].GeoLongitude == data.GeoLongitude) {
                return markerArray[i];
            }
        }
    }
    return null;
}

function lookupMarkerIndex(data) {
    for (var i = 0; i < markerArray.length; i++) {
        for (var j = 0; j < markerArray[i].commArray.length; j++) {
            if (markerArray[i].commArray[j].GeoLatitude == data.GeoLatitude && markerArray[i].commArray[j].GeoLongitude == data.GeoLongitude) {
                return i;
            }
        }
    }
    return null;
}

function removeMarkers() {
    for (var i = 0; i < markerArray.length; i++) {
        markerArray[i].gMarker.setMap(null);
    }
}
function sortByName() {
    priceArrow = noArrow;
    if (sort != "C") {
        sort = "C";
        bossSort = "A";
        commNameArray.sort();
    }
    else {
        //Reverse Direction
        commNameArray.reverse();
        sort = "";
        bossSort = "D";
    }
    if (nameArrow == arrowDesc) {
        nameArrow = arrowAsc;
    }
    else {
        nameArrow = arrowDesc
    }

    sortJSONByName();
    TableInit(0);
}


function sortByPrice() {
    nameArrow = noArrow;
    if (sort != "P") {
        sort = "P";
        bossSort = "A";
        priceArrayUnique.sort(sorterWSByPrice);
    }
    else {
        //Reverse Direction
        priceArrayUnique.reverse();
        sort = "";
        bossSort = "D";
    }
    if (priceArrow == arrowDesc) {
        priceArrow = arrowAsc;
    }
    else {
        priceArrow = arrowDesc
    }
    sortJSONByPrice();

    TableInit(1);

}
function sortJSONByName() {
    for (var i = 0; i < commNameArray.length; i++) {
        for (var j = 0; j < communityData.length; j++) {
            if (commNameArray[i] == communityData[j].Name) {
                var bossComms = communityData[j].WsmetroBosscommunities;
                var bossNameSorted = new Array();
                var destArray = new Array();
                for (var k = 0; k < bossComms.length; k++) {
                    bossNameSorted.push(bossComms[k].DisplayName);
                }
                bossNameSorted.sort();
                if (bossSort == "D")
                    bossNameSorted.reverse();
                for (var l = 0; l < bossNameSorted.length; l++) {
                    for (var k = 0; k < bossComms.length; k++) {                      
                        if (bossComms[k].DisplayName == bossNameSorted[l]) {
                            destArray.push(bossComms[k]);
                            //if matched remove from both arrays 
                            //to avoid redundant matches
                            bossComms.splice(k, 1);
                            break;
                        }
                    }
                }
                communityData[j].WsmetroBosscommunities = destArray;
                sortedArray[i] = communityData[j];
            }
        }
    }
}

function sortJSONByPrice() {
    sortedArray = new Array();
    for (var i = 0; i < priceArrayUnique.length; i++) {
        for (var j = 0; j < communityData.length; j++) {
            var bossComms = communityData[j].WsmetroBosscommunities;
            var bossCommPrices = new Array();
            for (var k = 0; k < bossComms.length; k++) {
                var addToSorted = true;
                if (priceArrayUnique[i] == bossComms[k].MinPrice) {
                    for (var l = 0; l < sortedArray.length; l++) {
                        if (sortedArray[l].Name == communityData[j].Name) {
                            addToSorted = false;
                        }
                    }
                    if (addToSorted == true) {
                        var destArray = new Array();
                        var innerBossComms = communityData[j].WsmetroBosscommunities;
                        var bossPriceSorted = new Array(innerBossComms.length);
                        for (var l = 0; l < innerBossComms.length; l++) {
                            bossPriceSorted[l] = new Array(1);
                            bossPriceSorted[l][0] = innerBossComms[l].MinPrice;
                            bossPriceSorted[l][1] = innerBossComms[l].BosscommunityKey;
                        }
                        bossPriceSorted.sort(sorterBOSSByPrice);
                        if (bossSort == "D")
                            bossPriceSorted.reverse();

                        for (var l = 0; l < bossPriceSorted.length; l++) {
                            for (var m = 0; m < innerBossComms.length; m++) {
                                if (bossPriceSorted[l][0] == innerBossComms[m].MinPrice &&
                                    bossPriceSorted[l][1] == innerBossComms[m].BosscommunityKey) {
                                    destArray.push(innerBossComms[m]);
                                }
                            }
                        }
                        communityData[j].WsmetroBosscommunities = destArray;
                        sortedArray.push(communityData[j]);
                    }
                }
            }
        }
    }
    var stopHere = "";
}

function convetToPricedFromText(price) {

    var priceString = price.toString();
    if (price > 0) {
//        if (priceString.length > 6) {
//            var rounded = priceString.substr(0, 1);
//            var rightOfDec = priceString.substr(1, 2);
//            priceString = rounded + "." + rightOfDec;
//            priceString = "$" + priceString + "Ms";
//        }
//        else {
//            if (priceString.length > 1) {
//                /*var rounded = priceString.substr(0, 2);
//                var zeros = "";
//                for (var i = 0; i < priceString.length; i++) {
//                if (i > 1) {
//                zeros = zeros + "0";
//                }
//                }
//                rounded = rounded + zeros;*/
//                var rounded = Math.round(price * .001);
//                priceString = rounded;
//                priceString = "$" + priceString + "s";
//            }
        //        }
        return "$" + addCommas(price);
    }
    else {
        return notReleasedText;
    }
    return priceString;
}
//Function to create solid objects with rounded corners
function createBorder(obj, html, cwidth, radius, nobottom, bcolor, color) {

    // Setup local variables
    var width = 1;

    // Create content element
    var content = $(document.createElement('div'))
               .addClass("qtip-content")
               .css({
                   background: bcolor,
                   color: color,
                   padding: 0,
                   cwidth: cwidth
                   //                   ,
                   //                   height: cheight + "px"

               })
               .html(html);

    if (radius === 0)
        content.css({ border: width + 'px solid ' + bcolor })
    else {
        //Create wrapper
        var wrapper = $(document.createElement('div'))
                                .addClass('qtip-contentWrapper')
                                .css({
                                    width: "auto"
                                })
                                .append(content)
                                .appendTo(obj);

        // Define borders
        var borders = {
            topLeft: [radius, radius], topRight: [0, radius],
            bottomLeft: [radius, 0], bottomRight: [0, 0]
        }

        // Define shape container elements
        var shapes = {};
        for (var i in borders) {
            shapes[i] = $(document.createElement('div'))
               .css({
                   height: radius,
                   width: radius,
                   overflow: 'hidden',
                   float: (i.search(/Left/) !== -1) ? 'left' : 'right',
                   lineHeight: 0.1
               })
        }

        // Use canvas element if supported
        if (document.createElement('canvas').getContext) {
            for (var i in borders) {
                var canvas = $(document.createElement('canvas'))
                  .attr('height', radius)
                  .attr('width', radius)
                  .css({ verticalAlign: 'top' })
                  .appendTo(shapes[i]);

                // Create corner
                var context = canvas.get(0).getContext('2d');
                context.fillStyle = bcolor;
                context.beginPath();
                context.arc(borders[i][0], borders[i][1], radius, 0, Math.PI * 2, false);
                context.fill();
            }
        }

        // Canvas not supported - Use VML (IE)
        else if ($.browser.msie || document.namespaces) {
            // Define borders
            var borders = {
                topLeft: [-90, 90, 0], topRight: [-90, 90, -radius],
                bottomLeft: [90, 270, 0], bottomRight: [90, 270, -radius]
            }

            for (var i in borders) {
                // Create VML arc
                $(document.createElement('v:arc'))
                  .attr('fill', 'true')
                  .attr('fillcolor', bcolor)
                  .attr('stroked', 'false')
                  .attr('startangle', borders[i][0])
                  .attr('endangle', borders[i][1])
                  .css({
                      width: radius * 2 + 3,
                      height: radius * 2 + 3,
                      marginLeft: (i.search(/Right/) !== -1) ? borders[i][2] - 3.5 : -1,
                      marginTop: -1,
                      verticalAlign: 'top'
                  })
                  .appendTo(shapes[i]);

                //DIGIFIX: <=7 instead of <7!!!! in the if block condition below   
                if (($.support && $.support.objectAll)
               || ($.browser.msie && parseInt($.browser.version.charAt(0)) <= 7)) {
                    if (i.search(/Left/) !== -1)
                        shapes[i].css({ marginRight: -3 })
                    else if (i.search(/Right/) !== -1)
                        shapes[i].css({ marginLeft: -3 })
                }
            }
        }

        // Create between corners
        var betweenCorners = $(document.createElement('div'))
            .addClass('qtip-betweenCorners')
            .css({
                height: radius,
                overflow: 'hidden',
                backgroundColor: bcolor,
                lineHeight: 0.1
            })

        // Create containers
        var borderTop = $(document.createElement('div'))
            .addClass('qtip-borderTop')
            .css({ height: radius })
            .append(shapes['topLeft'])
            .append(shapes['topRight'])
            .append(betweenCorners)
            .prependTo(wrapper);

        if (!nobottom) {
            var borderBottom = $(document.createElement('div'))
            .addClass('qtip-borderBottom')
            .css({ height: radius, clear: 'both' })
            .append(shapes['bottomLeft'])
            .append(shapes['bottomRight'])
            .append(betweenCorners.clone())
            .appendTo(wrapper);
        }

        // Setup container
        var sideWidth = Math.max(radius, (radius + (width - radius)))
        var vertWidth = Math.max(width - radius, 0);
        content.css({
            margin: 0,
            border: '0px solid ' + bcolor,
            borderWidth: vertWidth + 'px ' + sideWidth + 'px',
            //position: 'relative', //commented out by Derek
            clear: 'both'
        })
    }
};

// Create XML namespace and vml styles if IE
if (document.namespaces && document.namespaces["v"] == null) {
    document.namespaces.add("v", "urn:schemas-microsoft-com:vml");
    var stylesheet = document.createStyleSheet().owningElement;
    stylesheet.styleSheet.cssText = "v\\:*{behavior:url(#default#VML); display: inline-block }";
}


//custom sorter for BOSS communities passed as objects with min prices
//being properties
function sorterBOSSByPrice(comm1, comm2) {
    var price1 = comm1[0];
    var price2 = comm2[0];
    return ((price1 < price2) ? -1 : ((price1 > price2) ? 1 : 0));
}


//custom sorter for WS communities with args passed as scalar prices
function sorterWSByPrice(price1, price2) {
    return ((price1 < price2) ? -1 : ((price1 > price2) ? 1 : 0));
}
function BrowserType() {
    var _browser;
    jQuery.each(jQuery.browser, function(i, val) {
        switch (i) {
            case "msie":
                if (val) _browser = i;
                break;
            case "mozilla":
                if (val) _browser = i;
                break;
            case "safari":
                if (val) _browser = i;
            case "opera":
                if (val) _browser = i;
            default:
                break;
        }
    });
    return _browser;
}

//For getting the querystring values
//usage $.urlParam(ParamName)
$.urlParam = function(name) {
    var results = new RegExp('[\\?&]' + name + '=([^&#]*)').exec(window.location.href);
    if (!results) { return 0; }
    return results[1] || 0;
}

//support for hilite/focus on community row
var FocusCommunityRow = function(commName, isFromCommunityTable) {
    var targetCommunityEl = $("tr.commTableName a:econtains('" + commName + "')");

    var targetCommunityRowEl = targetCommunityEl.closest("tr").find("td");
    var normalColor = targetCommunityRowEl.css("background-color");
    targetCommunityRowEl.css({ "background-color": "#dedede" });
    targetCommunityRowEl.data("normalColor", normalColor);

    if (!isFromCommunityTable) {
        $("#contentTable").scrollTo(targetCommunityEl);
    }
}

var UnFocusCommunityRow = function(commName) {
    var targetCommunityEl = $("tr.commTableName a:econtains('" + commName + "')");

    var targetCommunityRowEl = targetCommunityEl.closest("tr").find("td");
    targetCommunityRowEl.css({ "background-color": targetCommunityRowEl.data("normalColor") });

}

/**
* jQuery.ScrollTo - Easy element scrolling using jQuery.
* Copyright (c) 2007-2009 Ariel Flesler - aflesler(at)gmail(dot)com | http://flesler.blogspot.com
* Dual licensed under MIT and GPL.
* Date: 5/25/2009
* @author Ariel Flesler
* @version 1.4.2
*
* http://flesler.blogspot.com/2007/10/jqueryscrollto.html
*/
; (function(d) { var k = d.scrollTo = function(a, i, e) { d(window).scrollTo(a, i, e) }; k.defaults = { axis: 'xy', duration: parseFloat(d.fn.jquery) >= 1.3 ? 0 : 1 }; k.window = function(a) { return d(window)._scrollable() }; d.fn._scrollable = function() { return this.map(function() { var a = this, i = !a.nodeName || d.inArray(a.nodeName.toLowerCase(), ['iframe', '#document', 'html', 'body']) != -1; if (!i) return a; var e = (a.contentWindow || a).document || a.ownerDocument || a; return d.browser.safari || e.compatMode == 'BackCompat' ? e.body : e.documentElement }) }; d.fn.scrollTo = function(n, j, b) { if (typeof j == 'object') { b = j; j = 0 } if (typeof b == 'function') b = { onAfter: b }; if (n == 'max') n = 9e9; b = d.extend({}, k.defaults, b); j = j || b.speed || b.duration; b.queue = b.queue && b.axis.length > 1; if (b.queue) j /= 2; b.offset = p(b.offset); b.over = p(b.over); return this._scrollable().each(function() { var q = this, r = d(q), f = n, s, g = {}, u = r.is('html,body'); switch (typeof f) { case 'number': case 'string': if (/^([+-]=)?\d+(\.\d+)?(px|%)?$/.test(f)) { f = p(f); break } f = d(f, this); case 'object': if (f.is || f.style) s = (f = d(f)).offset() } d.each(b.axis.split(''), function(a, i) { var e = i == 'x' ? 'Left' : 'Top', h = e.toLowerCase(), c = 'scroll' + e, l = q[c], m = k.max(q, i); if (s) { g[c] = s[h] + (u ? 0 : l - r.offset()[h]); if (b.margin) { g[c] -= parseInt(f.css('margin' + e)) || 0; g[c] -= parseInt(f.css('border' + e + 'Width')) || 0 } g[c] += b.offset[h] || 0; if (b.over[h]) g[c] += f[i == 'x' ? 'width' : 'height']() * b.over[h] } else { var o = f[h]; g[c] = o.slice && o.slice(-1) == '%' ? parseFloat(o) / 100 * m : o } if (/^\d+$/.test(g[c])) g[c] = g[c] <= 0 ? 0 : Math.min(g[c], m); if (!a && b.queue) { if (l != g[c]) t(b.onAfterFirst); delete g[c] } }); t(b.onAfter); function t(a) { r.animate(g, j, b.easing, a && function() { a.call(this, n, b) }) } }).end() }; k.max = function(a, i) { var e = i == 'x' ? 'Width' : 'Height', h = 'scroll' + e; if (!d(a).is('html,body')) return a[h] - d(a)[e.toLowerCase()](); var c = 'client' + e, l = a.ownerDocument.documentElement, m = a.ownerDocument.body; return Math.max(l[h], m[h]) - Math.min(l[c], m[c]) }; function p(a) { return typeof a == 'object' ? a : { top: a, left: a} } })(jQuery);

//support for exact matching JQuery selector "econtains"
$.expr[":"].econtains = function(obj, index, meta, stack) {
    return (obj.textContent || obj.innerText || $(obj).text() || "").toLowerCase() == meta[3].toLowerCase();
}
