// ----------------------------------------------------------------------------------------------
// -------------------------------------- PRODUCT SEARCH ----------------------------------------
// ----------------------------------------------------------------------------------------------

// PRODUCT SEARCH SLIDER
var isResetAll = false;
var isResetSlider = false;
var userModifiedSlider = false;
var mapLoadWaitTime = 500;
var sliderIncrement = 10000;
// var isSliderLocked = false;
var isSessionQuery = false;

var selectedCount = 0;

var priceCount = new Array(9);
var bedCount = new Array(5);
var bathCount = new Array(4);
var sqFtCount = new Array(5);
var planTypeCount = new Array(2);
var floorCount = new Array(2);
var garageCount = new Array(3);
var amenityCount = new Array(10);
var activeAdultCount = new Array(2);
var subBrandCount = new Array(1);

var productSearchValue = 'Enter City and State, or Zip';
var selectedGeoID = 0;
var selectedGeoType = "";

var geoPageTitle = "TBD"; // this is database default and is ignored value
var pageTitleStateName = "";
var pageTitleStateAbbreviation = "";
var pageTitleSubBrand = "0";

YUE.onDOMReady(function() {
    MapSearch.initialize();
});

var zipRadius = 15;

// ----------------------------------------------------------------------------------------------

// CONFIGURATION FOR PRODUCT SEARCH PAGE

var productCONFIG = {
    stateZoomLevel: 4,
    regionZoomLevel: 7,
    noClusterZoomLevel: 17,
    defaultMapZoom: function() { if (document.URL.toLowerCase().indexOf('/divosta/') >= 0) { return 6 } else { return 4 } },
    mapId: 'google-map',
    reasons: [],
    GeoAccuracy: [],
    ControlIdName: [],
    brandIds: [],
    initialize: function() {
        // reason for not finding the address on the map
        this.reasons[G_GEO_SUCCESS] = 'Success';
        this.reasons[G_GEO_MISSING_ADDRESS] = 'Missing Address: The address was either missing or had no value.';
        this.reasons[G_GEO_UNKNOWN_ADDRESS] = 'Unknown Address: No corresponding geographic location could be found for the specified address.';
        this.reasons[G_GEO_UNAVAILABLE_ADDRESS] = 'Unavailable Address: The geocode for the given address cannot be returned due to legal or contractual reasons.';
        this.reasons[G_GEO_BAD_KEY] = 'Bad Key: The API key is either invalid or does not match the domain for which it was given';
        this.reasons[G_GEO_TOO_MANY_QUERIES] = 'Too Many Queries: The daily geocoding quota for this site has been exceeded.';
        this.reasons[G_GEO_SERVER_ERROR] = 'Server error: The geocoding request could not be successfully processed.';

        // convert acccuracy to zoom level base on address found on map
        this.GeoAccuracy[0] = 3;
        this.GeoAccuracy[1] = 4;
        this.GeoAccuracy[2] = 8;
        this.GeoAccuracy[3] = 10;
        this.GeoAccuracy[4] = 12;
        this.GeoAccuracy[5] = 14;
        this.GeoAccuracy[6] = 14;
        this.GeoAccuracy[7] = 15;
        this.GeoAccuracy[8] = 16;

        // control ID name on the front end
        this.ControlIdName['stories'] = 'Stories';
        this.ControlIdName['homeType'] = 'HomeType';
        this.ControlIdName['communityType'] = 'CommunityType';
        this.ControlIdName['subBrand'] = 'SubBrand';
        this.ControlIdName['bedrooms'] = 'Bedrooms';
        this.ControlIdName['bathrooms'] = 'Bathrooms';
        this.ControlIdName['garage'] = 'Garage';
        this.ControlIdName['sqft'] = 'SqFt';
        this.ControlIdName['price'] = 'Price';
        this.ControlIdName['activeAdult'] = 'ActiveAdult';
        this.ControlIdName['poi'] = 'poi';
        this.ControlIdName['availableNow'] = 'homesAvailableNow';
        this.ControlIdName['bandb'] = 'BedroomsAndBathrooms';

        // brandID
        this.brandIds['pulte'] = 1;
        this.brandIds['delwebb'] = 2;
        this.brandIds['divosta'] = 3;
        this.brandIds['centex'] = 4;
    }
};

productCONFIG.initialize();

// ----------------------------------------------------------------------------------------------

YUE.onAvailable('communitylisting', function() {
    YUE.addListener('communitylisting', 'click', function() {
        availablehomes = [];
        availablehomes[0] = 0;
        //	    alert("here");
        SearchControlUtils.resetCheckboxRadioControls(productCONFIG.ControlIdName['availableNow'], true);
        //Pulte08.AjaxWebServices.MapService.FilterByHomesAvailableNow(brandIdList, availablehomes, MapSearch.newBounds);
    });
});

YUE.onAvailable('homes-available-now', function() {
    YUE.addListener('homes-available-now', 'click', function() {
        //alert("here in homes-available tab");
        //alert(brandIdList);
        availablehomes = [];
        availablehomes[0] = 1;
        MapSearch.toggleLoadingMessage(true);
        Pulte08.AjaxWebServices.MapService.FilterByHomesAvailableNow(brandIdList, availablehomes, MapSearch.newBounds);
        //SearchControlUtils.resetCheckboxRadioControls(productCONFIG.ControlIdName['availableNow'], false);
    });
});

// PRODUCT SEARCH STORIES BUTTON CONTROL

var storyButtonArray = [], bedroomButtonArray = [], bathroomButtonArray = [], garageButtonArray = [];
var fldHomeType = [], fldCommunityType = [], fldSubBrand = [], fldSqFt = [], fldPrice = [], fldActiveAdult = [], fldAvailableNow = [], fldPOI = [];
var brandIdList = new Array();

var planCount, communityCount;



// add click event listener to all checkbox and radio button
YUE.onDOMReady(function() {
    var curSiteName = getCurrSite().toLowerCase();
    fldHomeType = document.formProductSearch.HomeType;
    fldSqFt = document.formProductSearch.SqFt;

    // New price button array
    fldPrice = document.formProductSearch.Price;

    //Converted from buttons to links
    storyButtonArray = document.formProductSearch.Stories;
    bedroomButtonArray = document.formProductSearch.Bedrooms;
    bathroomButtonArray = document.formProductSearch.Bathrooms;
    garageButtonArray = document.formProductSearch.Garage;

    if (curSiteName != "divosta") {
        fldActiveAdult = document.formProductSearch.ActiveAdult;
    }
    fldAvailableNow = document.formProductSearch.homesAvailableNow;
    SearchControlUtils.addControlClickEventListener(productCONFIG.ControlIdName['homeType'], fldHomeType);
    SearchControlUtils.addControlClickEventListener(productCONFIG.ControlIdName['sqft'], fldSqFt);
    SearchControlUtils.addControlClickEventListener(productCONFIG.ControlIdName['price'], fldPrice);
    SearchControlUtils.addControlClickEventListener(productCONFIG.ControlIdName['activeAdult'], fldActiveAdult);
    SearchControlUtils.addControlClickEventListener(productCONFIG.ControlIdName['availableNow'], fldAvailableNow);

    //Click events converted from events on image buttons
    SearchControlUtils.addControlClickEventListener(productCONFIG.ControlIdName['stories'], storyButtonArray);
    SearchControlUtils.addControlClickEventListener(productCONFIG.ControlIdName['bedrooms'], bedroomButtonArray);
    SearchControlUtils.addControlClickEventListener(productCONFIG.ControlIdName['bathrooms'], bathroomButtonArray);
    SearchControlUtils.addControlClickEventListener(productCONFIG.ControlIdName['garage'], garageButtonArray);

    fldCommunityType = document.formProductSearch.CommunityType;
    SearchControlUtils.addControlClickEventListener(productCONFIG.ControlIdName['communityType'], fldCommunityType);

    if (curSiteName == "delwebb") {
        fldSubBrand = document.formProductSearch.SubBrand;
        SearchControlUtils.addControlClickEventListener(productCONFIG.ControlIdName['subBrand'], fldSubBrand);
    }

    if (curSiteName == "divosta") {
        fldPOI = document.formProductSearch.selectPOI;
        YUE.addListener(document.getElementById('poi'), 'change', function() { HandleChange() });
        function HandleChange() {
            var arr = [];
            var poiValue = document.getElementById("poi").value;
            if (poiValue != -1) {
                if (parseInt(poiValue)) {
                    arr.push(document.getElementById("poi").value);
                }
            }
            MapSearch.controlGroupSearch("poi", arr, -1);
        }
    }

});

// SET UP CLEAR/RESET BUTTONS

//YUE.addListener(window,'load',function(){

YUE.onDOMReady(function() {

    var theObject = YUD.getElementsByClassName('body', 'div');

    YUD.batch(theObject, function(el) {
        var resetLink = YUD.getElementsByClassName('reset', '', el)[0];
        var inputs = el.getElementsByTagName('input');
        var buttons = el.getElementsByTagName('button');
        var isBtn = false;
        if (buttons.length > 0) isBtn = true;

        YUE.on(el, 'click', function(e) {
            var target = YUE.getTarget(e);
            if (!resetLink || (!inputs && !buttons)) return;
            var counter = 0;
            if (isBtn) { for (var j = 0; j < buttons.length; j++) { if (YUD.getAncestorByClassName(buttons[j], 'yui-checkbox-button-checked')) counter += 1; } }
            if (inputs && inputs.length) {
                counter += SearchControlUtils.getRadioCheckboxValues(inputs).length;
            }
            if (counter < 1) { resetLink.style.display = 'none'; }
            else { resetLink.style.display = 'block'; }
        })
    });

    // for radius search
    var searchContainer = YUD.getElementsByClassName('searchForHome')[0];
    var searchReset = YUD.getElementsByClassName('reset', '', searchContainer)[0];
    YUE.addListener(document.getElementById('searchSubmit'), 'click', function() { if (document.getElementById('productsearch').value != '') searchReset.style.display = 'inline'; else searchReset.style.display = 'none'; });
    // default value for productsearch - only if no cookie from previous search exists. Blank it out onFocus.
    if (!getCookie('searchText')) SearchControlUtils.resetProductSearch();
    YUE.addListener(document.getElementById('productsearch'), 'focus', function() { if (document.getElementById('productsearch').value == productSearchValue) document.getElementById('productsearch').value = ''; });

    YAHOO.sessionTimeOut.init();
    // set timeout after 20 minutes
    sessionTimer = window.setTimeout(restartSessionTimeOut, sessionTimeOutLimit);
    YUE.addListener(document.body, 'click', function() {
        if (sessionTimer) window.clearTimeout(sessionTimer);
        sessionTimer = window.setTimeout(restartSessionTimeOut, sessionTimeOutLimit);
    });

});

// ----------------------------------------------------------------------------------------------

// GLOBAL VARS FOR THE MAP

var map;
var geocoder;
var curBrand = 'pulte';
var clusterer;
var isOpenInfoWindow = false;
var curZoom;
var isSearchEnabled = true;
var mapBounds = { southWest: null, northEast: null };
var breadcrumbList; // keep track all breadcrumb listing
var loadBreadcrumb = false;
var currentPage, totalPages, totalRows;
var dynamicCluster = false;
var clickedControlInfo = { buttonName: 'none', clickedState: 0 }; // keep track of clickedControl id, state, and group name clickedState 0 = not check, 1 = checked
var currentTaxonomy;
var breadcrumbInfo = { id: '', idType: '' };
var loadPageResult = false;
var pageResultInfo = { pageNumber: '', pageType: '' };
var radiusOverlay; // overlay for the circle
var polyBounds; // bounds for polygon
var zipSearched;
var zipCenterLat;
var zipCenterLng;

// searchControlUtils functions
var SearchControlUtils = {

    getButtonValues: function(buttonGroupArray) {
        var arr = [];
        for (var i = 0; i < buttonGroupArray.length; i++) { if (buttonGroupArray[i].get('checked')) arr.push(buttonGroupArray[i].get('value')) }
        return arr;
    },

    getRadioCheckboxValues: function(controlGroupArray) {
        var arr = [];
        if (!controlGroupArray) return;
        if (controlGroupArray.length) {
            for (var i = 0; i < controlGroupArray.length; i++) {
                if (controlGroupArray[i].checked) {
                    if (controlGroupArray[i].value != '') {  // ignore "all" box
                        if (controlGroupArray[i].value.indexOf(',') > -1) {
                            var addValues = controlGroupArray[i].value.split(',');
                            for (var k = 0; k < addValues.length; k++) arr.push(addValues[k]);
                        }
                        else { arr.push(controlGroupArray[i].value) }
                    }
                }
            }
        }
        else { if (controlGroupArray.checked) arr.push(controlGroupArray.value) }

        return arr;
    },

    // onButtonClick function
    onButtonClick: function(buttonName, buttonGroupArray, buttonIndex) {
        var buttonArray = SearchControlUtils.getButtonValues(buttonGroupArray);
        var isChecked = 0;
        if (buttonGroupArray[buttonIndex].get('checked')) isChecked = 1;

        // keep track of the current clicked control
        clickedControlInfo.buttonName = buttonName;
        clickedControlInfo.clickedState = isChecked;
        MapSearch.controlGroupSearch(buttonName, buttonArray, isChecked)
    },

    // onRadioCheckboxClick
    onRadioCheckboxClick: function(controlName, controlGroupArray, controlIndex) {
        var arr = SearchControlUtils.getRadioCheckboxValues(controlGroupArray);
        var isChecked = 0;
        if (controlIndex != -1) {
            if (controlGroupArray[controlIndex].value == '') { // "all" button was clicked, make all others in the group unchecked
                this.resetCheckboxRadioControls(controlName, true);
            }
            else {
                if (controlGroupArray[controlIndex].checked) isChecked = 1;
                if (controlGroupArray[0].value == '') { // this group has "all" box and we need to make it unchecked
                    controlGroupArray[0].checked = false;
                    var controlImg = YUD.getPreviousSibling(controlGroupArray[0]);
                    controlImg.src = returnCheckboxImgFalse();
                }
                MapSearch.controlGroupSearch(controlName, arr, isChecked);
            }
        }
        else {
            if (controlGroupArray.checked) isChecked = 1;
            MapSearch.controlGroupSearch(controlName, arr, isChecked);
        }
        //alert(controlIndex);alert(arr);
        // keep track of the current clicked control
        clickedControlInfo.buttonName = controlName;
        clickedControlInfo.clickedState = isChecked;
    },

    // addClickEvent for buttons
    addClickEventListener: function(buttonName, buttonGroupArray) {
        for (var i = 0; i < buttonGroupArray.length; i++) {
            SearchControlUtils.addClickEventFunction(buttonName, buttonGroupArray, i);
        }
    },

    // addClickEventFunction
    addClickEventFunction: function(buttonName, buttonGroupArray, buttonIndex) {
        buttonGroupArray[buttonIndex].addListener('click', function(e) { SearchControlUtils.onButtonClick(buttonName, buttonGroupArray, buttonIndex); })
    },

    // addRadioClickEventListener
    addControlClickEventListener: function(controlName, controlGroupArray) {
        if (controlGroupArray.length) {
            for (var i = 0; i < controlGroupArray.length; i++) { SearchControlUtils.addControlClickEventFunction(controlName, controlGroupArray, i) }
        }
        else {
            SearchControlUtils.addControlClickEventFunction(controlName, controlGroupArray, -1);
        }
    },

    // addRadioClickEventFunction listener
    addControlClickEventFunction: function(controlName, controlGroupArray, controlIndex) {
        //alert(controlName);
        //alert(controlIndex);
        if (controlIndex != -1) {
            YUE.addListener(controlGroupArray[controlIndex], 'click', function(e) { SearchControlUtils.onRadioCheckboxClick(controlName, controlGroupArray, controlIndex); });
        }
        else {
            YUE.addListener(controlGroupArray, 'click', function(e) { SearchControlUtils.onRadioCheckboxClick(controlName, controlGroupArray, controlIndex); });
        }
    },

    // updateButtonControls
    updateButtonControls: function(buttonName, buttonGroupArray, updatedValueList, selectedValueList) {
        if (!buttonGroupArray) return;

        for (var i = 0; i < buttonGroupArray.length; i++) {
            // selected the buttons if not already selected from the section
            if (selectedValueList && selectedValueList.length) {
                for (var k = 0; k < selectedValueList.length; k++) {
                    if (buttonGroupArray[i].get('value') == selectedValueList[k]) buttonGroupArray[i].set('checked', true);
                }
            }

            // ignore any control that is checked
            if (!buttonGroupArray[i].get('checked')) {
                var isEnabled = false;
                for (var k = 0; k < updatedValueList.length; k++) {
                    if (buttonGroupArray[i].get('value') == updatedValueList[k]) {
                        isEnabled = true;
                        break;
                    }
                }
                if (isEnabled) buttonGroupArray[i].set('disabled', false);
                else buttonGroupArray[i].set('disabled', true);
            }
        }
    },

    // Alok: Adds click event to [x] without overwriting the reference
    addRemoteClick: function(thisControl, remoteControl) {
        YUE.addListener(thisControl, 'click', function(e) { remoteControl.click(); });
    },

    //Alok: Gets labels, and replaces whatever is inside the () with the correct count and updates the You've Selected area.
    updateCountsSelections: function(countArray, controlGroupArray, selectionFeature) {

        if (!controlGroupArray) return;

        if (!controlGroupArray.length) {
            var controlType = controlGroupArray;
            controlGroupArray = [];
            controlGroupArray.push(controlType);
        }

        for (var i = 0, j = 0; i < controlGroupArray.length; i++) {
            var controlLabel = YUD.getNextSibling(controlGroupArray[i]);
            var controlName = controlGroupArray[i].name;

            if (controlGroupArray[i].value == "") {
                // Matches first item in array with a span tag
                if (controlLabel.innerHTML.match(/span/i)) {
                }
                else {
                    controlLabel.innerHTML = "<span>" + controlLabel.innerHTML + "</span>";
                }
            }
            else {

                /* Disabling count display
                // Matches strings that have "()" with any amount of characters inside
                if(controlLabel.innerHTML.match(/\(.*\)/)) {
                controlLabel.innerHTML = controlLabel.innerHTML.replace(/\(.*\)/, "(" + countArray[j] + ")");
                }
                else {
                controlLabel.innerHTML = "<span>" + controlLabel.innerHTML + "</span>" + " (" + countArray[j] + ")";
                }
                */

                // Added after disabling counts
                if (!controlLabel.innerHTML.match(/span/i)) {
                    controlLabel.innerHTML = "<span>" + controlLabel.innerHTML + "</span>";
                }

                if (controlGroupArray[i].checked) {
                    var s_a = document.createElement('a');
                    var s_li = document.createElement('li');

                    s_a.appendChild(document.createTextNode(" [x]"));

                    // If its a radio button, pick "All Items" control, instead of the current control.
                    if (controlGroupArray[i].type == "radio") {
                        this.addRemoteClick(s_a, controlGroupArray[0]);
                    }
                    else {
                        this.addRemoteClick(s_a, controlGroupArray[i]);
                    }

                    s_li.innerHTML = controlLabel.getElementsByTagName('span')[0].innerHTML;
                    s_li.appendChild(s_a);
                    selectionFeature.appendChild(s_li);

                    selectedCount++;
                }

                j++;
            }
        }
    },

    // function switches images to either enabled or disabled state based on whether the class is set to enabled or disabled
    updateCheckboxRadioControls: function(buttonName, controlGroupArray, updatedValueList, selectedValueList) {
        if (!controlGroupArray) return;

        var isCheckbox = true;
        if (!controlGroupArray.length) {
            var controlType = controlGroupArray;
            controlGroupArray = [];
            controlGroupArray.push(controlType);
        }
        var checkedCount = 0;
        if (controlGroupArray[0].getAttribute('type') == 'radio') isCheckbox = false;

        for (var i = 0; i < controlGroupArray.length; i++) {
            if (controlGroupArray[i].value != '') { //ignore 'all' boxes here
                var isEnabled = false;
                var controlImg = YUD.getPreviousSibling(controlGroupArray[i]);
                var controlLabel = YUD.getNextSibling(controlGroupArray[i]);

                // set the selected control if not already selected
                if (selectedValueList && selectedValueList.length) {
                    for (var k = 0; k < selectedValueList.length; k++) {
                        if (controlGroupArray[i].value == selectedValueList[k]) {

                            // if it is not already selected
                            if (!controlGroupArray[i].checked) {
                                controlGroupArray[i].checked = true;
                                if (isCheckbox) controlImg.src = returnCheckboxImgTrue();
                                else controlImg.src = returnRadioImgTrue();
                            }

                            if (!isCheckbox) {
                                controlGroupArray[i].disabled = true;
                                controlLabel.className = "rSelected";
                            }

                            break;
                        }
                    }
                }
                // ignore any control that is checked
                if (!controlGroupArray[i].checked) {
                    // updated list for enabling and disabling
                    if (updatedValueList) {
                        for (var k = 0; k < updatedValueList.length; k++) {
                            if (updatedValueList[k] != "") {
                                if (controlGroupArray[i].value == updatedValueList[k] || (buttonName == productCONFIG.ControlIdName['homeType'] && controlGroupArray[i].value.indexOf(updatedValueList[k]) > -1)) {
                                    isEnabled = true;
                                    break;
                                }
                            }
                        }
                    }

                    if (isEnabled) {
                        controlGroupArray[i].disabled = false;
                        controlLabel.className = "";
                        if (isCheckbox) controlImg.src = returnCheckboxImgFalse();
                        else controlImg.src = returnRadioImgFalse();
                    } else {
                        controlGroupArray[i].disabled = true;
                        controlLabel.className = "cDisabled";
                        //controlLabel.getElementsByTagName('span')[0].className = "disabled";
                        if (isCheckbox) {
                            if ((YUD.hasClass('pulte', 'template-F')) || (YUD.hasClass('delWebb', 'template-F')) || (YUD.hasClass('diVosta', 'template-F')) || (YUD.hasClass('centex', 'template-F'))) {
                                controlImg.src = '/images/global/btn-checkboxUnChecked.gif';
                            }
                            else {
                                controlImg.src = '/images/' + getCurrSite() + '/button-checkboxDisabled.gif';
                            }
                        }
                        else {
                            if ((YUD.hasClass('pulte', 'template-F')) || (YUD.hasClass('delWebb', 'template-F')) || (YUD.hasClass('diVosta', 'template-F')) || (YUD.hasClass('centex', 'template-F'))) {
                                controlImg.src = '/images/global/btn-checkboxUnChecked.gif';
                            }
                            else {
                                controlImg.src = '/images/' + getCurrSite() + '/button-radioDisabled.gif';
                            }
                        }
                    }
                }
                else { // checked, add to the count
                    checkedCount++;
                }
            }
            if (controlGroupArray[0].value == '') {
                if (checkedCount == 0) {// none of the boxes are checked, so check "all" 
                    controlGroupArray[0].checked = true;
                    var controlImg = YUD.getPreviousSibling(controlGroupArray[0]);
                    controlImg.src = returnCheckboxImgTrue();
                }
                else {
                    controlGroupArray[0].checked = false;
                    var controlImg = YUD.getPreviousSibling(controlGroupArray[0]);
                    controlImg.src = returnCheckboxImgFalse();
                }
            }
        }
    },

    // setButtonControls
    setButtonControls: function(buttonName, buttonGroupArray, updatedValueList) {
        if (!buttonGroupArray) return;

        for (var i = 0; i < buttonGroupArray.length; i++) {
            var isSet = false;
            for (var k = 0; k < updatedValueList.length; k++) {

                if (buttonGroupArray[i].get('value') == updatedValueList[k]) {
                    isSet = true;
                    break;
                }
            }
            if (isSet) buttonGroupArray[i].set('checked', true);
        }
    },

    //set checkbox or radio control base on parameters
    setCheckboxRadioControls: function(buttonName, controlGroupArray, updatedValueList) {
        if (!controlGroupArray) return;

        var isCheckbox = true;
        if (!controlGroupArray.length) {
            var controlType = controlGroupArray;
            controlGroupArray = [];
            controlGroupArray.push(controlType);
        }

        if (controlGroupArray[0].getAttribute('type') == 'radio') isCheckbox = false;

        for (var i = 0; i < controlGroupArray.length; i++) {
            var isSet = false;
            var controlImg = YUD.getPreviousSibling(controlGroupArray[i]);
            for (var k = 0; k < updatedValueList.length; k++) {
                if (controlGroupArray[i].value == updatedValueList[k] || (buttonName == productCONFIG.ControlIdName['homeType'] && controlGroupArray[i].value.indexOf(updatedValueList[k]) > -1)) {
                    isSet = true;
                    break;
                }
            }
            if (isSet) {
                controlGroupArray[i].checked = true;
                if (isCheckbox) controlImg.src = returnCheckboxImgTrue();
                else controlImg.src = returnRadioImgTrue();
            }
        }
    },

    // begin: resetSearchParameters ()
    resetSearchParameters: function() {
        //alert("resetSearchParameters");
        isResetAll = true;
        userModifiedSlider = false;
        SearchControlUtils.resetCheckboxRadioControls(productCONFIG.ControlIdName['homeType'], false);
        SearchControlUtils.resetCheckboxRadioControls(productCONFIG.ControlIdName['stories'], false);
        SearchControlUtils.resetCheckboxRadioControls(productCONFIG.ControlIdName['bedrooms'], false);
        SearchControlUtils.resetCheckboxRadioControls(productCONFIG.ControlIdName['bathrooms'], false);
        SearchControlUtils.resetCheckboxRadioControls(productCONFIG.ControlIdName['sqft'], false);
        SearchControlUtils.resetCheckboxRadioControls(productCONFIG.ControlIdName['price'], false);
        if (getCurrSite() != 'DiVosta') {
            SearchControlUtils.resetCheckboxRadioControls(productCONFIG.ControlIdName['activeAdult'], false);
        }
        SearchControlUtils.resetCheckboxRadioControls(productCONFIG.ControlIdName['garage'], false);
        SearchControlUtils.resetCheckboxRadioControls(productCONFIG.ControlIdName['poi'], false);
        //SearchControlUtils.resetCheckboxRadioControls(productCONFIG.ControlIdName['availableNow'], false);    (don't reset it - it's different tab starting from 1.0.6)
        SearchControlUtils.resetCheckboxRadioControls(productCONFIG.ControlIdName['communityType'], false);
        if (getCurrSite() == 'DelWebb') {
            SearchControlUtils.resetCheckboxRadioControls(productCONFIG.ControlIdName['subBrand'], false);
        }
        clickedControlInfo.buttonName = 'none';
        clickedControlInfo.clickedState = 0;
        // YAHOO.productSlider.resetSlider();
        var clearObjContainer = YUD.getElementsByClassName('body', 'div');
        for (var i = 0; i < clearObjContainer.length; i++) {
            var clearLink = YUD.getElementsByClassName('reset', '', clearObjContainer[i])[0];
            if (clearLink) clearLink.style.display = 'none';
        }
        SearchControlUtils.resetProductSearch();

        MapSearch.clearRadiusOverlay();
        zipSearched = "";
        setCookie('zipSearch', "", null, "/");
        if (document.getElementById("zipSearch")) {
            document.getElementById("zipSearch").value = "Zip";
        }
        //display loading message
        MapSearch.toggleLoadingMessage(true);
        brandIdList = [];
        brandIdList[0] = productCONFIG.brandIds[getCurrSite().toLowerCase()];
        Pulte08.AjaxWebServices.MapService.ResetAllSearchParametersSetBrand(brandIdList[0], MapSearch.newBounds);
    },

    // resetButtonControls
    resetButtonControls: function(controlName, isSearchable) {
        var controlGroupArray;
        //alert("resetButtonControls");
        switch (controlName) {
            case productCONFIG.ControlIdName['stories']: controlGroupArray = storyButtonArray; break;
            case productCONFIG.ControlIdName['bedrooms']: controlGroupArray = bedroomButtonArray; break;
            case productCONFIG.ControlIdName['bathrooms']: controlGroupArray = bathroomButtonArray; break;
            case productCONFIG.ControlIdName['garage']: controlGroupArray = garageButtonArray; break;
        }
        if (!controlGroupArray) return;
        for (var i = 0; i < controlGroupArray.length; i++) {
            if (controlGroupArray[i].get('disabled')) controlGroupArray[i].set('disabled', false); // set disabled to enabled
            if (controlGroupArray[i].get('checked')) controlGroupArray[i].set('checked', false); // set checked to unchecked
        }

        if (isSearchable) {
            clickedControlInfo.buttonName = 'none';
            clickedControlInfo.clickedState = 0;
            MapSearch.controlGroupSearch(controlName, SearchControlUtils.getButtonValues(controlGroupArray), 0);
        }

    },

    // resetBedBathControls
    resetBedBathControls: function() {
        SearchControlUtils.resetCheckboxRadioControls(productCONFIG.ControlIdName['bedrooms'], false);
        SearchControlUtils.resetCheckboxRadioControls(productCONFIG.ControlIdName['bathrooms'], false);
        MapSearch.controlGroupSearch(productCONFIG.ControlIdName['bandb'], [], 0);
    },

    // resetCheckboxRadioControls
    resetCheckboxRadioControls: function(controlName, isSearchable) {
        var controlGroupArray;
        switch (controlName) {
            case productCONFIG.ControlIdName['homeType']: controlGroupArray = fldHomeType; break;
            case productCONFIG.ControlIdName['communityType']: controlGroupArray = fldCommunityType; break;
            case productCONFIG.ControlIdName['subBrand']: controlGroupArray = fldSubBrand; break;
            case productCONFIG.ControlIdName['sqft']: controlGroupArray = fldSqFt; break;
            case productCONFIG.ControlIdName['price']: controlGroupArray = fldPrice; break;
            case productCONFIG.ControlIdName['activeAdult']: controlGroupArray = fldActiveAdult; break;
            case productCONFIG.ControlIdName['availableNow']: controlGroupArray = fldAvailableNow; break;
            case productCONFIG.ControlIdName['bedrooms']: controlGroupArray = bedroomButtonArray; break;
            case productCONFIG.ControlIdName['bathrooms']: controlGroupArray = bathroomButtonArray; break;
            case productCONFIG.ControlIdName['garage']: controlGroupArray = garageButtonArray; break;
            case productCONFIG.ControlIdName['stories']: controlGroupArray = storyButtonArray; break;
        }
        //alert(controlGroupArray.length);
        if (!controlGroupArray) return;
        if (!controlGroupArray.length) {
            var control = controlGroupArray;
            controlGroupArray = [];
            controlGroupArray.push(control);
        }

        var isCheckbox = true;
        if (controlGroupArray[0].getAttribute('type') == 'radio') isCheckbox = false;
        for (var i = 0; i < controlGroupArray.length; i++) {
            var controlImg = YUD.getPreviousSibling(controlGroupArray[i]);
            if (controlGroupArray[i].value != '') {
                if (controlGroupArray[i].disabled) controlGroupArray[i].disabled = false;
                if (controlGroupArray[i].checked) controlGroupArray[i].checked = false;
                if (isCheckbox) controlImg.src = returnCheckboxImgFalse();
                else controlImg.src = returnRadioImgFalse();
            }
            else { // this is "all" box, make it checked
                controlGroupArray[i].checked = true;
                if (isCheckbox) controlImg.src = returnCheckboxImgTrue();
            }
        }

        if (isSearchable) {
            clickedControlInfo.buttonName = 'none';
            clickedControlInfo.clickedState = 0;
            MapSearch.controlGroupSearch(controlName, [], 0);
        }
    },

    //updateSearchLink
    //removed Sept 4 08 due to removal of otherHomes section from Search pages
    //updateSearchLink: function(numHomes, numCommunities){
    //var searchLink = document.getElementById('otherHomes');
    //var searchLinkTitle = document.getElementById('otherHomesTitle');
    //if(!searchLink) return;

    //if(numHomes > 0 ){
    //searchLinkTitle.style.display = '';
    //searchLink.innerHTML = 'There are <a href="javascript:MapSearch.searchOtherBrands();">' + numHomes + ' homes in ' + numCommunities + ' neighborhoods from other Pulte Homes, Inc. brands</a> that match your search criteria.';
    //searchLink.style.display = '';
    //}
    //else {
    //searchLinkTitle.style.display = 'none';
    //searchLink.style.display = 'none';
    //}
    //},

    //updateHomeCount
    updateHomeCount: function(numHomes, numCommunities) {
        var homeCountText = document.getElementById('homeCount');
        if (!homeCountText) return;
        var commTitle = 'neighborhoods';
        if (getCurrSite().toLowerCase() == 'delwebb' || getCurrSite().toLowerCase() == 'divosta') commTitle = 'communities';
        if (numHomes > 0) homeCountText.innerHML = '<strong>' + numHomes + ' homes</strong>match your search criteria in <strong>' + numCommunities + ' ' + commTitle + '</strong>';
    },

    // submitEnter
    submitEnter: function(myfield, e) {
        var keycode;
        if (window.event) keycode = window.event.keyCode;
        else if (e) keycode = e.which;
        else return true;

        // if return key is pressed
        if (keycode == 13) {
            var searchVal = document.getElementById('productsearch').value;
            if (searchVal != '') {
                var searchContainer = YUD.getElementsByClassName('searchForHome')[0];
                var searchReset = YUD.getElementsByClassName('reset', '', searchContainer)[0];
                searchReset.style.display = 'inline';
                MapSearch.showAddress(searchVal);
            }
            return false;
        } else return true;
    },

    // set default to product search
    resetProductSearch: function() {
        if (document.getElementById('productsearch').value == '') { document.getElementById('productsearch').value = productSearchValue; }
    },

    // displayResetLink queryString set
    resetAllClearLinks: function() {
        var theObject = YUD.getElementsByClassName('body', 'div');
        YUD.batch(theObject, function(el) {
            var resetLink = YUD.getElementsByClassName('reset', '', el)[0];
            var inputs = el.getElementsByTagName('input');
            var buttons = el.getElementsByTagName('button');
            var isBtn = false;
            if (buttons.length > 0) isBtn = true;
            if (resetLink && (inputs || buttons)) {
                var counter = 0;
                if (isBtn) { for (var j = 0; j < buttons.length; j++) { if (YUD.getAncestorByClassName(buttons[j], 'yui-checkbox-button-checked')) counter += 1; } }
                if (inputs && inputs.length) {
                    counter += SearchControlUtils.getRadioCheckboxValues(inputs).length;
                }
                if (counter < 1) { resetLink.style.display = 'none'; }
                else { resetLink.style.display = 'block'; }
            }
        });
    }
};

// ----------------------------------------------------------------------------------------------

// PRODUCT SEARCH MAJOR FUNCTION

// group all of the mapsearch function together
var MapSearch = {
    searchQuery: '',
    // initialize
    initialize: function() {
        if (document.getElementById('geoDescription') != null) {
            if (document.getElementById('geoDescription').innerHTML.length < 10) {
                document.getElementById('geoDescription').style.visibility = 'hidden';
            }
        }
        brandIdList[0] = productCONFIG.brandIds[getCurrSite().toLowerCase()];
        // calls the webservice for updated search data, registers true initialize as callback handler
        Pulte08.AjaxWebServices.MapService.GetSearchURL(MapSearch.initializeCallbackHandler);
    },

    // initialize callback handler
    initializeCallbackHandler: function(result) {

        //loadPriceSlider();
        //addPriceSliderEvent();
        // timeout is need to set IE problem
        window.setTimeout(function() {
            // create the map object and add custom control
            map = new GMap2(document.getElementById(productCONFIG['mapId']));
            map.addControl(new GScaleControl());
            map.addControl(new MapSliderControl());

            // set the min zoom to be at the country level and max zoom at 18
            var mt = map.getMapTypes();
            for (var i = 0; i < mt.length; i++) {
                mt[i].getMinimumResolution = function() { return 3 }
            }
            for (var i = 0; i < mt.length; i++) {
                mt[i].getMaximumResolution = function() { return 18 }
            }

            geocoder = new GClientGeocoder();

            var qs = location.search.substring(1);
            var qsObj;
            //alert(result); //?
            if (result != null) {
                // get querystring portion of result (split on '?', take right half)
                var temp = (result.indexOf('?' > -1)) ? result.split('?') : '';

                if (temp.length > 0) MapSearch.searchQuery = temp[1];
            }

            if (qs.length == 0 && MapSearch.searchQuery != "") {
                isSessionQuery = true;
                qs = MapSearch.searchQuery;
                // if we're using searchQuery from server to initialize, load breadcrumb info from cookie if possible since this is unavailable on the server-side query string
                if (getCookie('bcId')) {
                    loadBreadcrumb = true;
                    breadcrumbInfo.id = getCookie('bcId');
                    breadcrumbInfo.idType = getCookie('bcType');
                }
                // load the specific page if exists
                if (getCookie('searchPageNumber')) {
                    loadPageResult = true;
                    pageResultInfo.pageNumber = getCookie('searchPageNumber');
                    pageResultInfo.pageType = getCookie('searchPageType');
                    pageResultInfo.curPageNumber = getCookie('searchCurrentPage');
                    deleteCookie('searchPageNumber');
                    deleteCookie('searchPageType');
                    deleteCookie('searchCurrentPage');
                }
                // load the search text if exists
                if (getCookie('searchText')) {
                    document.getElementById('productsearch').value = unescape(getCookie('searchText'));
                    document.getElementById('radius').value = getCookie('searchMiles');
                    var searchContainer = YUD.getElementsByClassName('searchForHome')[0];
                    var searchReset = YUD.getElementsByClassName('reset', '', searchContainer)[0];
                    searchReset.style.display = 'inline';
                }
                if (getCookie('zipSearch')) {
                    zipSearched = getCookie('zipSearch');
                    if (zipSearched != null) {
                        document.getElementById("zipSearch").value = zipSearched;
                        MapSearch.showAddress(zipSearched, zipRadius);
                    }
                }
            }
            //alert('qs.length=');alert(qs.length);//?
            //alert(qs);
            if (qs.length > 0 || (document.getElementById('bcIdHiddenInput'))) {
                //alert(qs);
                isSearchEnabled = false;
                qsObj = new Querystring(qs);
                // known coordinates
                if (qsObj.get('lat') && qsObj.get('lng')) {
                    //MapSearch.showPoint(qsObj.get('lat'), qsObj.get('lng'));
                }
                // zip
                if (qsObj.get('zip')) {
                    zipSearched = qsObj.get('zip');
                    //setCookie('zipSearch', zipSearched, null, "/");
                    document.getElementById("zipSearch").value = zipSearched;
                    MapSearch.showAddress(zipSearched, zipRadius);
                }
                //alert(MapSearch.zipCenter);
                var searchParams = MapSearch.populateSearchParams(qsObj);
                // make sure we have valid search params
                //alert('searchParams.cnt='); alert(searchParams.cnt);
                if (searchParams.cnt > 0) {
                    // load breadcrumb if state info is available
                    if (searchParams.State != null) {
                        loadBreadcrumb = true;
                        breadcrumbInfo.id = searchParams.State;
                        breadcrumbInfo.idType = 'state';
                        setCookie('bcId', breadcrumbInfo.id, null, "/");
                        setCookie('bcType', breadcrumbInfo.idType, null, "/");
                    }
                    // check querystring for breadcrumb data -- maybe on url, if so override cookie
                    if (qsObj.get('bcId')) {
                        loadBreadcrumb = true;
                        breadcrumbInfo.id = qsObj.get("bcId");
                        breadcrumbInfo.idType = qsObj.get("bcType");
                        // navigate to requested state/region/metro area
                        if (breadcrumbInfo.idType == "country") { MapSearch.zoomToCountry(); }
                        else { MapSearch.zoomToMarkerLocation(breadcrumbInfo.id, breadcrumbInfo.idType); }
                    }
                    //alert("here1");
                    if (document.getElementById('bcIdHiddenInput')) {
                        if (document.getElementById('bcIdHiddenInput').value > 0) {
                            loadBreadcrumb = true;
                            breadcrumbInfo.id = document.getElementById('bcIdHiddenInput').value;
                            breadcrumbInfo.idType = document.getElementById('bcTypeHiddenInput').value;
                            // navigate to requested state/region/metro area
                            if (breadcrumbInfo.idType == "country") { MapSearch.zoomToCountry(); }
                            else { MapSearch.zoomToMarkerLocation(breadcrumbInfo.id, breadcrumbInfo.idType); }
                        }
                    }
                    //alert("here2");
                    if (qsObj.get('nelat') && qsObj.get('nelng') && qsObj.get('swlat') && qsObj.get('swlng')) {
                        var qsnelat = parseFloat(qsObj.get('nelat'));
                        var qsnelng = parseFloat(qsObj.get('nelng'));
                        var qsswlat = parseFloat(qsObj.get('swlat'));
                        var qsswlng = parseFloat(qsObj.get('swlng'));
                        var qsCenterLat = (qsnelat + qsswlat) / 2.0;
                        var qsCenterLng = (qsnelng + qsswlng) / 2.0;

                        var markerBounds = new GLatLngBounds(new GLatLng(qsswlat, qsswlng), new GLatLng(qsnelat, qsnelng)); // sw, ne
                        var qsZoomLevel = map.getBoundsZoomLevel(markerBounds);
                        map.setCenter(new GLatLng(qsCenterLat, qsCenterLng), qsZoomLevel);
                    }
                    else {
                        map.setCenter(new GLatLng(defaultMapLat, defaultMapLng), productCONFIG.defaultMapZoom());
                    }
                    // if parameter passed from breadcrumb, it will be done in FilterCommunitiesBy<...> webservice
                    if ((!qsObj.get('bcId') && !(document.getElementById('bcIdHiddenInput')) && (!(qsObj.get('zip'))))) {//alert("if(!qsObj.get('bcId')");
                        Pulte08.AjaxWebServices.MapService.FilterByQueryString(searchParams, MapSearch.newBounds);
                    }
                } else {
                    isSearchEnabled = true;
                    map.setCenter(new GLatLng(defaultMapLat, defaultMapLng), productCONFIG.defaultMapZoom());
                }
            }
            else {
                // if no param pass from query string, set the map on country level
                map.setCenter(new GLatLng(defaultMapLat, defaultMapLng), productCONFIG.defaultMapZoom());
            }
            // add event listener to close custom info window if click on the map not a marker
            GEvent.addListener(map, 'click', function(marker, point) {
                if (!marker) {
                    if (curClickedMarker) curClickedMarker.closeDetailWin();
                }
            });

            // change the result set if the map has moved or zoom
            GEvent.addListener(map, 'moveend', function() {
                var bounds = map.getBounds();
                var southWest = bounds.getSouthWest();
                var northEast = bounds.getNorthEast();
                var all = bounds.toSpan();
                if (isSearchEnabled) {
                    if (mapBounds.southWest == null || mapBounds.northEast == null || southWest.lat() != mapBounds.southWest.lat() || southWest.lng() != mapBounds.southWest.lng() || northEast.lat() != mapBounds.northEast.lat() || northEast.lng() != mapBounds.northEast.lng()) {
                        //alert(southWest);
                        mapBounds.southWest = southWest;
                        mapBounds.northEast = northEast;
                        //display loading message
                        MapSearch.toggleLoadingMessage(true);
                        //alert(zipCenterLat); alert(zipCenterLng);
                        if (zipCenterLat == null || zipCenterLng == null) {
                            Pulte08.AjaxWebServices.MapService.FilterByGeo(brandIdList, northEast.lat(), northEast.lng(), southWest.lat(), southWest.lng(), MapSearch.newBounds);
                        } else {
                            setCookie('zipSearch', zipSearched, null, "/");
                            Pulte08.AjaxWebServices.MapService.FilterByGeoCenter(brandIdList, northEast.lat(), northEast.lng(), southWest.lat(), southWest.lng(), zipCenterLat, zipCenterLng, MapSearch.newBounds);
                        }
                        //
                    }
                }
            })
        }, 0);

    },

    // show address
    showAddress: function(address, radius) {
        if (!geocoder) return;
        if (radius == 0) { radius = zipRadius; }
        geocoder.getLocations(address, function(result) {
            var accuracy;
            var zoomlevel = 3;
            if (result.Status.code == G_GEO_SUCCESS) {
                if (result.Placemark.length > 1) {
                    document.getElementById('bounds').innerHTML = '<h4 class="noResults">More than one place found, please specify a more accurate address.</h4>';
                }
                else {
                    var point = result.Placemark[0].Point.coordinates;
                    accuracy = result.Placemark[0].AddressDetails.Accuracy;
                    breadcrumbInfo.id = result.Placemark[0].AddressDetails.Country.AdministrativeArea.AdministrativeAreaName;
                    breadcrumbInfo.idType = 'state';
                    loadBreadcrumb = true;
                    setCookie('bcId', breadcrumbInfo.id, null, "/");
                    setCookie('bcType', breadcrumbInfo.idType, null, "/");
                    setCookie('searchText', escape(address), null, "/");
                    setCookie('searchMiles', radius, null, "/");
                    if (accuracy > -1 && accuracy < productCONFIG.GeoAccuracy.length) zoomlevel = productCONFIG.GeoAccuracy[accuracy];
                    isSearchEnabled = false; // move the map
                    map.setCenter(new GLatLng(point[1], point[0]));
                    MapSearch.draw(new GLatLng(point[1], point[0]), radius, 36);
                    isSearchEnabled = true;
                    zipCenterLat = point[1];
                    zipCenterLng = point[0];
                    //alert('zipCenterLat='); alert(zipCenterLat);
                    MapSearch.fit();
                }
            }
            else {
                if (productCONFIG.reasons[result.Status.code]) document.getElementById('bounds').innerHTML = '<h4 class="noResults">Could not find "' + address + '" for the following reasons:<br />' + productCONFIG.reasons[result.Status.code] + '</h4>';
                else document.getElementById('bounds').innerHTML = '<h4 class="noResults">Could not find "' + address + '."</h4>';
            }
        });
    },

    taxonomySearch: function(searchResultSet) {//alert("taxonomySearch");
        var mapInfo = searchResultSet.MapInformation;
        if (mapInfo && mapInfo.Bounds != null) {
            isSearchEnabled = false;
            zipCenterLat = null;
            zipCenterLng = null;
            zipSearched = "";
            setCookie('zipSearch', "", null, "/");
            if (document.getElementById("zipSearch")) {
                document.getElementById("zipSearch").value = "Zip";
            }
            // added 10% padding on the bounds
            var maxX = mapInfo.Bounds.NorthEast.Latitude;
            var minX = mapInfo.Bounds.SouthWest.Latitude;
            var maxY = mapInfo.Bounds.NorthEast.Longitude;
            var minY = mapInfo.Bounds.SouthWest.Longitude;
            if (getCurrSite() == "DelWebb" && selectedGeoType == "region" && selectedGeoID == 52) {
                //alert(maxX); alert(minX);
                maxX = maxX - 0.4
            }
            var span = new GSize(Math.abs(maxX - minX), Math.abs(maxY - minY));
            var slopWid = 0;
            var slopHgt = 0;

            var slopPercentage = 10; // 10% padding on the map
            var heightOffsetPct = 10;  // 10% padding on the map
            slopWid = span.width * slopPercentage / 200;
            slopHgt = span.height * slopPercentage / 200;
            span.width *= 1 + slopPercentage / 100;
            span.height *= 1 + slopPercentage / 100;
            var deltaHgt = 0;
            deltaHgt = span.height * heightOffsetPct / 100;
            var markerBounds = new GLatLngBounds(new GLatLng(minX - slopHgt, minY - slopWid), new GLatLng(maxX + slopHgt, maxY + slopWid)); // sw, ne
            var zLevel = map.getBoundsZoomLevel(markerBounds);
            map.setCenter(markerBounds.getCenter());

            /*
            var markerBounds = new GLatLngBounds(new GLatLng(mapInfo.Bounds.SouthWest.Latitude, mapInfo.Bounds.SouthWest.Longitude), new GLatLng(mapInfo.Bounds.NorthEast.Latitude, mapInfo.Bounds.NorthEast.Longitude)); // sw, ne
            var zLevel = map.getBoundsZoomLevel(markerBounds);
            map.setCenter(new GLatLng(mapInfo.CenterPoint.Latitude, mapInfo.CenterPoint.Longitude));
            */
            map.setZoom(zLevel);

            if (mapInfo.SearchPageImagePath != null) {
                setCookie('SearchPageImagePath', mapInfo.SearchPageImagePath, null, "/");
                setCookie('SearchPageImageUrl', mapInfo.SearchPageImageUrl, null, "/");
                setCookie('SearchPageImageAltText', mapInfo.SearchPageImageAltText, null, "/");
                //document.getElementById('leadImage').src = mapInfo.SearchPageImagePath;
                //document.getElementById('searchleadImage').style.display='block';
            } else {
                setCookie('SearchPageImagePath', null, null, "/");
                setCookie('SearchPageImageUrl', null, null, "/");
                setCookie('SearchPageImageAltText', null, null, "/");
                //document.getElementById('searchleadImage').style.display='none';
            }

            // display Geo Description 
            //alert("mapInfo.GeoDescription");alert(mapInfo.GeoDescription);
            if (mapInfo.GeoDescription != null) {
                document.getElementById('geoDescription').innerHTML = mapInfo.GeoDescription;
                document.getElementById('geoDescription').style.visibility = 'visible';
                document.getElementById('seocopy').style.visibility = 'visible';
            }
            else {
                document.getElementById('geoDescription').innerHTML = '';
                document.getElementById('geoDescription').style.visibility = 'hidden';
                document.getElementById('seocopy').style.visibility = 'hidden';
                switchTab('primaryTabs', 'communitylisting');
            }
            // set the title value
            geoPageTitle = mapInfo.PageTitle;
            pageTitleStateName = mapInfo.StateName;
            pageTitleStateAbbreviation = mapInfo.StateAbbreviation;
            // set the bounds track if the map has moved
            var bounds = map.getBounds();
            var southWest = bounds.getSouthWest();
            var northEast = bounds.getNorthEast();
            mapBounds.southWest = southWest;
            mapBounds.northEast = northEast;
            MapSearch.toggleLoadingMessage(true);
            window.setTimeout(function() { Pulte08.AjaxWebServices.MapService.FilterByGeo(brandIdList, northEast.lat(), northEast.lng(), southWest.lat(), southWest.lng(), MapSearch.newBounds); }, mapLoadWaitTime);
            isSearchEnabled = true;
        } else {
            document.getElementById('bounds').innerHTML = '<h4 class="noResults">We were not able to find any communities that matched your preferences. Please change your search parameters and try again.</h4><br />';
            // remove the loading message
            MapSearch.toggleLoadingMessage(false);
            isSearchEnabled = true;
            return;
        }
    },


    // new bound search
    newBounds: function(searchResultSet) {
        //alert("newBounds");
        isResetSlider = false;
        if (!searchResultSet) {
            //SearchControlUtils.updateSearchLink(0,0);
            document.getElementById('bounds').innerHTML = '<h4 class="noResults">We were not able to find any communities that matched your preferences. Please change your search parameters and try again.</h4><br />';
            // remove the loading message
            MapSearch.toggleLoadingMessage(false);
            isSearchEnabled = true;
            return;
        }

        if (searchResultSet.MapInformation != null) {
            if (searchResultSet.MapInformation.Bounds) {
                MapSearch.taxonomySearch(searchResultSet);
                return;
            }
            else {
                //SearchControlUtils.updateSearchLink(0,0);
                document.getElementById('bounds').innerHTML = '<h4 class="noResults">We were not able to find any communities that matched your preferences. Please change your search parameters and try again.</h4><br />';
                // remove the loading message
                MapSearch.toggleLoadingMessage(false);
                isSearchEnabled = true;
                return;
            }
        }

        curZoom = map.getZoom();

        //community results
        var result = searchResultSet.MarkerSummary;
        var hardControls = searchResultSet.HardControls;

        if (hardControls) {
            /* Price Slider was disabled with Release 1.0.6
            var minPrice = searchResultSet.HardControls.UnFilteredMinPrice;
            var maxPrice = searchResultSet.HardControls.UnFilteredMaxPrice;
            YAHOO.productSlider.setLimits(minPrice, maxPrice);
            if(!userModifiedSlider) {YAHOO.productSlider.setValues(minPrice, maxPrice);}
            if(hardControls.SearchParams.PriceFrom && hardControls.SearchParams.PriceTo){
            YAHOO.productSlider.setValues(parseInt(hardControls.SearchParams.PriceFrom), parseInt(hardControls.SearchParams.PriceTo));
            var sliderReset = YUD.getElementsByClassName('sliderReset','','slider')[0];
            sliderReset.style.display = 'inline';
            }
            */

            SearchControlUtils.updateCheckboxRadioControls(productCONFIG.ControlIdName['homeType'], fldHomeType, hardControls.HomeType, hardControls.SearchParams.HomeType);
            SearchControlUtils.updateCheckboxRadioControls(productCONFIG.ControlIdName['stories'], storyButtonArray, hardControls.Stories, hardControls.SearchParams.Stories);
            SearchControlUtils.updateCheckboxRadioControls(productCONFIG.ControlIdName['bedrooms'], bedroomButtonArray, hardControls.Bedrooms, hardControls.SearchParams.Bedrooms);
            SearchControlUtils.updateCheckboxRadioControls(productCONFIG.ControlIdName['bathrooms'], bathroomButtonArray, hardControls.Bathrooms, hardControls.SearchParams.Bathrooms);
            SearchControlUtils.updateCheckboxRadioControls(productCONFIG.ControlIdName['sqft'], fldSqFt, hardControls.SqFt, hardControls.SearchParams.SquareFootage);
            //SearchControlUtils.updateCheckboxRadioControls(productCONFIG.ControlIdName['price'], fldPrice, hardControls.Price, hardControls.SearchParams.PriceList);
            // DiVosta does not have Active Adult
            if (getCurrSite() != "DiVosta") {
                SearchControlUtils.updateCheckboxRadioControls(productCONFIG.ControlIdName['activeAdult'], fldActiveAdult, hardControls.ActiveAdult, hardControls.SearchParams.ActiveAdult);
            }

            SearchControlUtils.updateCheckboxRadioControls(productCONFIG.ControlIdName['garage'], garageButtonArray, hardControls.Garages, hardControls.SearchParams.Garage);
            SearchControlUtils.updateCheckboxRadioControls(productCONFIG.ControlIdName['availableNow'], fldAvailableNow, hardControls.HomesAvailable, hardControls.SearchParams.HomesAvailableNow);
            SearchControlUtils.updateCheckboxRadioControls(productCONFIG.ControlIdName['communityType'], fldCommunityType, hardControls.CommunityType, hardControls.SearchParams.CommunityType);
            if (getCurrSite() == "DelWebb") {
                SearchControlUtils.updateCheckboxRadioControls(productCONFIG.ControlIdName['subBrand'], fldSubBrand, hardControls.SubBrand, hardControls.SearchParams.SubBrand);
                if ((pageTitleSubBrand != hardControls.SearchParams.SubBrand) || (pageTitleSubBrand != null && hardControls.SearchParams.SubBrand == null)) {
                    loadBreadcrumb = true;
                }
                pageTitleSubBrand = hardControls.SearchParams.SubBrand;
            }
            var priceCount = searchResultSet.PriceCount;
            var priceArray = new Array(9);
            for (i = 0; i <= 8; i++) {
                if (priceCount[i] > 0) { priceArray[i] = i + 1; } else { priceArray[i] = 0; }
            }
            SearchControlUtils.updateCheckboxRadioControls(productCONFIG.ControlIdName['price'], fldPrice, priceArray, hardControls.SearchParams.PriceList);
            SearchControlUtils.resetAllClearLinks();
        }

        // update other brand's search link data
        //SearchControlUtils.updateSearchLink(searchResultSet.OtherPlanCount, searchResultSet.OtherCommunityCount);
        //SearchControlUtils.updateHomeCount(searchResultSet.PlanCount, searchResultSet.CommunityCount);


        var taxonomy = searchResultSet.Taxonomy;
        // add new result marker on the map
        var bubbleContent, marker, tempId;

        if (curZoom < productCONFIG['regionZoomLevel']) {
            // handle zoom level between 3 to 8

            // if it is a region click, display dynamic cluster
            if (dynamicCluster) {
                MapSearch.buildDynamicCluster(result);
            }
            else {
                //otherwise, display state or region marker
                var isState = true;
                if (curZoom > productCONFIG['stateZoomLevel']) isState = false;
                var filteredTaxonomy = searchResultSet.FilteredTaxonomy;
                if (filteredTaxonomy) {
                    for (var z = 0; z < filteredTaxonomy.length; z++) {

                        // handle state marker
                        tempId = filteredTaxonomy[z].StateId;
                        bubbleContent = '';
                        if (isState) bubbleContent = '<a href="javascript:MapSearch.zoomToMarkerLocation(' + filteredTaxonomy[z].StateId + ',\'state\')" class="propertyName">' + filteredTaxonomy[z].StateName + '</a><br />';

                        var regionTaxonomy = filteredTaxonomy[z].RegionTaxonomy;
                        if (regionTaxonomy) {
                            for (var y = 0; y < regionTaxonomy.length; y++) {
                                tempId = regionTaxonomy[y].RegionId;
                                if (isState) {
                                    bubbleContent += '<a href="javascript:MapSearch.zoomToMarkerLocation(' + tempId + ',\'region\')">' + regionTaxonomy[y].RegionName + '</a> (' + regionTaxonomy[y].CommunityCount + ((regionTaxonomy[y].CommunityCount > 1) ? " communities" : " community") + ')<br />';
                                }
                                else {
                                    bubbleContent = '<a href="javascript:MapSearch.zoomToMarkerLocation(' + tempId + ',\'region\')" class="propertyName">' + regionTaxonomy[y].RegionName + '</a><br />';
                                }
                                if (!isState) {
                                    // if region marker, loop through metro area
                                    var metroTaxonomy = regionTaxonomy[y].MetroTaxonomy;
                                    if (metroTaxonomy) {
                                        for (var x = 0; x < metroTaxonomy.length; x++) {
                                            tempId = metroTaxonomy[x].MetroId;
                                            bubbleContent += '<a href="javascript:MapSearch.zoomToMarkerLocation(' + tempId + ',\'metro\')">' + metroTaxonomy[x].MetroName + '</a> (' + metroTaxonomy[x].CommunityCount + ((metroTaxonomy[x].CommunityCount > 1) ? " communities" : " community") + ')<br />';
                                        }
                                    }
                                    if (regionTaxonomy[y].Point && regionTaxonomy[y].Point.Latitude && regionTaxonomy[y].Point.Longitude) {
                                        marker = MapSearch.createMarker(new GLatLng(regionTaxonomy[y].Point.Latitude, regionTaxonomy[y].Point.Longitude), bubbleContent, regionTaxonomy[y].CommunityCount);
                                        map.addOverlay(marker);
                                    }
                                }
                            }
                        }
                        // if it is state marker and we have a point
                        if (isState && filteredTaxonomy[z].Point && filteredTaxonomy[z].Point.Latitude && filteredTaxonomy[z].Point.Longitude) {
                            marker = MapSearch.createMarker(new GLatLng(filteredTaxonomy[z].Point.Latitude, filteredTaxonomy[z].Point.Longitude), bubbleContent, filteredTaxonomy[z].CommunityCount);
                            map.addOverlay(marker);
                        }
                    }
                }
            }

        }
        else {
            MapSearch.buildDynamicCluster(result); // clustering markers
        }

        // remove the loading message
        MapSearch.toggleLoadingMessage(false);

        if (taxonomy) currentTaxonomy = taxonomy;

        if (loadBreadcrumb) { //alert(currentTaxonomy.length);
            if (breadcrumbInfo.idType == null || breadcrumbInfo.idType == '') { breadcrumbInfo.idType = 'country'; }
            MapSearch.updateBreadcrumb(breadcrumbInfo.id, breadcrumbInfo.idType); //alert(breadcrumbInfo.idType); alert(breadcrumbInfo.id);
            //loadBreadcrumb = false;
        }
        /*
        // load from current page result
        if(loadPageResult){
        loadPageResult = false;
        currentPage = parseInt(pageResultInfo.curPageNumber);
        // MapSearch.getPage(parseInt(pageResultInfo.pageNumber), parseInt(pageResultInfo.pageType));
        MapSearch.getPage(parseInt(pageResultInfo.curPageNumber), parseInt(pageResultInfo.pageType));
        }
        else {
        loadPageResult = false;
        deleteCookie('searchPageNumber');
        deleteCookie('searchPageType');
        deleteCookie('searchCurrentPage');
        MapSearch.renderSearchResults(searchResultSet);
        }
        */
        tabView = new YAHOO.widget.TabView('primaryTabs');
        var activeIndex = tabView.get('activeIndex');
        var activeTab = tabView.getTab(activeIndex);
        var tabId = activeTab.getElementsByTagName('a')[0].id;
        if (fldAvailableNow.checked) {
            if (searchResultSet.QuickMoveInCount > 0) {
                document.getElementById('availablebounds').innerHTML = searchResultSet.Html;
            }
            else {
                document.getElementById('availablebounds').innerHTML = "";
            }
            if (activeIndex == 0) {
                switchTab('primaryTabs', 'homes-available-now');
            }
            var homesTitle = (searchResultSet.QuickMoveInCount != 1) ? 'Homes' : 'Home';
            var countInfo = searchResultSet.QuickMoveInCount + ' Quick Move-in ' + homesTitle + ' Available in ' + document.getElementById('bc-locName').innerHTML;
            if (searchResultSet.QuickMoveInCount == 0) {
                countInfo = countInfo + "<br /><br />Thank you for your interest.  Please call 1-888-422-7653 to learn more about available Quick Move-In Homes in this area.";
            }
            document.getElementById('availableCount').innerHTML = countInfo;
        }
        else {
            document.getElementById('bounds').innerHTML = searchResultSet.Html;
            var commTitle = (searchResultSet.CommunityCount > 1) ? ' neighborhoods' : ' neighborhood';
            if (getCurrSite().toLowerCase() == 'delwebb' || getCurrSite().toLowerCase() == 'divosta') commTitle = (searchResultSet.CommunityCount > 1) ? ' communities' : ' community';
            var countInfo = searchResultSet.CommunityCount + commTitle + ' located in ' + document.getElementById('bc-locName').innerHTML;
            document.getElementById('communityCount').innerHTML = countInfo;
        }

        sorttable.init();
        // set the counts
        for (i = 0; i <= 8; i++) { priceCount[i] = searchResultSet.PriceCount[i]; }
        for (i = 0; i <= 4; i++) { bedCount[i] = searchResultSet.BedCount[i]; }
        for (i = 0; i <= 3; i++) { bathCount[i] = searchResultSet.BathCount[i]; }
        for (i = 0; i <= 4; i++) { sqFtCount[i] = searchResultSet.SqFtCount[i]; }
        for (i = 0; i <= 1; i++) { planTypeCount[i] = searchResultSet.PlanTypeCount[i]; }
        for (i = 0; i <= 1; i++) { floorCount[i] = searchResultSet.FloorCount[i]; }
        for (i = 0; i <= 2; i++) { garageCount[i] = searchResultSet.GarageCount[i]; }
        for (i = 0; i <= 9; i++) { amenityCount[i] = searchResultSet.AmenityCount[i]; }
        for (i = 0; i <= 1; i++) { activeAdultCount[i] = searchResultSet.CommunityTypeCount[i]; }
        for (i = 0; i <= 0; i++) { subBrandCount[i] = 0; }



        // Alok: Updates to You've Selected Section and Counts for each item
        var uSel = document.getElementById('youSelected');
        var sLoc = uSel.getElementsByTagName('p')[0];
        var topBC = document.getElementById('searchBreadCrumb');
        MapSearch.removeAllChildNodes(sLoc);

        // Get location for You Selected section
        for (var i = 0; i < topBC.childNodes.length; i++) {
            sLoc.appendChild(document.createTextNode(topBC.childNodes[i].innerHTML || topBC.childNodes[i].nodeValue));
        }

        var homeFeat = document.getElementById('selHomeFeatures');
        var hoodFeat = document.getElementById('selHoodFeatures');

        MapSearch.removeAllChildNodes(homeFeat);
        MapSearch.removeAllChildNodes(hoodFeat);

        SearchControlUtils.updateCountsSelections(priceCount, fldPrice, homeFeat);
        SearchControlUtils.updateCountsSelections(bedCount, bedroomButtonArray, homeFeat);
        SearchControlUtils.updateCountsSelections(bathCount, bathroomButtonArray, homeFeat);
        SearchControlUtils.updateCountsSelections(sqFtCount, fldSqFt, homeFeat);
        SearchControlUtils.updateCountsSelections(planTypeCount, fldHomeType, homeFeat);
        SearchControlUtils.updateCountsSelections(floorCount, storyButtonArray, homeFeat);
        SearchControlUtils.updateCountsSelections(garageCount, garageButtonArray, homeFeat);
        SearchControlUtils.updateCountsSelections(amenityCount, fldCommunityType, hoodFeat);

        if (getCurrSite() != "DiVosta") {
            SearchControlUtils.updateCountsSelections(activeAdultCount, fldActiveAdult, hoodFeat);
        }

        if (getCurrSite() == "DelWebb") {
            SearchControlUtils.updateCountsSelections(subBrandCount, fldSubBrand, hoodFeat);
        }

        var selectedFeatures = document.getElementById('selectedFeatures');
        var defaultFeatures = document.getElementById('defaultFeatures');
        var markerType = getCookie('bcType');

        if ((selectedCount <= 0) && (!markerType || markerType == 'country')) {
            selectedFeatures.style.display = 'none';
            defaultFeatures.style.display = 'block';
        }
        else {
            selectedFeatures.style.display = 'block';
            defaultFeatures.style.display = 'none';
        }

        selectedCount = 0;
    },

    doNothing: function() {
        return;
    },

    // removeExistingMarkers
    removeExistingMarkers: function() {
        // get rid of our existing marker on the map
        if (map.pdMarkers && map.pdMarkers.length) {
            while (map.getFirstMarker()) {
                map.getFirstMarker().remove();
            }
        }

        // get rid of any cluster reference
        if (clusterer) {
            clusterer.markers = [];
            clusterer.clusters = [];
            clusterer = null;
        }
    },

    // drawCircle
    drawCircle: function(center, radius, nodes, liColor, liWidth, liOpa, fillColor, fillOpa) {
        //calculating km/degree
        radius = radius * 1.609344;
        var latConv = center.distanceFrom(new GLatLng(center.lat() + 0.1, center.lng())) / 100;
        var lngConv = center.distanceFrom(new GLatLng(center.lat(), center.lng() + 0.1)) / 100;

        //Loop
        var points = [];
        var step = parseInt(360 / nodes) || 10;
        for (var i = 0; i <= 360; i += step) {
            var pint = new GLatLng(center.lat() + (radius / latConv * Math.cos(i * Math.PI / 180)), center.lng() +
            (radius / lngConv * Math.sin(i * Math.PI / 180)));
            points.push(pint);
            polyBounds.extend(pint); //this is for fit function
        }

        fillColor = fillColor || liColor || '#0055ff';
        liWidth = liWidth || 2;
        radiusOverlay = new GPolygon(points, liColor, liWidth, liOpa, fillColor, fillOpa);
        map.addOverlay(radiusOverlay);
    },

    draw: function(pnt, givenRad, givenQuality) {
        if (radiusOverlay) map.removeOverlay(radiusOverlay);
        polyBounds = new GLatLngBounds();
        var centre = pnt || map.getCenter();
        MapSearch.drawCircle(centre, givenRad, givenQuality);
        map.panTo(polyBounds.getCenter());
    },

    fit: function() {
        map.setZoom(map.getBoundsZoomLevel(polyBounds));
    },

    radiusChange: function(radius) {
        isSearchEnabled = false;
        MapSearch.draw(map.getCenter(), radius, 36);
        isSearchEnabled = true;
        MapSearch.fit();
    },

    clearRadiusOverlay: function() {
        if (radiusOverlay != null) {
            map.removeOverlay(radiusOverlay);
        }
        document.getElementById('productsearch').value = productSearchValue;
        document.getElementById('radius').value = '20';
        var searchContainer = YUD.getElementsByClassName('searchForHome')[0];
        var searchReset = YUD.getElementsByClassName('reset', '', searchContainer)[0];
        searchReset.style.display = 'none';
    },

    //buildDynamicCluster
    buildDynamicCluster: function(result) {
        var marker, bubbleContent;
        dynamicCluster = false;
        clusterer = new Clusterer(map);
        for (var i = 0; i < result.length; i++) {
            var point = result[i].Point;

            MapSearch.getMarkerBrand(result[i].BrandId, result[i].ComingSoonFlag);

            bubbleContent = result[i].BubbleContent;

            if (point.Latitude && point.Latitude) {
                var markerPoint = new GLatLng(point.Latitude, point.Longitude);
                marker = MapSearch.createMarker(markerPoint, bubbleContent);
                if (curZoom < productCONFIG['noClusterZoomLevel']) clusterer.AddMarker(marker);
                else map.addOverlay(marker);
            }
        }
    },

    // function to craete marker
    createMarker: function(point, html, markerLabel) {
        var marker;
        if (typeof markerLabel != 'undefined') {
            var opts = {
                'clickable': true,
                'title': markerLabel,
                'labelText': markerLabel,
                'labelOffset': new GSize(-5, -30),
                'labelClass': 'markerLabel'
            };
            if (getCurrSite().toLowerCase() == "centex") {
                marker = new PdMarker(point, mapCONFIG.gIcons['centexMarker'], opts);
                marker.setHoverImage(mapCONFIG.gIconImages['centexMarker'].imageOn);
            }
            else {
                marker = new PdMarker(point, mapCONFIG.gIcons['marker'], opts);
                marker.setHoverImage(mapCONFIG.gIconImages['marker'].imageOn);
            }
        }
        else {
            marker = new PdMarker(point, mapCONFIG.gIcons[curBrand]);
            marker.setHoverImage(mapCONFIG.gIconImages[curBrand].imageOn);
        }

        marker.setDetailWinHTML(html);

        // click event for PDMarker class
        GEvent.addListener(marker, 'click', function() {
            if (marker.getMouseOutEnabled()) { marker.setMouseOutEnabled(false); }
            else { marker.setMouseOutEnabled(true); }
        });

        return marker;
    },

    getMarkerBrand: function(brandId, soonFlag) {
        if (!brandId || brandId == '') return;
        switch (brandId) {
            case 1: curBrand = 'pulte'; break;
            case 2: curBrand = 'delwebb'; break;
            case 3: curBrand = 'divosta'; break;
            case 4: curBrand = 'centex'; break;
            default: curBrand = 'pulte';
        }
        if (soonFlag || soonFlag == 'true') curBrand += 'Soon';
    },

    // getResultBrand
    getResultBrand: function(brandId) {
        var brandName = 'Pulte';
        switch (brandId) {
            case 1: brandName = 'Pulte'; break;
            case 2: brandName = 'DelWebb'; break;
            case 3: brandName = 'Divosta'; break;
            case 4: brandName = 'Centex'; break;
        }
        return brandName;
    },

    // getResultBrand
    getResultBrandURL: function(brandId) {
        var url = 'http://www.pulte.com';
        switch (brandId) {
            case 1: url = 'http://www.pulte.com'; break;
            case 2: url = 'http://www.divosta.com'; break;
            case 3: url = 'http://www.delwebb.com'; break;
            case 4: url = 'http://www.centex.com'; break;
        }
        return url;
    },

    //controlGroupSearch
    controlGroupSearch: function(controlName, searchValues, isChecked) {
        //display loading message
        MapSearch.toggleLoadingMessage(true);
        switch (controlName) {
            case productCONFIG.ControlIdName['garage']:
                Pulte08.AjaxWebServices.MapService.FilterByGarage(brandIdList, searchValues, MapSearch.newBounds);
                break;
            case productCONFIG.ControlIdName['bedrooms']:
                Pulte08.AjaxWebServices.MapService.FilterByBedrooms(brandIdList, searchValues, MapSearch.newBounds);
                break;
            case productCONFIG.ControlIdName['bathrooms']:
                Pulte08.AjaxWebServices.MapService.FilterByBathrooms(brandIdList, searchValues, MapSearch.newBounds);
                break;
            case productCONFIG.ControlIdName['stories']:
                Pulte08.AjaxWebServices.MapService.FilterByStories(brandIdList, searchValues, MapSearch.newBounds);
                break;
            case productCONFIG.ControlIdName['homeType']:
                Pulte08.AjaxWebServices.MapService.FilterByHomeType(brandIdList, searchValues, MapSearch.newBounds);
                break;
            case productCONFIG.ControlIdName['communityType']:
                Pulte08.AjaxWebServices.MapService.FilterByCommunityType(brandIdList, searchValues, MapSearch.newBounds);
                break;
            case productCONFIG.ControlIdName['subBrand']:
                Pulte08.AjaxWebServices.MapService.FilterBySubBrand(brandIdList, searchValues, MapSearch.newBounds);
                break;
            case productCONFIG.ControlIdName['sqft']:
                Pulte08.AjaxWebServices.MapService.FilterBySquareFootage(brandIdList, searchValues, MapSearch.newBounds);
                break;
            case productCONFIG.ControlIdName['price']:
                Pulte08.AjaxWebServices.MapService.FilterByPrice(brandIdList, searchValues, MapSearch.newBounds);
                break;
            case productCONFIG.ControlIdName['activeAdult']:
                Pulte08.AjaxWebServices.MapService.FilterByActiveAdult(brandIdList, searchValues, MapSearch.newBounds);
                break;
            case productCONFIG.ControlIdName['poi']:
                Pulte08.AjaxWebServices.MapService.FilterByPOI(brandIdList, searchValues, MapSearch.newBounds);
                break;
            case productCONFIG.ControlIdName['availableNow']:
                Pulte08.AjaxWebServices.MapService.FilterByHomesAvailableNow(brandIdList, searchValues, MapSearch.newBounds);
                break;
            case productCONFIG.ControlIdName['bandb']:
                Pulte08.AjaxWebServices.MapService.ResetBedroomsAndBathrooms(MapSearch.newBounds);
                break;
        }
    },

    // searchOtherBrands
    searchOtherBrands: function() {
        var curBrand = getCurrSite().toLowerCase();
        brandIdList = [];
        switch (curBrand) {
            case 'pulte': brandIdList.push(productCONFIG.brandIds['divosta']); brandIdList.push(productCONFIG.brandIds['delwebb']); break;
            case 'divosta': brandIdList.push(productCONFIG.brandIds['pulte']); brandIdList.push(productCONFIG.brandIds['delwebb']); break;
            case 'delwebb': brandIdList.push(productCONFIG.brandIds['pulte']); brandIdList.push(productCONFIG.brandIds['divosta']); break;
        }
        MapSearch.toggleLoadingMessage(true);
        Pulte08.AjaxWebServices.MapService.FilterByBrand(brandIdList, MapSearch.newBounds);
    },

    // pan the map to the location given and zoom to proper level
    zoomToMarkerLocation: function(linkId, markerType) {
        // disable the moveend listen
        isSearchEnabled = false;

        //clear radioOverly if exists
        MapSearch.clearRadiusOverlay();

        // force the dynamic clustering
        if (markerType == 'region' || markerType == 'metro')
            dynamicCluster = true;

        if (curClickedMarker) {
            curClickedMarker.closeDetailWin();
        }

        // set update breadcrumb variables
        if (linkId) {
            loadBreadcrumb = true;
            breadcrumbInfo.id = linkId;
            breadcrumbInfo.idType = markerType;
            setCookie('bcId', linkId, null, "/");
            setCookie('bcType', markerType, null, "/");
        }
        //display loading message
        MapSearch.toggleLoadingMessage(true);
        // set the global variables to be used in other places
        selectedGeoID = linkId;
        selectedGeoType = markerType;
        switch (markerType) {
            case 'state':
                window.setTimeout(function() { Pulte08.AjaxWebServices.MapService.FilterCommunitiesByState(linkId, MapSearch.taxonomySearch); }, mapLoadWaitTime);
                break;
            case 'region':
                window.setTimeout(function() { Pulte08.AjaxWebServices.MapService.FilterCommunitiesByRegion(linkId, MapSearch.taxonomySearch); }, mapLoadWaitTime);
                break;
            case 'metro':
                window.setTimeout(function() { Pulte08.AjaxWebServices.MapService.FilterCommunitiesByMetro(linkId, MapSearch.taxonomySearch); }, mapLoadWaitTime);
                break;
        }

    },

    // cluster zoom
    zoomToCluster: function(lat, lng, zoom) {
        // disable the moveend listen
        MapSearch.clearRadiusOverlay();
        isSearchEnabled = false;
        if (curClickedMarker) {
            curClickedMarker.closeDetailWin();
        }
        //clear radioOverly if exists
        MapSearch.clearRadiusOverlay();

        map.setCenter(new GLatLng(lat, lng));
        zoom = this.getMaxZoom(zoom);
        isSearchEnabled = true;
        window.setTimeout(function() { map.setZoom(zoom); }, mapLoadWaitTime);
    },

    //zoomToCountry
    zoomToCountry: function() {//alert("zoomToCountry");
        MapSearch.clearRadiusOverlay();
        isSearchEnabled = false;
        this.updateBreadcrumb(0, 'country');
        if (curClickedMarker) curClickedMarker.closeDetailWin();
        map.setCenter(new GLatLng(defaultMapLat, defaultMapLng));
        breadcrumbInfo.id = '';
        breadcrumbInfo.idType = 'country';
        setCookie('bcId', breadcrumbInfo.id, null, "/");
        setCookie('bcType', breadcrumbInfo.idType, null, "/");
        isSearchEnabled = true;

        window.setTimeout(function() { map.setZoom(productCONFIG.defaultMapZoom()); }, mapLoadWaitTime);
    },

    //getMaxZoom Level from Normal map
    getMaxZoom: function(zoom) {
        var maxRes = G_NORMAL_MAP.getTileLayers()[0].maxResolution();
        if (zoom > maxRes) zoom = maxRes;
        return zoom;
    },

    //updateBreadcrumb base on Taxonomy version 2
    updateBreadcrumb: function(linkId, markerType) {
        var markerId, parentNode, selectedNode, childNodes, usNode;
        if (markerType == 'country') {
            //alert("country");
            var loc = document.getElementById('bc-locName');
            loc.innerHTML = 'United States';
            this.updateWindowTitle('', '');
            var nav = YUD.getElementsByClassName('navHdr', 'div')[0];
            var p = nav.getElementsByTagName('p')[0];
            var ul = nav.getElementsByTagName('ul')[0];
            this.removeAllChildNodes(p);
            this.removeAllChildNodes(ul);
            setCookie('SearchPageImagePath', null, null, "/");
            setCookie('SearchPageImageUrl', null, null, "/");
            setCookie('SearchPageImageAltText', null, null, "/");

            var temp_a = document.createElement('a');
            temp_a.href = 'javascript:MapSearch.zoomToCountry()';
            temp_a.appendChild(document.createTextNode('United States'));
            p.appendChild(temp_a);
            //p.appendChild(document.createTextNode('United States'));

            temp_li = document.createElement('li');
            temp_li.innerHTML = '&nbsp';
            ul.appendChild(temp_li);
            // top breadcrumb
            var topBC = document.getElementById('searchBreadCrumb');
            if (topBC != null) {
                topBC.innerHTML = '<a href="javascript:MapSearch.zoomToCountry()">United States</a>';
            }
            if (document.getElementById('seocopy') != null) {
                document.getElementById('seocopy').style.visibility = 'hidden';
                switchTab('primaryTabs', 'communitylisting');
            }
        }
        else { // use taxonomy instead
            for (var i = 0; i < currentTaxonomy.length; i++) {
                if (markerType == 'state') {
                    if (currentTaxonomy[i].StateId == linkId || currentTaxonomy[i].StateAbbr == (linkId + "").toUpperCase()) {
                        parentNode = { name: 'United States', id: '', idType: 'country', communities: 0 };
                        selectedNode = { name: currentTaxonomy[i].StateName, id: currentTaxonomy[i].StateId, idType: 'state', communities: currentTaxonomy[i].CommunityCount };
                        childNodes = MapSearch.buildChildList(currentTaxonomy[i].RegionTaxonomy, 'region');
                        break;
                    }
                } else if (markerType == "region") {
                    for (var j = 0; j < currentTaxonomy[i].RegionTaxonomy.length; j++) {
                        if (currentTaxonomy[i].RegionTaxonomy[j].RegionId == linkId) {
                            usNode = { name: 'United States', id: '', idType: 'country', communities: 0 };
                            parentNode = { name: currentTaxonomy[i].StateName, id: currentTaxonomy[i].StateId, idType: 'state', communities: currentTaxonomy[i].CommunityCount };
                            selectedNode = { name: currentTaxonomy[i].RegionTaxonomy[j].RegionName, id: currentTaxonomy[i].RegionTaxonomy[j].RegionId, idType: 'region', communities: currentTaxonomy[i].RegionTaxonomy[j].CommunityCount };
                            childNodes = MapSearch.buildChildList(currentTaxonomy[i].RegionTaxonomy[j].MetroTaxonomy, 'metro');
                            break;
                        }
                    }
                } else if (markerType == "metro") {
                    var isFound = false;
                    for (var j = 0; j < currentTaxonomy[i].RegionTaxonomy.length; j++) {
                        for (var k = 0; k < currentTaxonomy[i].RegionTaxonomy[j].MetroTaxonomy.length; k++) {
                            if (currentTaxonomy[i].RegionTaxonomy[j].MetroTaxonomy[k].MetroId == linkId) {
                                usNode = { name: 'United States', id: '', idType: 'country', communities: 0, abbr: '' };
                                parentNode = { name: currentTaxonomy[i].StateName, id: currentTaxonomy[i].StateId, idType: 'state', communities: currentTaxonomy[i].CommunityCount, abbr: currentTaxonomy[i].StateAbbr };
                                selectedNode = { name: currentTaxonomy[i].RegionTaxonomy[j].RegionName, id: currentTaxonomy[i].RegionTaxonomy[j].RegionId, idType: 'region', communities: currentTaxonomy[i].RegionTaxonomy[j].CommunityCount, abbr: currentTaxonomy[i].StateAbbr };
                                childNodes = [{ name: currentTaxonomy[i].RegionTaxonomy[j].MetroTaxonomy[k].MetroName, id: currentTaxonomy[i].RegionTaxonomy[j].MetroTaxonomy[k].MetroId, idType: 'metro', communities: currentTaxonomy[i].RegionTaxonomy[j].MetroTaxonomy[k].CommunityCount, abbr: currentTaxonomy[i].StateAbbr}];
                                break;
                            }
                        }
                        if (isFound) break;
                    }
                }
            } // end the for loop
            if (currentTaxonomy.length == 0 && zipSearched != null && zipSearched != "") {
                // nothing found in zip search
                var loc = document.getElementById('bc-locName');
                locationName = zipSearched + " zip code area";
                loc.innerHTML = locationName;
            }
            if (parentNode) {
                var loc = document.getElementById('bc-locName');
                var locationName = "";
                if (markerType == "metro") { // selectedNode is still a region
                    locationName = childNodes[0].name;
                } else {
                    locationName = selectedNode.name;
                }
                if (zipSearched != null && zipSearched != "") {
                    locationName = zipSearched + " zip code area";
                }
                loc.innerHTML = locationName;
                this.updateWindowTitle(locationName, pageTitleStateAbbreviation);

                var nav = YUD.getElementsByClassName('navHdr', 'div')[0];
                var p = nav.getElementsByTagName('p')[0];
                var ul = nav.getElementsByTagName('ul')[0];
                this.removeAllChildNodes(p);
                this.removeAllChildNodes(ul);
                var temp_a, temp_span, temp_li, temp;
                var topBC = document.getElementById('searchBreadCrumb');
                this.removeAllChildNodes(topBC);

                // check is uSNode is on
                if (usNode) {
                    temp_a = document.createElement('a');
                    temp_a.href = 'javascript:MapSearch.zoomToCountry()';
                    temp_a.appendChild(document.createTextNode(usNode.name));
                    p.appendChild(temp_a);
                    p.appendChild(document.createTextNode(' > '));
                }

                temp_a = document.createElement('a');
                if (parentNode.idType == 'country') {
                    temp_a.href = 'javascript:MapSearch.zoomToCountry()';
                } else {
                    temp_a.href = 'javascript:MapSearch.zoomToMarkerLocation(' + parentNode.id + ',"' + parentNode.idType + '")';
                }
                temp_a.appendChild(document.createTextNode(parentNode.name));
                p.appendChild(temp_a);
                p.appendChild(document.createTextNode(' > '));

                // if type is metro, make the selected linkable as well
                if (markerType == "metro") {
                    temp_a = document.createElement('a');
                    temp_a.href = 'javascript:MapSearch.zoomToMarkerLocation(' + selectedNode.id + ',"' + selectedNode.idType + '")';
                    temp_a.appendChild(document.createTextNode(selectedNode.name));
                    p.appendChild(temp_a);
                    topBC.innerHTML = p.innerHTML;
                } else {
                    topBC.innerHTML = p.innerHTML;
                    topBC.innerHTML += '<a href="javascript:MapSearch.zoomToMarkerLocation(' + selectedNode.id + ',\'' + selectedNode.idType + '\')">' + selectedNode.name + '</a>';
                    p.appendChild(document.createTextNode(selectedNode.name));
                }

                for (var k = 0; k < childNodes.length; k++) {
                    temp_li = document.createElement('li');
                    /* 1.0.6 - don't show community counts in geo taxonomy
                    temp_span = document.createElement('span');
                    temp = '(' + childNodes[k].communities + ((childNodes[k].communities > 1)?' communities)':' community)');
                    temp_span.appendChild(document.createTextNode(temp));
                    temp_li.appendChild(temp_span);                                   */
                    if (markerType == "metro") {
                        temp_li.appendChild(document.createTextNode(childNodes[k].name));
                        ul.appendChild(temp_li);
                        topBC.innerHTML += ' > <a href="javascript:MapSearch.zoomToMarkerLocation(' + childNodes[k].id + ',\'' + childNodes[k].idType + '\')">' + childNodes[k].name + '</a>';
                    } else {
                        temp_a = document.createElement('a');
                        temp_a.href = 'javascript:MapSearch.zoomToMarkerLocation(' + childNodes[k].id + ',"' + childNodes[k].idType + '")';
                        temp_a.appendChild(document.createTextNode(childNodes[k].name));
                        temp_li.appendChild(temp_a);
                    }
                    ul.appendChild(temp_li);
                }
                loadBreadcrumb = false; // don't load it again
            }
        }
        if (document.getElementById('searchleadImage') && document.getElementById('searchleadImage') != null) {
            // display or hide image above search criteria
            searchPageImagePath = getCookie('SearchPageImagePath');

            if ((searchPageImagePath != null) && (searchPageImagePath != 'null') && (searchPageImagePath != '')) { // IE gets a string value, not actuall NULL
                //alert(searchPageImagePath);
                searchPageImageUrl = getCookie('SearchPageImageUrl');
                searchPageImageAltText = getCookie('SearchPageImageAltText');
                document.getElementById('leadImage').src = searchPageImagePath;
                document.getElementById('leadImage').setAttribute("title", searchPageImageAltText);
				if ((searchPageImageUrl != null) && (searchPageImageUrl != 'null') && (searchPageImageUrl != '')) {
					document.getElementById('leadImageUrl').setAttribute("href", searchPageImageUrl);
					if (searchPageImageUrl.indexOf("geotype") > -1){
						document.getElementById('leadImageUrl').setAttribute("target", "_blank");
					}
				}else{
					document.getElementById('leadImageUrl').setAttribute("href", "#");
				}
				
                document.getElementById('searchleadImage').style.display = 'block';
            } else {
                //alert('no cookie');
                document.getElementById('searchleadImage').style.display = 'none';
            }
        }
    },
    // end of updateBreadcrumb base on Taxonomy

    // updateWindowTitle
    updateWindowTitle: function(location, state) {
        //alert(getCurrSite()); alert(location); alert(state); alert(breadcrumbInfo.idType);
        var pageTitle = "";
        if (location != "") location = location + " ";
        if (state != "") state = state + " ";
        if (getCurrSite() == "Pulte") {
            if (jQuery.trim(location) == pageTitleStateName) {  // it's state level, title is different
                pageTitle = "New Homes " + location + '| ' + location + "New Home Builder | Pulte Homes";
            } else {
                pageTitle = "New Homes " + location + state + '| ' + location + "New Home Builder | Pulte Homes";
            }
        } else if (getCurrSite() == "Centex") {
            if (jQuery.trim(location) == pageTitleStateName) {  // it's state level, title is different
                pageTitle = location + " New Homes | " + location + " Home Builder | Centex Homes";
            } else {
                pageTitle = location + " New Homes for Sale | " + location + " Home Builder | Centex Homes";
            }
        } else {
            if (getCurrSite() == "DelWebb") {
                //alert(pageTitleSubBrand);
                if (pageTitleSubBrand == null) {
                    if (state != "" && breadcrumbInfo.idType == "metro") {
                        pageTitle = "Retirement Communities " + location + "| 55+ Senior Communities " + state + " - Del Webb homes";
                    } else {
                        pageTitle = "Retirement Communities " + location + "| Active Adult Communities " + state + " - Del Webb homes";
                    }
                    // change text in region title if it's stored in GeoDescription back to what it is in the database
                    if (!(geoPageTitle == null || geoPageTitle == "TBD")) {
                        geoPageTitle = geoPageTitle.replace("Sun City", "Retirement").replace("Resort Style Active Adult Communities", "Active Adult Communities");
                    }
                }
                else { // sun city subbrand was selected
                    if (jQuery.trim(location) == pageTitleStateName) {  // it's state level, title is different for Sun City
                        pageTitle = "Sun City Communities " + location + "| Resort Style Active Adult Communities | Del Webb homes";
                    } else {
                        pageTitle = "Sun City Communities " + location + "| Resort Style Active Adult Communities " + state + "| Del Webb homes";
                    }
                    // change text in title if it's stored in GeoDescription
                    if (!(geoPageTitle == null || geoPageTitle == "TBD")) {
                        geoPageTitle = geoPageTitle.replace("Retirement", "Sun City").replace("Active Adult Communities", "Resort Style Active Adult Communities").replace("55+ Senior Communities", "Resort Style Active Adult Communities");
                    }
                }
            } else { // divosta 
                pageTitle = getCurrSite() + " Homes | " + location + "New Homes | Find a New Home That's Right for You in " + location;
            }
        }
        if (geoPageTitle == null || geoPageTitle == "TBD" || location == "") {
            document.title = pageTitle;
        }
        else {
            document.title = geoPageTitle;
        }
        /*  AG 9/28/09: leave meta description as it was generated initially.
        //changing the meta description dynamically
        if (document.getElementsByName) {
        var metaArray = document.getElementsByName('description');
        newTag = "Search for new homes in the " + location + ". Choose your new home price, new home type, amenities and view all new home plan models";
        metaArray[0].content = newTag;
        }
        */
    },

    // removeAllChildNodes
    removeAllChildNodes: function(obj) {
        if (obj.hasChildNodes()) {
            while (obj.childNodes.length > 0) {
                obj.removeChild(obj.firstChild);
            }
        }
    },

    // populateSearchParams
    populateSearchParams: function(qsObj) {
        //alert("populateSearchParams");
        var searchParams = new Object();
        searchParams.cnt = 0;
        // bounds
        if (qsObj.get('nelat')) {
            searchParams.Bounds = new Object();
            searchParams.Bounds.NorthEast = new Object();
            searchParams.Bounds.NorthEast.Latitude = qsObj.get('nelat');
            searchParams.cnt += 1;
        }
        if (qsObj.get('nelng')) {
            if (!searchParams.Bounds) searchParams.Bounds = new Object();
            if (!searchParams.Bounds.NorthEast) searchParams.Bounds.NorthEast = new Object();
            searchParams.Bounds.NorthEast.Longitude = qsObj.get('nelng');
            searchParams.cnt += 1;
        }
        if (qsObj.get('swlat')) {
            if (!searchParams.Bounds) searchParams.Bounds = new Object();
            if (!searchParams.Bounds.SouthWest) searchParams.Bounds.SouthWest = new Object();
            searchParams.Bounds.SouthWest.Latitude = qsObj.get('swlat');
            searchParams.cnt += 1;
        }
        if (qsObj.get('swlng')) {
            if (!searchParams.Bounds) searchParams.Bounds = new Object();
            if (!searchParams.Bounds.SouthWest) searchParams.Bounds.SouthWest = new Object();
            searchParams.Bounds.SouthWest.Longitude = qsObj.get('swlng');
            searchParams.cnt += 1;
        }
        // price list
        if (qsObj.get('price')) {
            searchParams.PriceList = [];
            if (qsObj.get('price').indexOf(',') > -1) {
                var vals = qsObj.get('price').split(',');
                for (var i = 0; i < vals.length; i++) {
                    searchParams.PriceList.push(vals[i]);
                }
            } else {
                searchParams.PriceList.push(qsObj.get('price'));
            }
            // set the control to be checked
            SearchControlUtils.setCheckboxRadioControls(productCONFIG.ControlIdName['price'], fldPrice, searchParams.PriceList);
            searchParams.cnt += 1;
        }

        // hometype
        if (qsObj.get('htype')) {
            searchParams.HomeType = [];
            if (qsObj.get('htype').indexOf(',') > -1) {
                var vals = qsObj.get('htype').split(',');
                for (var i = 0; i < vals.length; i++) {
                    searchParams.HomeType.push(vals[i]);
                }
            } else {
                searchParams.HomeType.push(qsObj.get('htype'));
            }
            // set the control to be checked
            SearchControlUtils.setCheckboxRadioControls(productCONFIG.ControlIdName['homeType'], fldHomeType, searchParams.HomeType);
            searchParams.cnt += 1;
        }
        //stories
        if (qsObj.get('story')) {
            searchParams.Stories = [];
            if (qsObj.get('story').indexOf(',') > -1) {
                var vals = qsObj.get('story').split(',');
                for (var i = 0; i < vals.length; i++) {
                    searchParams.Stories.push(vals[i]);
                }
            } else {
                searchParams.Stories.push(qsObj.get('story'));
            }
            // set the control to be checked
            SearchControlUtils.setCheckboxRadioControls(productCONFIG.ControlIdName['stories'], storyButtonArray, searchParams.Stories);
            searchParams.cnt += 1;
        }
        // bedrooms
        if (qsObj.get('bed')) {
            searchParams.Bedrooms = [];
            if (qsObj.get('bed').indexOf(',') > -1) {
                var vals = qsObj.get('bed').split(',');
                for (var i = 0; i < vals.length; i++) {
                    searchParams.Bedrooms.push(vals[i]);
                }
            } else {
                searchParams.Bedrooms.push(qsObj.get('bed'));
            }
            // set the control to be checked
            SearchControlUtils.setCheckboxRadioControls(productCONFIG.ControlIdName['bedrooms'], bedroomButtonArray, searchParams.Bedrooms);
            searchParams.cnt += 1;
        }
        // bathrooms
        if (qsObj.get('bath')) {

            searchParams.Bathrooms = [];
            if (qsObj.get('bath').indexOf(',') > -1) {
                var vals = qsObj.get('bath').split(',');
                for (var i = 0; i < vals.length; i++) {
                    searchParams.Bathrooms.push(vals[i]);
                }
            } else {
                searchParams.Bathrooms.push(qsObj.get('bath'));
            }
            // set the control to be checked
            SearchControlUtils.setCheckboxRadioControls(productCONFIG.ControlIdName['bathrooms'], bathroomButtonArray, searchParams.Bathrooms);
            searchParams.cnt += 1;
        }
        //square footage
        if (qsObj.get('sqft')) {
            searchParams.SquareFootage = [];
            if (qsObj.get('sqft').indexOf(',') > -1) {
                var vals = qsObj.get('sqft').split(',');
                for (var i = 0; i < vals.length; i++) {
                    searchParams.SquareFootage.push(vals[i]);
                }
            } else {
                searchParams.SquareFootage.push(qsObj.get('sqft'));
            }
            // set the control to be checked
            SearchControlUtils.setCheckboxRadioControls(productCONFIG.ControlIdName['sqft'], fldSqFt, searchParams.SquareFootage);
            searchParams.cnt += 1;
        }
        // garage
        if (qsObj.get('g')) {
            searchParams.Garage = [];
            if (qsObj.get('g').indexOf(',') > -1) {
                var vals = qsObj.get('g').split(',');
                for (var i = 0; i < vals.length; i++) {
                    searchParams.Garage.push(vals[i]);
                }
            } else {
                searchParams.Garage.push(qsObj.get('g'));
            }
            // set the control to be checked
            SearchControlUtils.setCheckboxRadioControls(productCONFIG.ControlIdName['garage'], garageButtonArray, searchParams.Garage);
            searchParams.cnt += 1;
        }

        /* Price slider is disabled Release 1.0.6
        var minPrice, maxPrice;
        // price from
        if(qsObj.get('pf')){
        searchParams.PriceFrom = qsObj.get('pf');
        // set the min price in the slider
        userModifiedSlider = true;
        minPrice = parseInt(qsObj.get('pf'));
        searchParams.cnt += 1;
        }
        // price to
        if(qsObj.get('pt')){
        searchParams.PriceTo = qsObj.get('pt');
        // set the max price in the slider
        userModifiedSlider = true;
        maxPrice = parseInt(qsObj.get('pt'));
        searchParams.cnt += 1;
        }

        setTimeout(function(){
        var limitMin = YAHOO.productSlider.getMinValue();
        var limitMax = YAHOO.productSlider.getMaxValue();
        var setLimit = false;
        if(minPrice < limitMin){limitMin = minPrice; setLimit = true;}
        if(minPrice > limitMax){limitMax = minPrice; setLimit = true;}
        if(maxPrice > limitMax){limitMax = maxPrice; setLimit = true;}
        if(maxPrice < limitMin){limitMin = maxPrice; setLimit = true;}
        if(setLimit){YAHOO.productSlider.setLimits(limitMin, limitMax);}
        if(minPrice < maxPrice){YAHOO.productSlider.setValues(minPrice, maxPrice);}
        }, 50);

         */

        // Pulte && DelWebb only
        if (getCurrSite() != "DiVosta") {
            // active adult
            if (qsObj.get('act')) {
                searchParams.ActiveAdult = [];
                if (qsObj.get('act').indexOf(',') > -1) {
                    var vals = qsObj.get('act').split(',');
                    for (var i = 0; i < vals.length; i++) {
                        searchParams.ActiveAdult.push(vals[i]);
                    }
                } else {
                    searchParams.ActiveAdult.push(qsObj.get('act'));
                }
                // set the control to be checked
                SearchControlUtils.setCheckboxRadioControls(productCONFIG.ControlIdName['activeAdult'], fldActiveAdult, searchParams.ActiveAdult);
                searchParams.cnt += 1;
            }
        }
        //alert(location.search.substring(1));alert(qsObj.get('ha')); //?
        // homes available
        if (qsObj.get('ha') && qsObj.get('ha') == '1') {
            //searchParams.HomesAvailableNow = [];
            //if(qsObj.get('ha').indexOf(',') > -1){
            //    var vals = qsObj.get('ha').split(',');
            //    for(var i=0; i < vals.length; i++){
            //        searchParams.HomesAvailableNow.push(vals[i]);
            //    }
            //} else {
            //    searchParams.HomesAvailableNow.push(qsObj.get('ha'));
            //}
            // set the control to be checked
            //SearchControlUtils.setCheckboxRadioControls(productCONFIG.ControlIdName['availableNow'], fldAvailableNow, searchParams.HomesAvailableNow);
            availablehomes = [];
            availablehomes[0] = 1;
            searchParams.HomesAvailableNow = availablehomes;
            MapSearch.toggleLoadingMessage(true);
            Pulte08.AjaxWebServices.MapService.SetParameterHomesAvailableNow(brandIdList, availablehomes, MapSearch.doNothing);
            searchParams.cnt += 1;
        }
        else { // reset the HomesAvailableNow parameter
            availablehomes = [];
            availablehomes[0] = 0;
            searchParams.HomesAvailableNow = availablehomes;
            MapSearch.toggleLoadingMessage(true);
            Pulte08.AjaxWebServices.MapService.SetParameterHomesAvailableNow(brandIdList, availablehomes, MapSearch.doNothing);
            searchParams.cnt += 1;
        }

        // coommunity type (amenity)
        if (qsObj.get('at')) {
            searchParams.CommunityType = [];
            if (qsObj.get('at').indexOf(',') > -1) {
                var vals = qsObj.get('at').split(',');
                for (var i = 0; i < vals.length; i++) {
                    searchParams.CommunityType.push(vals[i]);
                }
            } else {
                searchParams.CommunityType.push(qsObj.get('at'));
            }
            // set the control to be checked
            SearchControlUtils.setCheckboxRadioControls(productCONFIG.ControlIdName['communityType'], fldCommunityType, searchParams.CommunityType);
            searchParams.cnt += 1;
        }

        // (DelWebb Only)
        if (getCurrSite() == "DelWebb") {
            if (qsObj.get('sb')) {
                searchParams.SubBrand = [];
                if (qsObj.get('sb').indexOf(',') > -1) {
                    var vals = qsObj.get('sb').split(',');
                    for (var i = 0; i < vals.length; i++) {
                        searchParams.SubBrand.push(vals[i]);
                    }
                } else {
                    searchParams.SubBrand.push(qsObj.get('sb'));
                }
                // set the control to be checked
                SearchControlUtils.setCheckboxRadioControls(productCONFIG.ControlIdName['subBrand'], fldSubBrand, searchParams.SubBrand);
                searchParams.cnt += 1;
            }
        }

        // State Id or state 2-letter name
        if (qsObj.get('state')) {
            searchParams.State = qsObj.get('state');
            searchParams.cnt += 1;
        }
        // Region id
        if (qsObj.get('region')) {
            searchParams.Region = qsObj.get('region');
            searchParams.cnt += 1;
        }
        // Metro id
        if (qsObj.get('metro')) {
            searchParams.Metro = qsObj.get('metro');
            searchParams.cnt += 1;
        }

        //poi
        if (getCurrSite() == "DiVosta") {
            if (qsObj.get('poi')) {
                searchParams.PointOfInterest = [];
                searchParams.PointOfInterest.push(qsObj.get('poi'));

                SearchControlUtils.setCheckboxRadioControls(productCONFIG.ControlIdName['poi'], fldPOI, searchParams.PointOfInterest);

                setSelectBoxValue(document.getElementById("poi"), searchParams.PointOfInterest);

                searchParams.cnt += 1;
            }
        }
        // Brand id
        if (qsObj.get('brand')) {
            searchParams.BrandId = [];
            var curBrandId = productCONFIG.brandIds[getCurrSite().toLowerCase()];
            // if we have more than 1 brandID param: 1) if curBrand exist, then reset to use only 1 brand, otherwise, use the brands pass in
            if (qsObj.get('brand').indexOf(',') > -1) {
                var vals = qsObj.get('brand').split(',');
                if (isSessionQuery) {
                    var isBrandFound = false;
                    for (var i = 0; i < vals.length; i++) {
                        if (curBrandId == vals[i]) {
                            isBrandFound = true;
                            break;
                        }
                    }
                    if (isBrandFound) { searchParams.BrandId.push(curBrandId); }
                    else { for (var i = 0; i < vals.length; i++) { searchParams.BrandId.push(vals[i]); } }
                    isSessionQuery = false;
                } else {
                    for (var i = 0; i < vals.length; i++) {
                        searchParams.BrandId.push(vals[i]);
                    }
                }

            } else {
                // otherwise, check with current page brandID
                if (isSessionQuery) {
                    searchParams.BrandId.push(curBrandId);
                    isSessionQuery = false;
                } else {
                    searchParams.BrandId.push(qsObj.get('brand'));
                }
            }

            // reset the brandIdList
            brandIdList = [];
            for (var i = 0; i < searchParams.BrandId.length; i++) { brandIdList.push(searchParams.BrandId[i]); }
            searchParams.cnt += 1;
        }
        // Breadcrumb
        if (qsObj.get('bcType')) {
            searchParams.cnt += 1;
        }
        //check if searchParams has no brandId, then get the current brand - else this will throw error from backend
        if (!searchParams.BrandId) {
            brandIdList = [];
            searchParams.BrandId = [];
            brandIdList[0] = productCONFIG.brandIds[getCurrSite().toLowerCase()];
            searchParams.BrandId.push(brandIdList[0]);
        }
        // zip 
        if (qsObj.get('zip')) {
            searchParams.zipCode = qsObj.get('zip');
            searchParams.cnt += 1;
        }
        return searchParams;
    },

    //toggleLodingMessage
    toggleLoadingMessage: function(isShown) {
        var loadObj = document.getElementById('alert');
        if (loadObj) {
            if (isShown) {
                MapSearch.removeExistingMarkers();
                loadObj.style.display = 'block';
            }
            else {
                loadObj.style.display = 'none';
            }
        }
    },

    renderSearchResults: function(searchResultSet) {
        var result = searchResultSet.SearchSummary;
        var planInfo = '';
        var communityInfo = '';
        var table = '';
        var header = '';
        var body = '';
        var footer = '';
        var finalOutput = '';
        var commAnn = '';
        var topPagination = '';
        var bottomPagination = '';
        var communityCountInfo = '';
        var pageBrand;

        pageBrand = getCurrSite().toLowerCase();

        //for paging, display only the first 6 records
        var numRows = 0;
        if (result.length >= 6) numRows = 6;
        else numRows = result.length;

        topPagination = '<p class="pagination"><a href="javascript:MapSearch.getPage(currentPage,1);"><img id="btnFirst1" src="/images/Pulte/button-paginationFastBack.gif" alt="Pagination: Fast Back" /></a><a href="javascript:MapSearch.getPage(currentPage,2);"><img id="btnPrev1" src="/images/Pulte/button-paginationBack.gif" alt="Pagination: Back" /></a><em>';
        bottomPagination = '<p class="pagination"><a href="javascript:MapSearch.getPage(currentPage,1);"><img id="btnFirst2" src="/images/Pulte/button-paginationFastBack.gif" alt="Pagination: Fast Back" /></a><a href="javascript:MapSearch.getPage(currentPage,2);"><img id="btnPrev2" src="/images/Pulte/button-paginationBack.gif" alt="Pagination: Back" /></a><em>';

        if (totalPages > 1) {
            var firstPage;
            var lastPage;

            //set first page number value to be displayed
            if (currentPage > 6) {
                firstPage = currentPage - 5;
            } else {
                firstPage = 1;
            }
            //set last page number value to be displayed
            lastPage = firstPage + 9;

            if (lastPage > totalPages) {
                lastPage = totalPages;
            }
            //always display ten page numbers
            if ((lastPage - firstPage) < 9 && lastPage > 10) {
                firstPage -= (10 - (lastPage - firstPage + 1));
            }
            //sanity check for current page
            if (currentPage > lastPage) {
                currentPage = lastPage;
            }
            setCookie('searchCurrentPage', currentPage, null, "/");
            setCookie('searchPageNumber', totalPages, null, "/");
            //setCookie('searchPageType', pType, null, "/");
            // special treatment for IE6 - force font size for links
            var ie6Style = "";
            var brVer = jQuery.browser.version;

            if (brVer.substr(0, 2) == "6.") ie6Style = 'style="font-size:1.0em;"';

            for (var i = firstPage; i <= lastPage; i++) {
                if (i == currentPage) {
                    topPagination += i + '&nbsp;';
                    bottomPagination += i + '&nbsp;';
                }
                else {
                    topPagination += '<a href="javascript:MapSearch.getPage(' + i + ', 3);" ' + ie6Style + '>' + i + '</a>';
                    bottomPagination += '<a href="javascript:MapSearch.getPage(' + i + ', 3);" ' + ie6Style + '>' + i + '</a>';
                }
            }
        }

        topPagination += '</em><a href="javascript:MapSearch.getPage(currentPage,4);"><img id="btnNext1" src="/images/Pulte/button-paginationForward.gif" alt="Pagination: Forward" /></a><a href="javascript:MapSearch.getPage(currentPage,5);"><img id="btnLast1" src="/images/Pulte/button-paginationFastForward.gif" alt="Pagination: Fast Forward" /></a></p>';
        bottomPagination += '</em><a href="javascript:MapSearch.getPage(currentPage,4);"><img id="btnNext2" src="/images/Pulte/button-paginationForward.gif" alt="Pagination: Forward" /></a><a href="javascript:MapSearch.getPage(currentPage,5);"><img id="btnLast2" src="/images/Pulte/button-paginationFastForward.gif" alt="Pagination: Fast Forward" /></a></p>';
        var commTitle = 'neighborhoods';
        if (getCurrSite().toLowerCase() == 'delwebb') commTitle = 'communities';
        communityCountInfo = '<p class="resultsSummary"><em>' + searchResultSet.PlanCount + ' homes</em> match your search criteria in <em>' + searchResultSet.CommunityCount + ' ' + commTitle + '</em></p>';



        // Set up our GMarkerOptions object
        for (var i = 0; i < numRows; i++) {
            var communityName = result[i].CommunityName;
            var communityId = result[i].CommunityId;
            var city = result[i].City;
            var state = result[i].StateAbbr;
            var sqftmin = result[i].SqftMin;
            var sqftmax = result[i].SqftMax;
            var pricemin = result[i].PriceMin;
            var pricemax = result[i].PriceMax;
            var point = result[i].Point;
            var address1 = result[i].Address1;
            var address2 = result[i].Address2;
            var announcements = result[i].Announcements;
            var commPageURL = result[i].PageURL;
            var commImagePath = result[i].ImagePath;
            var otherBrand = MapSearch.getResultBrand(result[i].BrandId);

            footer = '';
            commAnn = '';
            header = '';

            // master community info
            if (result[i].IsMasterCommunity || otherBrand.toLowerCase() != pageBrand) {
                header = '<div class="searchResultTabs">';
                if (result[i].IsMasterCommunity) {
                    header += '<div class="searchResultTab searchResultTab-' + pageBrand + '"><span><a href="' + result[i].MasterCommunityPageURL + '" target="_blank">' + result[i].MasterCommunityName + '</a></span></div>';
                }
                if (otherBrand.toLowerCase() != pageBrand) {
                    header += '<div class="searchResultTab searchResultTab-' + otherBrand.toLocaleLowerCase() + '"><span><a href="' + MapSearch.getResultBrandURL(result[i].BrandId) + '" target="_blank" class="branded">' + otherBrand + '</a></span></div>';
                }
                header += '<div class="clear"></div></div>';
            }

            header += '<table class="searchResults" summary="Search Result: ' + communityName + '">';
            header += '<thead><tr><td class="srCorners" colspan="3"></td></tr>';
            header += '<tr><td>' + city + ', ' + state;
            var communityHref = '<a href="' + commPageURL + '"' + '>' + communityName + '</a>';
            var saveToNoteBookHref = '<div><a href="' + 'javascript:void(\'\');" onclick="NotebookUtils.saveCommunityToNotebook(' + communityId + ', this, \'srMyNotebookYes\');"' + ' class=' + '"' + 'srMyNotebookNo' + '"' + '><img src="/images/' + getCurrSite() + '/button-saveToNotebook.gif" alt="Save to Notebook"></a></div>';
            var contactUsHref = '<div><a href="' + urlSiteBase + '/customer-service/contact-us.aspx?communityid=' + communityId + '&pagetitle=Search%20Results' + '"' + ' class="srContact"><img src="/images/' + getCurrSite() + '/button-requestInfo.gif" alt="Request Info About This Neighborhood"></a></div>';
            header += '<h2>' + communityHref + '</h2></td>';



            body = '<tbody><tr><td class="srSummary"><dl><dt>' + '<a href="' + commPageURL + '"' + '>' + '<img alt="' + communityName + '" src="' + commImagePath + '"></a></dt>';
            body += '<dd><em>' + result[i].PhoneNumber + '</em><br />';
            body += address1 + '<br />' + city + ', ' + state + '<br />';

            // do not display maps and directions for coming soon community
            if (result[i].ComingSoonFlag) {
                body += '</dd></dl></td>';
            } else {
                body += '<br /><a href="' + commPageURL + '?selected=directions"' + '>Maps and Directions</a><br />' + '</dd></dl></td>';
            }

            // if pulte display plan info otherwise display overview
            if (otherBrand.toLowerCase() == "pulte") {
                // pulte header
                header += '<td class="srListingsHdr"><span>Starting at:</span>' + 'Plan Models' + '</td>'
                header += '<td>Next Steps</td></tr></thead>';
                var plans = result[i].Plans;
                if (plans != null && plans.length > 0) {
                    planInfo = '<td class="srListings">';
                    var planLen = plans.length;
                    for (var k = 0; k < planLen; k++) {
                        var planHref = '<a href="' + plans[k].PageURL + '"' + '>' + plans[k].Name + '</a>';
                        var numHalfBaths = plans[k].NumHalfBathrooms;
                        var bathString = '';
                        if (numHalfBaths == 1) {
                            bathString = plans[k].NumFullBathrooms + '.5';
                        }
                        else if (numHalfBaths > 1) {
                            bathString = plans[k].NumFullBathrooms + '.5 +';
                        }
                        else {
                            bathString = plans[k].NumFullBathrooms;
                        }

                        var t = '<div><span>' + ((parseInt(plans[k].Price) < 1) ? 'TBD' : '$' + StringUtils.addCommas(plans[k].Price)) + '</span><em>' + plans[k].NumBedrooms + ' bed / ' + bathString + ' bath / ' + plans[k].Sqft + ' Sq ft ' + '</em>' + planHref + '</div>';
                        planInfo += t;

                    }
                    planInfo += '<p><a href="' + commPageURL + '?selected=overview"' + '>View All Home Models</a></p></td>';
                }
                else
                    planInfo = '<td class="srListings"></td>';

            } else {
                // calculate the lowest plan price
                var plans = result[i].Plans;
                var planPrice = -1;
                var curPrice;
                if (plans != null && plans.length > 0) {
                    var planLen = plans.length;
                    for (var k = 0; k < planLen; k++) {
                        curPrice = parseInt(plans[k].Price);
                        if (planPrice == -1) {
                            planPrice = (curPrice > 0) ? curPrice : planPrice;
                        } else {
                            planPrice = Math.min(planPrice, curPrice);
                        }
                    }

                }
                // DelWebb and Divosta Header
                header += '<td class="srListingsHdr"><span>Starting at: ' + ((planPrice > 0) ? ('$' + StringUtils.addCommas(planPrice)) : 'TBD') + '</span></td>';
                header += '<td>Next Steps</td></tr></thead>';
                planInfo = '<td class="srListings">' + MapSearch.removeHtmlTags(result[i].Overview) + '<br /><a href="' + commPageURL + '">[more...]</a>';

                var ComingSoonFlag = result[i].ComingSoonFlag;

                if (!ComingSoonFlag) {
                    planInfo += '<p><span><a href="' + commPageURL + '?selected=amenities">Community Amenities</a></span>';
                }

                else { planInfo += '<p>'; }

                if (plans != null && plans.length > 0) {
                    planInfo += '<a href="' + commPageURL + '?selected=overview">View Floor Plans</a></p>' + '</td>';
                }

                else {
                    planInfo += '</p>' + '</td>';
                }

                // DelWebb & Divosta overview info
            }

            if (announcements != null && announcements.length > 0) {
                commAnn += '<td class="srExtras">';
                commAnn += contactUsHref;
                commAnn += saveToNoteBookHref;
                commAnn += '<ul>';
                for (var s = 0; s < announcements.length; s++) {
                    commAnn += '<li>' + announcements[s].AnnouncementType + '</li>';
                }
                commAnn += '</ul></td>';
            }
            else
                commAnn = '<td class="srExtras">' + contactUsHref + saveToNoteBookHref + '</td>'

            footer += commAnn;
            footer += '</tr></tbody></table>';
            finalOutput += header + body + planInfo + footer;
        }

        if (fldAvailableNow.checked) {
            document.getElementById('availablebounds').innerHTML = topPagination + communityCountInfo + finalOutput + bottomPagination + "<div style='line-height:0px; width:100%'/>";
        }
        else {
            document.getElementById('bounds').innerHTML = topPagination + communityCountInfo + finalOutput + bottomPagination + "<div style='line-height:0px; width:100%'/>";
        }
        MapSearch.enablePagingControls();
        renderSearchResultsCorners();
        highlightTableRows();
        window.setTimeout(function() { isSearchEnabled = true; }, 1000);
    },

    // get page function
    getPage: function(pageNumber, pType) {
        var pageType;
        switch (pType) {
            case 1: pageType = 'first';
                currentPage = 1;
                break;
            case 2: pageType = 'prev';
                currentPage--;
                break;
            case 3: pageType = 'page';
                currentPage = pageNumber;
                break;
            case 4: pageType = 'next';
                currentPage++;
                break;
            case 5: pageType = 'last';
                currentPage = totalPages;
                break;
            default: pageType = 'page';
                currentPage = pageNumber;
                pType = 3;
        }
        //setCookie('searchCurrentPage', currentPage, null, "/");
        //setCookie('searchPageNumber', pageNumber, null, "/");
        setCookie('searchPageType', pType, null, "/");
        Pulte08.AjaxWebServices.MapService.PagingSearch(pageNumber, pageType, MapSearch.pagingSearch);
    },

    pagingSearch: function(pageResult) {

        if (pageResult == null) {
            //SearchControlUtils.updateSearchLink(0,0);
            var finalOutput = '<h4 class="noResults">We were not able to find any communities that matched your preferences.   Please change your search parameters and try again.</h4><br />';
            $get('bounds').innerHTML = finalOutput;

            var nePoint = map.getBounds().getNorthEast();
            var swPoint = map.getBounds().getSouthWest();

            var nwPoint = new GLatLng(swPoint.lat(), nePoint.lng());
            var sePoint = new GLatLng(nePoint.lat(), swPoint.lng());

            var nePointsDistInMiles = (nePoint.distanceFrom(nwPoint)) / 1609.3;
            var swPointDistInMiles = (sePoint.distanceFrom(swPoint)) / 1609.3;

            return;
        }

        MapSearch.renderSearchResults(pageResult);
        window.location.href = "#content";
    },

    // enablePagingControls
    enablePagingControls: function() {
        var first = document.getElementById('btnFirst1');
        var prev = document.getElementById('btnPrev1');
        var next = document.getElementById('btnNext1');
        var last = document.getElementById('btnLast1');

        var firstBtm = document.getElementById('btnFirst2');
        var prevBtm = document.getElementById('btnPrev2');
        var nextBtm = document.getElementById('btnNext2');
        var lastBtm = document.getElementById('btnLast2');

        if (currentPage == 1)//this is the first page
        {
            first.style.display = 'none';
            firstBtm.style.display = 'none';

            prev.style.display = 'none';
            prevBtm.style.display = 'none';

            if (currentPage != totalPages)//checking if result has only 1 page
            {
                next.style.display = '';
                nextBtm.style.display = '';

                last.style.display = '';
                lastBtm.style.display = '';
            }
            else {
                next.style.display = 'none';
                nextBtm.style.display = 'none';

                last.style.display = 'none';
                lastBtm.style.display = 'none';
            }
        }
        else {
            if (currentPage == totalPages)//this is the last page
            {
                next.style.display = 'none';
                nextBtm.style.display = 'none';

                last.style.display = 'none';
                lastBtm.style.display = 'none';

                prev.style.display = '';
                prevBtm.style.display = '';

                first.style.display = '';
                firstBtm.style.display = '';
            }
            else {
                next.style.display = '';
                nextBtm.style.display = '';

                last.style.display = '';
                lastBtm.style.display = '';

                prev.style.display = '';
                prevBtm.style.display = '';

                first.style.display = '';
                firstBtm.style.display = '';
            }
        }
    },

    // buildChildList
    buildChildList: function(taxonomy, type) {
        var tempList = [];
        var cNode;
        if (taxonomy) {
            for (var i = 0; i < taxonomy.length; i++) {
                var tempId;
                if (type == 'region') {
                    tempId = 'region' + taxonomy[i].RegionId;
                    cNode = { name: taxonomy[i].RegionName, id: taxonomy[i].RegionId, idType: 'region', communities: taxonomy[i].CommunityCount };
                } else {
                    tempId = 'metro' + taxonomy[i].MetroId;
                    cNode = { name: taxonomy[i].MetroName, id: taxonomy[i].MetroId, idType: 'metro', communities: taxonomy[i].CommunityCount };
                }

                tempList.push(cNode);
            }
        }

        return tempList;
    },

    // remove p tag from community overView
    removeHtmlTags: function(targetTxt) {
        var strInputCode = targetTxt.replace(/&(lt|gt);/g, function(strMatch, p1) {
            return (p1 == "lt") ? "<" : ">";
        });
        return strInputCode.replace(/<\/?[^>]+(>|$)/g, "");
    }
};

// ----------------------------------------------------------------------------------------------

// CLOSE SEARCH OVERLAY

YUE.on(document, 'click', function(e) {
    if (YUD.getElementsByClassName('overlayClose').length > 0) {
        if (!YUD.getAncestorByClassName(YUE.getTarget(e), 'overlayWrapper') || YUE.getTarget(e).id == 'overlayClose') YUD.getElementsByClassName('overlayClose')[0].style.visibility = 'hidden'
    }
});

// ----------------------------------------------------------------------------------------------

// INTERNAL POP-UP

YUE.onAvailable('internalPopUpContainer', function() {

    var trigger = document.getElementById('internalPopUpTrigger');
    var target = document.getElementById('internalPopUpTarget');
    var close = document.getElementById('internalPopUpClose');

    YUE.on(trigger, 'click', function() { YUD.setStyle(target, 'display', 'block') });
    YUE.on(close, 'click', function() { YUD.setStyle(target, 'display', 'none') });

});

// ----------------------------------------------------------------------------------------------


function OpenZipSearch() {
    var zipSearch = document.getElementById("zipSearch");
    if (zipSearch != null) {
        if ((zipSearch.value != "") && (!isNaN(zipSearch.value))) {
            zipSearched = zipSearch.value; // set global variable
            var zipValue = zipSearch.value;
            var ret = findZip(zipValue);
        }
    }
}

function SetOrderBy(columnName) {
    Pulte08.AjaxWebServices.MapService.OrderBy(columnName, MapSearch.newBounds);
}