﻿/// <reference path="Utilities.js" />
/// <reference path="MapFunctions.js" />
/// <reference path="SearchResults.js" />
/// <reference path="SearchSitesResultsBuilder.js" />
/// <reference path="CommunitySearchSitesResultsBuilder.js" />


var _SSR = new GISPlanning_SearchResults();
var _PropertySearchResultBuilder = new GISP_PropertySearchResultBuilder();
var _CommunitySearchResultBuilder = new GISP_CommunitySearchResultBuilder();
var _BusinessSearchResultBuilder = new GISP_BusinessSearchResultBuilder();
var _ReportResultBuilder = new GISP_ReportResultBuilder();
var _SearchParams = { SITES: null, BUILDINGS: null, COMMUNITIES: null, BUSINESSES: null };
var _SearchReseters = { SITES: [], BUILDINGS: [], COMMUNITIES: [], BUSINESSES: [] };
var _SearchScope = { GeoEntityList: [], BrokerID: null }; //+91CBF7A5-0DEC-4E70-B04F-4C27EFDA1690(Hartford as an example, Broker 796
var _ReportLoader = new ReportLoaderQueue();
var _IsInitialFeaturedSearch = true; //this is used to let the results manager know to not zoom the map to the results
var _searchWindow = new SearchWindow();

function ReportLoaderQueue() {
    this._items = [];
    this.IsProcessing = false;
    this.QueueRequest = function (pID, pType, pUnique) {
        this._items.push({ PropertyID: pID, ReportType: pType, UniqueID: pUnique });
    };
    this.ProcessNext = function (pUniqueID) {
        if (this._items.length > 0) {
            this.IsProcessing = true;
            var nextRequest = this._items.pop();
            // Why are we doing an eval here?
            var sCall = 'LoadSubReport(\'' + nextRequest.PropertyID + '\', \'' + nextRequest.ReportType + '\', \'' + nextRequest.UniqueID + '\', false)';
            eval(sCall);
        }
        else {
            this.IsProcessing = false;
        }
    };
    this.DiscardAllPendingExcept = function (pReportIdToKeep) {
        while (this._items.length > 0 && this._items[0].UniqueID != pReportIdToKeep) {
            this._items.shift();
        }
    };
    this.HasItems = function () { return (this._items.length > 0); };
}


function GetNewSearchParams(pWhatType) {
    var myParams = null;
    switch (pWhatType) {
        case "BUILDINGS":
            myParams = {
                SearchType: pWhatType,
                PropertyID: null,
                BrokerID: null,
                ExternalID: null,
                PropertyType: "",
                MinSize: null,
                MaxSize: null,
                GeoEntityList: "",
                RegionsList: "",
                Attributes: "",
                Address: null,
                IsBuilding: true,
                PolyPoints: "",
                SessionID: _JavascriptSessionID,
                SubsetToken: _GISP_Theme,
                StartRowID: -1,
                EndRowID: -1,
                SortBy: "default",
                SortDirection: true,
                RequestID: GISPlanning_MapUtilities_GUID(),
                InputParameters: null
            };
            break;
        case "SITES":
            myParams = {
                SearchType: pWhatType,
                PropertyID: null,
                BrokerID: null,
                ExternalID: null,
                PropertyType: "",
                MinSize: null,
                MaxSize: null,
                GeoEntityList: "",
                RegionsList: "",
                Attributes: "",
                Address: null,
                IsBuilding: false,
                PolyPoints: "",
                SessionID: _JavascriptSessionID,
                SubsetToken: _GISP_Theme,
                StartRowID: -1,
                EndRowID: -1,
                SortBy: "default",
                SortDirection: true,
                RequestID: GISPlanning_MapUtilities_GUID(),
                InputParameters: null
            };
            break;
        case "BUSINESSES":
            myParams = {
                Radius: -1, //Not used in this search
                Lat: map.getCenter().lat(),
                Lng: map.getCenter().lng(),
                NAICS_Classes: "",
                NAICS_Codes: "",
                Clusters: "",
                Name: "",
                Address: "",
                RevenueMin: "",
                RevenueMax: "",
                EmployeesMin: "",
                EmployeesMax: "",
                PolyAreaPoints: "",
                GeoEntities: "",
                StartRowID: 0,
                EndRowID: CalcCurrentPageSizeBasedOnClientWidth(),
                SortBy: "",
                YearsMin: "",
                YearsMax: "",
                BusinessTypes: "",
                LifeCycleTypes: "",
                SubsetToken: _GISP_Theme,
                RequestID: GISPlanning_MapUtilities_GUID(),
                SessionID: _JavascriptSessionID
            };
            break;
        default:
            myParams = {};
            break;
    } //end case


    return myParams;
} //end function
function DisplaySiteSearchWhenLoaded() {
    if (_searchWindow == null) {
        setTimeout(function () { DisplaySiteSearchWhenLoaded(); }, GISP_TIME_TO_WAIT_WHEN_CHECKING_LOAD_OF_SCRIPT);
    }
    else {
        DisplaySearch(false, "sites");
    }
}
function DisplayBuildingSearchWhenLoaded() {
    if (_searchWindow == null) {
        setTimeout(function () { DisplayBuildingSearchWhenLoaded(); }, GISP_TIME_TO_WAIT_WHEN_CHECKING_LOAD_OF_SCRIPT);
    }
    else {
        DisplaySearch(false, "buildings");
    }
}
function DisplayCommmunitySearchWhenLoaded() {
    if (_searchWindow == null) {
        setTimeout(function () { DisplayCommmunitySearchWhenLoaded(); }, GISP_TIME_TO_WAIT_WHEN_CHECKING_LOAD_OF_SCRIPT);
    }
    else {
        DisplaySearch(false, "communities");
    }
}
function DisplayBusinessSearchWhenLoaded() {
    if (_searchWindow == null) {
        setTimeout(function () { DisplayBusinessSearchWhenLoaded(); }, GISP_TIME_TO_WAIT_WHEN_CHECKING_LOAD_OF_SCRIPT);
    }
    else {
        DisplaySearch(false, "businesses");
    }
}



function DisplayCommunityPropertyListingWhenLoaded(pGID, pListingType) {
    if (_searchWindow == null) {
        setTimeout(function () { DisplayCommunityPropertyListingWhenLoaded(pGID, pListingType); }, GISP_TIME_TO_WAIT_WHEN_CHECKING_LOAD_OF_SCRIPT);
    } else {
        var searchType = pListingType == 'B' ? 'BUILDINGS' : 'SITES';
        _SearchScope.GeoEntityList.push('+' + pGID);
        _SSR._CurrentViewType = searchType;
        DoSiteSearch(searchType);
    } //end ifelse found
}

function DisplayBrokerPropertyListingWhenLoaded(pBID, pListingType) {
    if (_searchWindow == null) {
        setTimeout(function () { DisplayBrokerPropertyListingWhenLoaded(pBID, pListingType); }, GISP_TIME_TO_WAIT_WHEN_CHECKING_LOAD_OF_SCRIPT);
    } else {
        var searchType = pListingType == 'B' ? 'BUILDINGS' : 'SITES';
        $("#brokerID_" + searchType.toLowerCase()).val(pBID);
        _SearchScope.BrokerID = pBID;
        _SSR._CurrentViewType = searchType;
        DoSiteSearch(searchType);
        _SearchScope.BrokerID = null;
    } //end ifelse found
}

function DisplaySearch(pIsRefinement, pWhatSearch) {
    if (!pIsRefinement) {
        _searchWindow.Reset();
    } //end if not refining
    //call the search, including the appopriate type
    _SSR._CurrentViewType = pWhatSearch.toUpperCase();
    ShowSearch(pWhatSearch);
} //end function


function DoSiteSearch(pType) {
    _SSR.ClearCurrentReportOverlays();
    _SSR.ClearOtherReportOverlays();
    HideSearch();

    ShowExternalContentInModal("/fragments/modal/loading.htm");
    var myTracker = _SSR._Trackers[pType];
    var myResultOrientation = myTracker.ResultOrientation;

    var myCurrentPageSize = (myResultOrientation == "vertical") ? CalcCurrentPageSizeBasedOnClientWidth() : _SSR._PageSizeDEFAULT;
    _SSR._SetPageSize(myCurrentPageSize, pType);

    var mySearchParams = GetSearchParameters(pType);
    mySearchParams.StartRowID = 0;
    mySearchParams.EndRowID = myCurrentPageSize;

    _SSR._CurrentViewClass = "RESULTS";

    switch (pType) {
        case "BUILDINGS": CallBuildingSearchService(mySearchParams, { successCallback: SearchSuccess, failureCallback: SearchFail }); break;
        case "SITES": CallSiteSearchService(mySearchParams, { successCallback: SearchSuccess, failureCallback: SearchFail }); break;
        case "BUSINESSES": alert("not implemented yet"); break;
        case "COMMUNITIES": CallCommunitySearchService(mySearchParams, { successCallback: SearchSuccess, failureCallback: SearchFail }); break;
        default: break;
    } //end switch

} //end function


function DoShowcaseSearch(pType, pAttributes) {
    var myCurrentPageSize = CalcCurrentPageSizeBasedOnClientWidth();
    _SSR._SetPageSize(myCurrentPageSize, pType);
    var myParams = GetNewSearchParams(pType);

    switch (pType) {
        case "BUILDINGS":
            myParams.Attributes = pAttributes;
            myParams.StartRowID = 0;
            myParams.EndRowID = myCurrentPageSize;
            myParams.SubsetToken = _GISP_Theme;
            myParams.SortBy = "random";
            myParams.SortDirection = false;
            myParams.RequestID = GISPlanning_MapUtilities_GUID();
            CallBuildingSearchService(myParams, { successCallback: SearchSuccess, failureCallback: SearchFail });
            break;
        case "SITES":
            myParams.Attributes = pAttributes;
            myParams.StartRowID = 0;
            myParams.EndRowID = myCurrentPageSize;
            myParams.SubsetToken = _GISP_Theme;
            myParams.SortBy = "random";
            myParams.SortDirection = false;
            myParams.RequestID = GISPlanning_MapUtilities_GUID();
            CallSiteSearchService(myParams, { successCallback: SearchSuccess, failureCallback: SearchFail });
            break;
        case "BUSINESSES":
            myParams.StartRowID = 0;
            myParams.EndRowID = myCurrentPageSize;
            myParams.SubsetToken = _GISP_Theme;
            myParams.SortBy = "default";
            myParams.SortDirection = false;
            myParams.RequestID = GISPlanning_MapUtilities_GUID();
            CallBusinessSearchService(myParams, { successCallback: SearchSuccess, failureCallback: SearchFail });
            break;
        case "COMMUNITIES":
            myParams.StartRowID = 0;
            myParams.EndRowID = myCurrentPageSize;
            myParams.SubsetToken = _GISP_Theme;
            myParams.SortBy = "default";
            myParams.SortDirection = false;
            myParams.RequestID = GISPlanning_MapUtilities_GUID();
            CallCommunitySearchService(myParams, { successCallback: SearchSuccess, failureCallback: SearchFail });
            break;
        default:
            myParams = {};
            break;
    } //end swtich
} //end function

function CalcCurrentPageSizeBasedOnClientWidth() {
    //get the client, width, subtract the margin and return integer part of width/listing width
    var myWidth = GetClientWidth() - GISP_PROPERTY_CONTAINER_MARGIN;
    return parseInt(myWidth / GISP_PROPERTY_WIDTH, 10);
} //end function

function OrderData(pType, pParams, pSuccessCallback, pFailCallback) {
    log.info("OrderData() Type: " + pType + " Params: " + pParams);
    switch (pType) {
        case "SITES":
            CallSiteSearchService(pParams, { successCallback: pSuccessCallback, failureCallback: pFailCallback, updateUI: false });
            break;
        case "COMMUNITIES":
            CallCommunitySearchService(pParams, { successCallback: pSuccessCallback, failureCallback: pFailCallback, updateUI: false });
            break;
        case "BUSINESSES":
            CallBusinessSearchService(pParams, { successCallback: pSuccessCallback, failureCallback: pFailCallback, updateUI: false });
            break;
        case "BUILDINGS":
        default:
            CallBuildingSearchService(pParams, { successCallback: pSuccessCallback, failureCallback: pFailCallback, updateUI: false });
            break;
    } //end function
} //end function


function CallBuildingSearchService(pSearchParams, pOptions) {
    var myOptions = $.extend({ updateUI: true, retryCount: 0 }, pOptions);

    pSearchParams.IsBuilding = true;
    pSearchParams.MinSize = SanitizeNumber(pSearchParams.MinSize);
    pSearchParams.MaxSize = SanitizeNumber(pSearchParams.MaxSize);
    // TODO: Change to $.ajax()
    log.info("Calling search service");

    var myTimeoutRetry = function () {
        myOptions.retryCount++;
        if (myOptions.retryCount < 4) {
            CallBuildingSearchService(pSearchParams, myOptions);
        } else {
            alert("Search Timed Out, Please try again");
            HideLoadingScreen();
            _searchWindow.Hide();
        }
    }

    $.ajax({
        type: "POST",
        dataType: "json",
        contentType: "application/json; charset=utf-8",
        url: "/common/services/Properties.asmx/GetProperties",
        data: JSON.stringify({ pParams: pSearchParams }),
        timeout: 8000,
        success: function (data, text) {
            log.info("Search success");
            myOptions.successCallback(data.d);
        },
        error: function (xhr, text, error) {
            log.warn("Search failure text: " + text);
            log.warn("Search failure request: " + xhr);
            log.warn("Search failure error: " + error);
            if (text == "timeout") {
                log.info("Retrying search...");
                myTimeoutRetry();
            } else {
                if (xhr.responseText !== undefined && xhr.responseText.length > 0) {
                    var responseData = JSON.parse(xhr.responseText);
                    responseData._message = responseData.Message;
                    SearchFail(responseData);
                }
                if (myOptions.failureCallback !== undefined) {
                    myOptions.failureCallback(xhr);
                }

                if (myOptions.updateUI) {
                    HideLoadingScreen();
                    //todo: show error
                    _searchWindow.Hide();
                } //end if updating UI
            } //end if not timeout
        }
    });
}

function CallSiteSearchService(pSearchParams, pOptions) {
    var myOptions = $.extend({ updateUI: true, retryCount: 0 }, pOptions);

    pSearchParams.IsBuilding = false;
    pSearchParams.MinSize = SanitizeNumber(pSearchParams.MinSize);
    pSearchParams.MaxSize = SanitizeNumber(pSearchParams.MaxSize);


    var myTimeoutRetry = function () {
        myOptions.retryCount++;
        if (myOptions.retryCount < 4) {
            CallSiteSearchService(pSearchParams, myOptions);
        } else {
            alert("Search Timed Out, Please try again");
            HideLoadingScreen();
            _searchWindow.Hide();
        }
    }

    $.ajax({
        type: "POST",
        dataType: "json",
        contentType: "application/json; charset=utf-8",
        url: "/common/services/Properties.asmx/GetProperties",
        data: JSON.stringify({ pParams: pSearchParams }),
        timeout: 8000,
        success: function (data, text) {
            myOptions.successCallback(data.d);
        },
        error: function (xhr, text, error) {
            log.warn("Search failure text: " + text);
            log.warn("Search failure request: " + xhr);
            log.warn("Search failure error: " + error);
            if (text == "timeout") {
                log.info("Retrying search...");
                myTimeoutRetry();
            } else {
                if (xhr.responseText !== undefined && xhr.responseText.length > 0) {
                    var responseData = JSON.parse(xhr.responseText);
                    responseData._message = responseData.Message;
                    SearchFail(responseData);
                }
                if (myOptions.failureCallback !== undefined) {
                    myOptions.failureCallback(xhr);
                }

                if (myOptions.updateUI) {
                    HideLoadingScreen();
                    //todo: show error
                    _searchWindow.Hide();
                } //end if updating UI
            } //end if not timeout
        }
    });
}

function CallBusinessSearchService(pSearchParams, pOptions) {
    var myOptions = $.extend({ updateUI: true, retryCount: 0 }, pOptions);


    //Because this JSON stuff is very picky, we beed to make sure the search params dont have the __type property
    //this happens on subsequent seraches.
    if (pSearchParams.__type != undefined) {
        delete pSearchParams.__type;
    }

    //Create an object suitable for jsonification
    var myNewParams = { pParams: {} };
    for (var i in pSearchParams) {
        myNewParams.pParams[i] = pSearchParams[i];
    }

    //this callback calls itself in the event of a timeout
    var myTimeoutRetry = function () {
        myOptions.retryCount++;
        if (myOptions.retryCount < 4) {
            CallBusinessSearchService(pSearchParams, myOptions);
        } else {
            alert("Search Timed Out, Please try again");
            HideLoadingScreen();
            _searchWindow.Hide();
        }
    }

    $.ajax({
        async: true,
        cache: true,
        contentType: "application/json; charset=utf-8",
        data: JSON.stringify(myNewParams),
        dataType: "json",
        timeout: 15000,
        error: function (xhr, text, error) {
            log.warn("Search failure text: " + text);
            log.warn("Search failure request: " + xhr);
            log.warn("Search failure error: " + error);
            if (text == "timeout") {
                log.info("Retrying search...");
                myTimeoutRetry();
            } else {
                if (xhr.responseText !== undefined && xhr.responseText.length > 0) {
                    var responseData = JSON.parse(xhr.responseText);
                    responseData._message = responseData.Message;
                    SearchFail(responseData);
                }
                if (myOptions.failureCallback !== undefined) {
                    myOptions.failureCallback(xhr);
                }

                if (myOptions.updateUI) {
                    HideLoadingScreen();
                    //todo: show error
                    _searchWindow.Hide();
                } //end if updating UI
            } //end if not timeout
        },
        success: function (data, textStatus) {
            //remove the __type property apeneded by ASPNET
            for (var i = 0; i < data.d.Results.length; i++) {
                delete data.d.Results[i].__type;
            }

            if (myOptions.successCallback !== undefined) {
                myOptions.successCallback(data.d); //remove this pesky attribute that causes seralization failure when present
            }



            if (_businessMapClickHandlers["BUSINESS_SEARCH"] === undefined || _businessMapClickHandlers["BUSINESS_SEARCH"] === null) {
                _businessMapClickHandlers["BUSINESS_SEARCH"] = HandleBusinessSearchMapClicksCallback;
            }
            _currentBusinessMapClickHander = "BUSINESS_SEARCH";
            _currentBusinessMapRequestID = myNewParams.pParams.RequestID;

            //update the ui (this is not done on an order data situation as it could be happening in the background
            //while the user has started doing another search and this would close the window.
            if (myOptions.updateUI) {
                ShowBusinessMapTileLayer(myNewParams.pParams.RequestID);
                HideLoadingScreen();
                _searchWindow.Hide();
            } //and if updating UI

        },
        type: "POST",
        url: "/common/services/Business.asmx/GetBusinesses"
    });
}


function HandleBusinessSearchMapClicksCallback(pMessageData) {
    var myGetBizInfoCallback = function (pMessage) {
        var myBizResult = pMessage.d;



        _SSR._AddResult(myBizResult, "BUSINESSES");
        var myMarker = _BusinessSearchResultBuilder.CreateMarker(myBizResult, "BUSINESSES");

        _infoWindow.open(map, myMarker);
        _infoWindow.setContent(myMarker.HTML);
        _propertyMarkers.push(myMarker);
    };


    if (pMessageData.BIN !== null) {
        GetBusinessInformation(pMessageData.BIN, myGetBizInfoCallback, null);
    } //end if BIN found
} //end function

function CallCommunitySearchService(pSearchParams, pOptions) {

    //Because this JSON stuff is very picky, we beed to make sure the search params dont have the __type property
    //this happens on subsequent seraches.
    if (pSearchParams.__type != undefined) {
        delete pSearchParams.__type;
    }

    var myOptions = $.extend({ updateUI: true, retryCount: 0 }, pOptions);

    //Create an object suitable for jsonification
    var myNewParams = { pParams: {} };
    for (var i in pSearchParams) {
        myNewParams.pParams[i] = pSearchParams[i];
    }


    //this callback calls itself in the event of a timeout
    var myTimeoutRetry = function () {
        myOptions.retryCount++;
        if (myOptions.retryCount < 4) {
            CallCommunitySearchService(pSearchParams, myOptions);
        } else {
            alert("Search Timed Out, Please try again");
            HideLoadingScreen();
            _searchWindow.Hide();
        }
    }


    $.ajax({
        async: true,
        cache: true,
        contentType: "application/json; charset=utf-8",
        data: JSON.stringify(myNewParams),
        dataType: "json",
        timeout: 8000,
        error: function (xhr, text, error) {
            log.warn("Search failure text: " + text);
            log.warn("Search failure request: " + xhr);
            log.warn("Search failure error: " + error);
            if (text == "timeout") {
                log.info("Retrying search...");
                myTimeoutRetry();
            } else {
                if (xhr.responseText !== undefined && xhr.responseText.length > 0) {
                    var responseData = JSON.parse(xhr.responseText);
                    responseData._message = responseData.Message;
                    SearchFail(responseData);
                }
                if (myOptions.failureCallback !== undefined) {
                    myOptions.failureCallback(xhr);
                }

                if (myOptions.updateUI) {
                    HideLoadingScreen();
                    //todo: show error
                    _searchWindow.Hide();
                } //end if updating UI
            } //end if not timeout
        },
        success: function (data, textStatus) {

            if (typeof (myOptions.successCallback) === "function") {
                myOptions.successCallback(data.d);
            }

            if (myOptions.updateUI) {
                HideLoadingScreen();
                _searchWindow.Hide();
            } //end if updateUI
        },
        type: "POST",
        url: "/common/services/Community.asmx/GetCommunities"
    });
} //end function



function GetSearchParameters(pType) {
    var mySearchParams;

    if (pType == "BUILDINGS" || pType == "SITES") {
        var mySize = GetSizeFromSearchForm(pType);
        var myTypes = GetPropertyTypesFromSearchForm(pType);
        var myAttributes = GetPropertyAttributesFromSearchForm(pType);

        mySearchParams = GetNewSearchParams(pType);
        mySearchParams.PropertyType = myTypes;
        mySearchParams.PolyPoints = $("#hfldPolyPoints").val();
        mySearchParams.Attributes = myAttributes;
        mySearchParams.Address = GetAddressFromSearchForm(pType);
        mySearchParams.ExternalID = GetPropertyIdFromSearchForm(pType);
        mySearchParams.BrokerID = GetBrokerIdFromSearchForm(pType);
        mySearchParams.MinSize = mySize.Min;
        mySearchParams.MaxSize = mySize.Max;
        mySearchParams.GeoEntityList = GetSelectedGeoEntities(pType);
        mySearchParams.RegionsList = GetSelectedRegions(pType);
        mySearchParams.PropertyID = GetPropertyIdFromSearchForm(pType);
    } //end if building or sites

    if (mySearchParams.PolyPoints === null || mySearchParams.PolyPoints.length === 0) {
        RemovePoly();
    }

    if (pType == "BUSINESSES") {
        alert("not implemented yet");
    }

    if (pType == "COMMUNITIES") {
        alert("not implemented yet");
    }

    mySearchParams.SubsetToken = _GISP_Theme;
    mySearchParams.SortBy = _SSR._GetSortBy(pType);
    mySearchParams.SortDirection = false;
    mySearchParams.RequestID = GISPlanning_MapUtilities_GUID();

    return mySearchParams;
} //end function

function GetBuildingSearchDisplayParams(pType) {
    var mySeachParams = GetSearchParameters(pType);

    var myDisplayParams = {
        Property_Type: mySeachParams.PropertyType,
        Minimum_Size: (mySeachParams.MinSize && mySeachParams.MinSize > 0 ? mySeachParams.MinSize : null),
        Maximum_Size: (mySeachParams.MaxSize && mySeachParams.MaxSize > 0 ? mySeachParams.MaxSize : null),
        Area_Filter: (mySeachParams.PolyPoints !== "" ? "Polygon Area Selected" : null),
        Address: mySeachParams.Address
    };
    return myDisplayParams;
} //end funciton

function AddPersistantPolygonInidicatingSearchArea() {
    var $hiddenPolyPoints = $("#hfldPolyPoints");
    var myLatLngs = $hiddenPolyPoints[0].value.split(',');
    var latlngs = [];
    for (i = 0; i < myLatLngs.length; i++) {
        var point = myLatLngs[i];
        var myLatLng = point.split(':');
        latlngs.push(new google.maps.LatLng(myLatLng[0], myLatLng[1]));
    } //end for each point
    $hiddenPolyPoints.data("latlngs", latlngs);
    //create the polygon and add it to the map
    _GISP_Filtering_Poly_Overlay = new google.maps.Polygon({ map: map, path: latlngs, strokeColor: "#7d0e01", strokeWidth: 3, strokeOpacity: 0.8, fillColor: "#7d0e01", fillOpacity: 0.05, clickable: false });

}

function ModifyPoly() {
    alert("Not implemented yet");
} //end function

function RemovePoly() {
    //reset the hidden field
    $("#hfldPolyPoints").val("");
    //update UI

    //remove overlay from map
    if (_GISP_Filtering_Poly_Overlay !== null) {
        try {
            _GISP_Filtering_Poly_Overlay.setMap(null);
            _GISP_Filtering_Poly_Overlay = null;
        }
        catch (exception) {
            // map did not have overlay _GISP_Filtering_Poly_Overlay
        }
    } //end if poly exists
} //end function

function StartPoly() {
    $find("mpeSearch").hide();
    _mapBar.FunctionControl().ActivateFunction(null, null, { ControlID: "POLY" });
} //end function

function ConvertToSqFt(pAcres) {
    return Math.round(pAcres * 43560);
}

function ConvertToSqFtIfNecessary(pSqFt, pWhatSearch) {
    if (/[^0-9\.]/.test(pSqFt)) {
        return null;
    }
    if (pWhatSearch == "SITES") {
        return ConvertToSqFt(pSqFt);
    }
    else {
        return pSqFt;
    }
}
function GetPropertyTypesFromSearchForm(pWhatSearch) {
    var categoryClass = pWhatSearch.toLowerCase();
    categoryClass = categoryClass.substr(0, 1).toUpperCase() + categoryClass.substr(1);

    var category = $(".search-column.right > li." + categoryClass);
    var subTypeChecked = category.find(".propertytype ul.subTypes li .checkMe.checked");

    var subtypes = [];
    subTypeChecked.each(function () {
        subtypes.push($(this).find("a b").html());
    });
    return subtypes.join(",");
}
function GetSaleLeaseFromSearchForm(pWhatSearch) {
    var category = $(".search-column.right > li.active");
    var results = [];
    var forSale = category.find("#forSale.searchInput.attribute");
    if (forSale[0] !== undefined && forSale[0] !== null && forSale[0].checked) {
        results.push(forSale.val() + ":[=]1");
    }
    var forLease = category.find("#forLease.searchInput.attribute");
    if (forLease[0] !== undefined && forLease[0] !== null && forLease[0].checked) {
        results.push(forLease.val() + ":[=]1");
    }
    return results;
}
function GetCeilingHeightFromSearchForm(pWhatSearch) {
    var $cMinTextbox = $("#ceilingHeightMin_" + pWhatSearch.toLowerCase());
    var $cMaxTextbox = $("#ceilingHeightMax_" + pWhatSearch.toLowerCase());
    var ceilingHeights = [];

    if ($cMinTextbox.val() != $cMinTextbox.attr("title")) {
        if ($cMinTextbox.val().length > 0) {
            ceilingHeights.push("17:[>=]" + $cMinTextbox.val());
        }
    }
    if ($cMaxTextbox.val() != $cMaxTextbox.attr("title")) {
        if ($cMaxTextbox.val().length > 0) {
            ceilingHeights.push("17:[<=]" + $cMaxTextbox.val());
        }
    }
    return ceilingHeights;
}
function GetProximityFromSearchForm(pWhatSearch) {
    var $distAirMinTextbox = $("#distAirportMin_" + pWhatSearch.toLowerCase());
    var $distAirMaxTextbox = $("#distAirportMax_" + pWhatSearch.toLowerCase());
    var $distInterstateMinTextbox = $("#distInterstateMin_" + pWhatSearch.toLowerCase());
    var $distInterstateMaxTextbox = $("#distInterstateMax_" + pWhatSearch.toLowerCase());
    var proximity = [];

    if ($distAirMinTextbox.val() != $distAirMinTextbox.attr("title")) {
        if ($distAirMinTextbox.val().length > 0) {
            proximity.push("28:[>=]" + $distAirMinTextbox.val());
        }
    }
    if ($distAirMaxTextbox.val() != $distAirMaxTextbox.attr("title")) {
        if ($distAirMaxTextbox.val().length > 0) {
            proximity.push("28:[<=]" + $distAirMaxTextbox.val());
        }
    }

    if ($distInterstateMinTextbox.val() != $distInterstateMinTextbox.attr("title")) {
        if ($distInterstateMinTextbox.val().length > 0) {
            proximity.push("30:[>=]" + $distInterstateMinTextbox.val());
        }
    }
    if ($distInterstateMaxTextbox.val() != $distInterstateMaxTextbox.attr("title")) {
        if ($distInterstateMaxTextbox.val().length > 0) {
            proximity.push("30:[<=]" + $distInterstateMaxTextbox.val());
        }
    }


    return proximity;
}
function GetAssetsFromSearchForm(pWhatSearch) {
    var category = $(".search-column.right > li.active");
    var assetsChecked = category.find("ul.assets .checkMe.checked");
    var assets = [];
    assetsChecked.each(function () {
        //15:[=]1
        assets.push($(this).find("a b").html() + ":[=]1");
    });
    return assets;
}
function GetPriceFromSearchForm(pWhatSearch) {
    var sMin = -1, sMax = -1;
    var category = $(".search-column.right > li.active");
    var $sMinTextbox = category.find("#salesPriceMin_" + pWhatSearch.toLowerCase());
    var $sMaxTextbox = category.find("#salesPriceMax_" + pWhatSearch.toLowerCase());
    var sMinTextboxVal = $sMinTextbox.val();
    var sMaxTextboxVal = $sMaxTextbox.val();
    sMinTextboxVal = SanitizeSearchValueNumber(sMinTextboxVal, $sMinTextbox);
    sMaxTextboxVal = SanitizeSearchValueNumber(sMaxTextboxVal, $sMaxTextbox);

    if (sMinTextboxVal != $sMinTextbox.attr("title")) {
        if (sMinTextboxVal.length > 0) {
            sMin = sMinTextboxVal;
        }
    }
    if (sMaxTextboxVal != $sMaxTextbox.attr("title")) {
        if (sMaxTextboxVal.length > 0) {
            sMax = sMaxTextboxVal;
        }
    }

    var prices = [];
    if (sMin >= 0) {
        prices.push("108:[>=]" + sMin);
    }
    if (sMax >= 0) {
        prices.push("108:[<=]" + sMax);
    }
    return prices;
}
function GetLeaseRateFromSearchForm(pWhatSearch) {
    var lMin = -1, lMax = -1;
    var category = $(".search-column.right > li.active");
    var $lMinTextbox = category.find("#leaseRateMin_" + pWhatSearch.toLowerCase());
    var $lMaxTextbox = category.find("#leaseRateMax_" + pWhatSearch.toLowerCase());
    var lMinTextboxVal = $lMinTextbox.val();
    var lMaxTextboxVal = $lMaxTextbox.val();
    lMinTextboxVal = SanitizeSearchValueNumber(lMinTextboxVal, $lMinTextbox);
    lMaxTextboxVal = SanitizeSearchValueNumber(lMaxTextboxVal, $lMaxTextbox);

    if (lMinTextboxVal != $lMinTextbox.attr("title")) {
        if (lMinTextboxVal.length > 0) {
            lMin = lMinTextboxVal;
        }
    }
    if (lMaxTextboxVal != $lMaxTextbox.attr("title")) {
        if (lMaxTextboxVal.length > 0) {
            lMax = lMaxTextboxVal;
        }
    }

    var leases = [];
    if (lMin >= 0) {
        leases.push("72:[>=]" + lMin);
    }
    if (lMax >= 0) {
        leases.push("72:[<=]" + lMax);
    }
    return leases;
}
function GetAddressFromSearchForm(pWhatSearch) {
    var $addressTextbox = $("#address_" + pWhatSearch.toLowerCase());
    if ($addressTextbox.val() != $addressTextbox.attr("title")) {
        if ($addressTextbox.val().length > 0) {
            return $addressTextbox.val();
        }
    }
    return null;
}
function GetPropertyIdFromSearchForm(pWhatSearch) {
    var $propertyIDTextbox = $("#propertyID_" + pWhatSearch.toLowerCase());
    if ($propertyIDTextbox.val() != $propertyIDTextbox.attr("title")) {
        if ($propertyIDTextbox.val().length > 0) {
            return $propertyIDTextbox.val();
        }
    }
    return null;
}
function GetBrokerIdFromSearchForm(pWhatSearch) {
    var myBrokerID = _SearchScope.BrokerID; //could be null most likely

    var $brokerIDTextbox = $("#brokerID_" + pWhatSearch.toLowerCase());
    if ($brokerIDTextbox.val() != $brokerIDTextbox.attr("title")) {
        if ($brokerIDTextbox.val().length > 0) {
            myBrokerID = $brokerIDTextbox.val();
        }
    }
    return myBrokerID;
}
function GetSelectedGeoEntities(pWhatSearch) {
    var category = $(".search-column.right > li.active");
    var geoEntities = [].concat(_SearchScope.GeoEntityList);


    category.find(".Geography .content > div:not(.regions, .subregion, .neighborhood, .incentivezone)").each(function () {
        $(this).find(".to li:not(.prompt)").each(function (index, geoEntity) {
            var myDirection = $(geoEntity).html().indexOf("[+]") != -1 ? "+" : "-";
            geoEntities.push(myDirection + $(geoEntity).attr("geoid"));
        });
    });

    return geoEntities.join(",");
}
function GetSelectedRegions(pWhatSearch) {
    var category = $(".search-column.right > li.active");
    var regionGeoIds = [];
    category.find(".Geography .content > div.regions .to li:not(.prompt)").each(function (index, region) {
        regionGeoIds.push("+" + $(region).attr("geoid"));
    });
    return regionGeoIds.join(",");
}
function GetPropertyAttributesFromSearchForm(pWhatSearch) {
    var myAttributes = [];
    myAttributes = myAttributes.concat(GetSaleLeaseFromSearchForm(pWhatSearch));
    myAttributes = myAttributes.concat(GetAssetsFromSearchForm(pWhatSearch));
    myAttributes = myAttributes.concat(GetCeilingHeightFromSearchForm(pWhatSearch));
    myAttributes = myAttributes.concat(GetPriceFromSearchForm(pWhatSearch));
    myAttributes = myAttributes.concat(GetLeaseRateFromSearchForm(pWhatSearch));
    myAttributes = myAttributes.concat(GetProximityFromSearchForm(pWhatSearch));
    myAttributes = myAttributes.concat(GetLocationFromSearchForm(pWhatSearch));
    return myAttributes.join(",");
} //end function

function GetLocationFromSearchForm(pWhatSearch) {
    var category = $(".search-column.right > li.active");
    var attributes = [];
    category.find(".Geography .content > div.subregion .to li:not(.prompt)").each(function (index, i) {
        attributes.push("536:[=]" + $(i).attr("geoid"));
    });
    category.find(".Geography .content > div.neighborhood .to li:not(.prompt)").each(function (index, i) {
        attributes.push("535:[=]" + $(i).attr("geoid"));
    });
    category.find(".Geography .content > div.incentivezone .to li:not(.prompt)").each(function (index, i) {
        attributes.push("534:[=]" + $(i).attr("geoid"));
    });


    return attributes;
} //end function


function GetSizeFromSearchForm(pWhatSearch) {
    var $myMinSize = $("#minSize_" + pWhatSearch.toLowerCase());
    var $myMaxSize = $("#maxSize_" + pWhatSearch.toLowerCase());

    var myMinSize = $myMinSize.val();
    var myMaxSize = $myMaxSize.val();
    myMinSize = SanitizeSearchValueNumber(myMinSize, $myMinSize);
    myMaxSize = SanitizeSearchValueNumber(myMaxSize, $myMaxSize);
    var myIsAcres = pWhatSearch == "SITES";

    //remove any empty string
    myMinSize = myMinSize === '' ? null : myMinSize;
    myMaxSize = myMaxSize === '' ? null : myMaxSize;

    //correct for acres
    if (myIsAcres) {
        if (myMinSize !== null && myMinSize !== '') {
            myMinSize = Math.round(myMinSize * 43560);
        }
        if (myMaxSize !== null) {
            myMaxSize = Math.round(myMaxSize * 43560);
        }
    } //end if acres
    return { Min: myMinSize, Max: myMaxSize };
}
//==========================================SEARCH PROCESSING========================================/
function SearchSuccess(result) {
    var myType = result.Type;
    var setMapType = function (map) {
        if (typeof (map) === "undefined" || map === null) {
            setTimeout(function () { setMapType(map); }, 100);
        }
        else {
            map.setMapTypeId(google.maps.MapTypeId.ROADMAP);
        }
    };
    setMapType(map);

    if (myType != "BUSINESS") {
        _businessMap.hide();
    }

    map.getStreetView().setVisible(false);

    _SSR.ResetSearchResults(myType);
    _SSR._SetSearchResults(result);

    _SSR._StopProcessCurrentIterativeAsyncResultOperation = false;

    CreateLoadingScreen("CONTENT");

    resultCount = _SSR._GetCount(myType);
    if (resultCount > 0) {
        _SSR._CurrentViewType = myType;
        _SSR._LastSearchType = myType;

        if (resultCount == 1 && (/COMMUNIT/).exec(myType)) {
            //show the result
            ShowFirstResult(myType);
        }
        else {
            ShowSearchResults(myType);
        }
    }
    else {
        //create the based on search result links
        var mySearchParams = null;

        //note: DisplayNoResultsMessage is poorly written and clears the header and footer as well. So the call to set the search tickler must occur after this call
        DisplayNoResultsMessage("No results were found with this search, click here to <a href='javascript:RefineSearch();'>refine your search</a>.", "");

        var mySearchBasedOnHTML = CreateSearchTickler(myType);
        ReplaceView("HEADER_SECONDARY", mySearchBasedOnHTML, false);
    } //end ifelse
    CancelSearch();
} //end function


function SearchAdditionalPageSuccess(result) {
    log.info("SearchAdditionalPageSuccess()");
    var myType = result.Type;
    _SSR._AddResults(result.Results, result.StartID - 1, result.Type);

    if (_SSR.FindCallback(result.RequestID) != -1) {
        setTimeout(function () { _SSR.ExecuteCallback(result.RequestID); }, 1);
    } //end if

    ManageOrderReceived();

} //end method

function DisplayNoResultsMessage(pTitle, pSubtitle) {
    //show a no results message
    RemoveMarkers(map, _propertyMarkers);
    _propertyMarkers = [];

    _SSR.ClearCurrentReportOverlays();
    ResetContentItemHolder();
    ClearHeaderAndFooter();
    _SSR._CurrentViewClass = "NONE";
    ReplaceView("CONTENT", "<div class='noResults'><h2>" + pTitle + "</h2><div>" + pSubtitle + "</div></div>");

} //end function display no results

function ClearHeaderAndFooter() {
    ReplaceView("HEADER", "");
    ReplaceView("FOOTER", "");
    $("#contentHeaderMenu").empty();
    $("#contentFooterMenu").empty();
    $("#ContentStatsHeader").empty();
    $("#ContentStatsFooter").empty();
    $("#contentNav .back").css("display", "none");
    $("#contentNav .next").css("display", "none");
}

function ReplaceView(pType, pHTML, pRemoveProgressBarMap) {


    //clear the progress bar
    if (pRemoveProgressBarMap) {
        RemoveProgressBar();
    } //end if replace progress bar


    var mySelectorsToClear = [];

    switch (pType) {
        case "HEADER":
            mySelectorsToClear.push("#contentBoxHeaderPrimaryItem");
            mySelectorsToClear.push("#contentBoxHeader .contentBoxHeader_menu");
            break;
        case "FOOTER":
            break;
        case "CONTENT":
            //show a loading screen
            mySelectorsToClear.push("#ContentItemHolder");
            break;
        case "SUBREPORT":
            mySelectorsToClear.push("#SubReportNodeToReplace");
            break;
        case "MODAL":
            mySelectorsToClear.push("#dynamicModalWindowHolder");
            break;
        case "HEADER_PRIMARY":
            mySelectorsToClear.push("#contentBoxHeaderPrimaryItem");
            break;
        case "HEADER_SECONDARY":
            mySelectorsToClear.push("#contentBoxHeader .contentBoxHeader_menu");
            break;
        default:
            break;
    } //end swtich

    for (var i = 0; i < mySelectorsToClear.length; i++) {
        $(mySelectorsToClear[i]).children().empty().remove();
        $(mySelectorsToClear[i]).empty();
        $(mySelectorsToClear[i]).html(pHTML);
        if(pType == "CONTENT" || pType == "SUBREPORT"){
          SendDocumentHeight(); // from interfaceinteraction
        }
    }


} //end function

function DisplaySearchResultsProxy(pPage, pPageSize, pType) {

    //set the default page size if not specified
    pPageSize = (pPageSize === null ? _SSR._GetPageSize(pType) : pPageSize);

    //set the default pType if not specified (paging links do this)
    pType = (pType === null ? _SSR._CurrentViewType : pType);

    var myClosure = function () {
        return new function () {
            DisplaySearchResults(pPage, pPageSize, _SSR._GetCount(_SSR._CurrentViewType), map, _propertyMarkers);
        };
    };

    //execute in timeout so async operation completes
    setTimeout(myClosure, 1);

} //end method




function DisplaySearchResults(pPage, pPageSize, pNumResults, pMap, pPropertyMarkers) {
    var startID = pPage * pPageSize;
    var endID = (pNumResults >= startID + pPageSize) ? startID + pPageSize : pNumResults;
    var myType = _SSR._CurrentViewType;



    var mySearchBasedOnHTML = CreateSearchTickler(myType);
    ReplaceView("HEADER_SECONDARY", mySearchBasedOnHTML, false);

    //Add the paging
    CreatePagingLinks(_SSR._GetCount(myType), pPageSize, pPage);






    //set the global page size reference
    _SSR._SetPageSize(pPageSize, myType);
    _SSR._SetCurrentIndex(startID, myType);
    _SSR._SetStopAtIndex(endID, myType);

    SetCurrentlyViewableProperties(startID, endID, myType);

    //clear the loading indicator
    ReplaceView("CONTENT", "");

    //call the ManagePropertyResults which ends the ajax call
    setTimeout(function () {
        ManagePropertyResults();
        //reset backtracking
        _SSR.GetNavBackText();
    }, 10);

} //end function

function SetCurrentlyViewableProperties(pStartID, pEndID, pMyType) {
    var myTracker = _SSR._Trackers[pMyType];
    myTracker.CurrentlyViewable = [];
    for (i = pStartID; i < pEndID; i++) {
        myTracker.CurrentlyViewable.push(myTracker.Results[i]);
    }
} //end function

function CreatePagingLinks(pNumberOfRows, pPageSize, pCurrentPage, pSearchParams) {
    var myType = _SSR._CurrentViewType;

    var myTotalResults = _SSR._GetCount(myType);

    //figure ot the number of pages and what pages to show (max pages to display at once is 5
    var numPages = (pNumberOfRows - (pNumberOfRows % pPageSize)) / pPageSize + ((pNumberOfRows % pPageSize > 0) ? 1 : 0);
    var myPagePadding = GISP_PROPERTY_PAGER_BUFFER;

    //modifiers will allow always 5 pages to be displayed
    var myEndPageModifier = (pCurrentPage - myPagePadding) > 0 ? 0 : -(pCurrentPage - myPagePadding);
    var myStartPageModifier = pCurrentPage + myPagePadding <= numPages ? 0 : myPagePadding - (numPages - pCurrentPage);

    var myStartPage = (pCurrentPage - myPagePadding - myStartPageModifier) > 0 ? pCurrentPage - myPagePadding - myStartPageModifier : 0;
    var myEndPage = pCurrentPage + myPagePadding + myEndPageModifier <= numPages ? pCurrentPage + myPagePadding + myEndPageModifier : numPages;


    //calculaate the now viewing
    var myListViewable = pCurrentPage * pPageSize + pPageSize;
    if (myListViewable > myTotalResults) {
        myListViewable = myTotalResults;
    } //end if greater than count
    var myNowViewing = "Viewing " + (pCurrentPage * pPageSize + 1) + "-" + myListViewable + " of " + myTotalResults;



    var myPager = "<li class='found'>" + myNowViewing + "</li>\
				   <li class='PageMenu'><span class='contentStatsMenu'><a href='#'>Pages</a></span>\
					   <ul class='popDownMenu paging'>\
							<li><a href='javascript:SkipResults(0);' title='Skip to the first page'>First page</a></li>\
							<li><a href='javascript:SkipResults(" + (numPages - 1) + ");' title='Skip to the last page'>Last page</a></li>\
						</ul>\
						</li><li><span class='pageNumbers'>@PAGES of @TOTALPAGES</span></li>";
    var myPage = "<span class='@PAGECLASS'><a href=\"@LINK\">@PAGENUM</a></span>";
    var myPages = "";


    //loop thru the results
    for (var i = myStartPage; i < myEndPage; i++) {
        myPages += myPage.replace("@LINK", "javascript:SkipResults(" + i + ")").replace("@PAGENUM", i + 1).replace("@PAGECLASS", i == pCurrentPage ? "current" : "");
        if (i < myEndPage - 1) {
            myPages += " | ";
        } //end if not last page
    } //end for each page

    //finish it up
    myPager = myPager.replace("@TOTALPAGES", numPages);
    myPager = myPager.replace("@TOTALFOUND", myTotalResults);
    myPager = myPager.replace("@PAGES", myPages);


    $("#ContentStatsHeader").html(myPager);
    $("#ContentStatsFooter").html(myPager);

    //set up all mouseover states for the content tools
    $(".PageMenu").hover(
				function () {
				    $("ul:first", this).css("display", "block");
				    $("span:first", this).attr("id", "current");
				},
				function () {
				    $("ul:first", this).css("display", "none");
				    $("span:first", this).attr("id", "");
				}
			);

    //fix up the zindex
    FixIE7IndexingContainer($("#ContentStatsHeader"), 7800);
    FixIE7IndexingContainer($("#ContentStatsFooter"), 7800);


} //end function

//Temporary clean-up until we get it into the DB
function CleanUpCommunitySearchParameters(pSearchParams) {
    var newParams = {};

    newParams["StartRowID"] = pSearchParams.StartRowID;
    newParams["EndRowID"] = pSearchParams.EndRowID;
    newParams["SortBy"] = pSearchParams.SortBy;
    newParams["SortDirection"] = pSearchParams.SortDirection;
    newParams["RequestID"] = pSearchParams.RequestID;
    newParams["InputParameters"] = pSearchParams.InputParameters;
    newParams["Community Type"] = pSearchParams.commType;
    newParams["Population Min"] = pSearchParams.popmin;
    newParams["Population Max"] = pSearchParams.popmax;
    newParams["Unemployment Min"] = pSearchParams.uermin;
    newParams["Unemployment Max"] = pSearchParams.uermax;
    newParams["Education Type"] = $("#educationType option[value=" + pSearchParams.edfac + "]").text();
    newParams["Airport Type"] = $("#airportType option[value=" + pSearchParams.airport + "]").text();
    newParams["Labor Size Min"] = pSearchParams.lfsmin;
    newParams["Labor Size Max"] = pSearchParams.lfsmax;
    newParams["Bachelors Degree Min %"] = pSearchParams.bdpmin;
    newParams["Bachelors Degree Max %"] = pSearchParams.bdpmax;
    newParams["Highschool Graduates Min %"] = pSearchParams.hspMin;
    newParams["Highschool Graduates Max %"] = pSearchParams.hspMax;
    newParams["Household Income Min"] = pSearchParams.hhimin;
    newParams["Household Income Max"] = pSearchParams.hhimax;
    newParams["Median Age Min"] = pSearchParams.medmin;
    newParams["Median Age Max"] = pSearchParams.medmax;
    newParams["Distance to Interstate Min"] = pSearchParams.dintMin;
    newParams["Distance to Interstate Max"] = pSearchParams.dintMax;
    newParams["Distance to Rail Min"] = pSearchParams.drailMin;
    newParams["Distance to Rail Max"] = pSearchParams.drailMax;
    newParams["Young and Educated Min"] = pSearchParams.yedumin;
    newParams["Young and Educated Max"] = pSearchParams.yedumax;
    newParams["Home Value Min"] = pSearchParams.homeMin;
    newParams["Home Value Max"] = pSearchParams.homeMax;
    newParams["Blue Collar Min %"] = pSearchParams.blupctmin;
    newParams["Blue Collar Max %"] = pSearchParams.blupctmax;
    newParams["White Collar Min %"] = pSearchParams.whtpctmin;
    newParams["White Collar Max %"] = pSearchParams.whtpctmax;
    newParams["Travel Time Min"] = pSearchParams.travMin;
    newParams["Travel Time Max"] = pSearchParams.travMax;
    newParams["Federal Enterprise Community or Empowerment Zone "] = pSearchParams.entzone;
    newParams["SubsetToken"] = pSearchParams.SubsetToken;

    return newParams;
}

function CreateSearchTickler(pType) {

    //todo: replace with embeddedjs template
    var myMenuScript = "<script type=\"text/javascript\">\n" +
						"//set up all mouseover states for the content tools\n" +
						"$(\".contentBoxHeader_menu\").hover(function() {$(\"ul:first\",this).css(\"display\", \"block\");$(this).addClass(\"contentBoxHeader_menu_current\");},function() {$(\"ul:first\",this).css(\"display\", \"none\");$(this).removeClass(\"contentBoxHeader_menu_current\");});\n" +
						"</script>\n";
    //todo: replace with embeddedjs template
    var myMenuBase = "<a href=\"#\" id=\"contentBoxHeaderSecondaryItem\" class=\"ContentToolsItem\">Based On</a><ul class=\"popDownMenu\" id=\"contentBoxHeaderSecondaryMenu\">";

    //todo: replace with embeddedjs template
    var myRefineSearchFunction = "javascript:RefineSearch();";

    //todo: replace with embeddedjs template
    var mySearchTicklerRefine = "<li><a style='background:transparent none; border: none;' href=\"" + myRefineSearchFunction + "\" title='Click here to refine your current search'>Refine Search</a></li></ul>";
    var mySearchTicklerItems = "";
    var mySearchParams = $.extend(true, {}, _SSR._Trackers[pType].SearchParameters); //creates clone

    //convert sqft to acres if of type 'SITES'
    if (mySearchParams.SearchType == "SITES") {
        if (mySearchParams["MinSize"] > 0) {
            mySearchParams["MinSize"] = mySearchParams["MinSize"] * (2.29568411 * Math.pow(10, -5));
            mySearchParams["MinSize"] = Math.round(mySearchParams["MinSize"] * Math.pow(10, 2)) / Math.pow(10, 2);
        }
        if (mySearchParams["MaxSize"] > 0) {
            mySearchParams["MaxSize"] = mySearchParams["MaxSize"] * (2.29568411 * Math.pow(10, -5));
            mySearchParams["MaxSize"] = Math.round(mySearchParams["MaxSize"] * Math.pow(10, 2)) / Math.pow(10, 2);
        }
    }

    //Clean up parameters for properties (buildings/sites)
    if (mySearchParams["Attributes"] !== undefined && mySearchParams["Attributes"] !== "") {
        mySearchParams["Attributes"] = GetDisplayAttributes(mySearchParams["Attributes"]);
    }
    if (mySearchParams["GeoEntityList"] !== undefined && mySearchParams["GeoEntityList"] !== "") {
        mySearchParams["GeoEntityList"] = GetDisplayGeoEntities(mySearchParams["GeoEntityList"]);
    }
    if (mySearchParams.PropertyType !== undefined && mySearchParams.PropertyType !== "") {
        mySearchParams.PropertyType = GetDisplayPropertyTypes(mySearchParams.PropertyType);
    }
    if (mySearchParams.RegionsList !== undefined && mySearchParams.RegionsList !== null && mySearchParams.RegionsList !== "") {
        mySearchParams.RegionsList = GetDisplayRegionList(mySearchParams.RegionsList);
    }

    if (mySearchParams["MinSize"] == -1) { mySearchParams["MinSize"] = null; }
    if (mySearchParams["MaxSize"] == -1) { mySearchParams["MaxSize"] = null; }

    //Clean up community search params
    if (mySearchParams["commType"] !== undefined) {
        mySearchParams = CleanUpCommunitySearchParameters(mySearchParams);
    }

    //Clean up parameters for all types
    mySearchParams["__type"] = null; //dont show the ASP.net type
    mySearchParams["SessionID"] = null;
    mySearchParams["RequestID"] = null;
    mySearchParams["SortBy"] = null;
    mySearchParams["StartRowID"] = null;
    mySearchParams["EndRowID"] = null;
    mySearchParams["SubsetToken"] = null;
    mySearchParams["IsBuilding"] = null;

    //Create html for "tickler"
    //todo: replace with embeddedjs template
    for (var p in mySearchParams) {
        if (mySearchParams[p] !== null && mySearchParams[p] !== "") {
            mySearchTicklerItems += "<li><strong>" + p.replace("_", " ") + "</strong>:<br/> " + mySearchParams[p] + "</li>";
        } //end if parameter passed
    } //end for each parameter

    //todo: replace with embeddedjs template
    return myMenuScript + myMenuBase + mySearchTicklerItems + mySearchTicklerRefine;
} //end function

function GetDisplayAttributes(pSearchAttributes) {
    var myDisplayAttributes = null;

    $.ajax({
        url: "/common/services/Utilities.asmx/CreateDisplayStringFromSiteAttributes",
        async: false,
        data: "{'pSiteAttributes': '" + pSearchAttributes + "'}",
        dataType: "json",
        contentType: "application/json; charset=utf-8",
        type: "POST",
        cache: false, //TODO: insures the latest version (we may want to consider turning this off after development)
        success: function (result) {
            myDisplayAttributes = result.d;
        }
    });
    return myDisplayAttributes;
} //end function
function GetDisplayRegionList(pRegionList) {
    var myDisplayRegions;

    $.ajax({
        url: "/common/services/Utilities.asmx/GetRegionySearchDisplayString",
        async: false,
        data: "{'pSearchRegions': '" + pRegionList + "'}",
        dataType: "json",
        contentType: "application/json; charset=utf-8",
        type: "POST",
        cache: false,
        success: function (result) {
            myDisplayRegions = result.d;
        }
    });
    return myDisplayRegions;
}
function GetDisplayGeoEntities(pSearchGeoEntities) {
    var myDisplayGeoEntities;

    $.ajax({
        url: "/common/services/Utilities.asmx/GetGeoEntitySearchDisplayString",
        async: false,
        data: "{'pSearchGeoEntities': '" + pSearchGeoEntities + "'}",
        dataType: "json",
        contentType: "application/json; charset=utf-8",
        type: "POST",
        cache: false, //TODO: insures the latest version (we may want to consider turning this off after development)
        success: function (result) {
            myDisplayGeoEntities = result.d;
        }
    });
    return myDisplayGeoEntities;
} //end function

function GetDisplayPropertyTypes(pSearchPropertyTypes) {
    var myDisplayPropertyTypes;
    $.ajax({
        url: "/common/services/Utilities.asmx/GetPropertyTypeSearchDisplayString",
        async: false,
        data: "{'pSearchPropertyTypes': '" + pSearchPropertyTypes + "'}",
        dataType: "json",
        contentType: "application/json; charset=utf-8",
        type: "POST",
        cache: false, //TODO: insures the latest version (we may want to consider turning this off after development)
        success: function (result) {
            myDisplayPropertyTypes = result.d;
        }
    });
    return myDisplayPropertyTypes;
}

function SearchFail(error) {
    log.error("SearchFail()");
    alert("Failed to retreive results from the search: " + error._message);
    CancelSearch();
} //end function

function CancelSearch() {
    //TODO: Figure out how to cancel async in progress

    //hide the loading screen
    HideDynamicModal();
} //end function

function SortResults(pWhatField) {
    //clear the markers from the map and the array
    var myType = _SSR._CurrentViewType;
    var myParams = _SSR._Trackers[myType].SearchParameters;
    myParams.StartRowID = 0;
    myParams.EndRowID = _SSR._Trackers[myType].PageSize;
    myParams.SortBy = pWhatField;
    myParams.SortDirection = true;
    RemoveMarkers(map, _propertyMarkers);
    _propertyMarkers = [];

    CreateLoadingScreen("CONTENT");
    var myNoResultsHeaderDiv = document.createElement("div");
    var myNoResultsFooterDiv = document.createElement("div");
    ReplaceView("HEADER", myNoResultsHeaderDiv);
    ReplaceView("FOOTER", myNoResultsFooterDiv);


    //do the search
    _SSR.ResetSearchResults(myType);
    _SSR._SetSortBy(pWhatField, myType);


    switch (myType) {
        case "SITES":
            CallSiteSearchService(myParams, { successCallback: SearchSuccess, failureCallback: SearchFail });
            break;
        case "BUILDINGS":
            CallBuildingSearchService(myParams, { successCallback: SearchSuccess, failureCallback: SearchFail });
            break;
        case "COMMUNITIES":
            CallCommunitySearchService(myParams, { successCallback: SearchSuccess, failureCallback: SearchFail });
            break;
        case "SAVED":
            alert("Sorting saved results is not implemented yet.");
            break;
        default:
            break;
    } //end switch
}


function ResetClientSearch() {

    //iterate over all the resetters
    for (var r in _SearchReseters) {
        var myResetArray = _SearchReseters[r];
        for (var i = 0; i < myResetArray.length; i++) {
            setTimeout(myResetArray[i], 1);
        } //end for each item
    } //end for each property 

    RemovePoly(); //remove any existing permanent polygon

    //clear the polypoints
    $("#hfldPolyPoints").val("");

    return false;
} //end function

function ToggleSaveRemoveReport(pReportID, pType) {
    //Saves or removes the property, business or community

    var myMarker = FindPropertyMarker(pReportID);
    var myCurrentIcon = myMarker.getIcon();
    var IsSaving = !_SSR.IsResultSaved(pReportID);
    var myMarkerImage = myMarker.getIcon().url;
    var myButtonImage = "";
    var myType;

    if (pType !== undefined) {
        myType = pType;
    }
    else {
        myType = _SSR._CurrentViewType;
    }

    //Save or remove
    if (IsSaving) {
        if (/REPORTS_SAVED/.exec(myType) === null) {
            _SSR.SaveResult(pReportID, myType);
        }
        else {
            SaveReport(pReportID);
        }
    } else {
        if (/REPORTS_SAVED/.exec(myType) === null) {
            _SSR.RemoveResult(pReportID, myType);
        }
        else {
            _SSR.DeleteReport(pReportID);
        }
    } //end if/else saving

    _SSR.UpdateMyFolder();


    //update the property icon on the map and the display listing
    if (IsSaving) {
        var myIndexOfLastSlash = myMarkerImage.lastIndexOf('.');
        myMarkerImage = myMarkerImage.substr(0, myIndexOfLastSlash) + "_on" + myMarkerImage.substr(myIndexOfLastSlash, myMarkerImage.length - myIndexOfLastSlash);
    }
    else {
        myMarkerImage = myMarkerImage.replace("_on", "");
    }
    // find link in marker
    var $mymarker_link = $("#hrefSaveResultInfoWindow_" + pReportID);
    var $mymarker_html_link = $("#hrefSaveResultInfoWindow_" + pReportID, myMarker.HTML);

    if (IsSaving) {
        $mymarker_link.html("Remove");
        $mymarker_html_link.html("Remove");
        $mymarker_link.next().html(" from folder");
        $mymarker_html_link.next().html(" from folder");
    }
    else {
        $mymarker_link.html("Save");
        $mymarker_html_link.html("Save");
        $mymarker_link.next().html(" to folder");
        $mymarker_html_link.next().html(" to folder");
    }
    // This code updates the markers html with the most recent state
    myMarker.HTML = $mymarker_html_link.closest("table#miniwindow").wrapAll("<div/>").closest("div").html();

    //update the property listing
    if (IsSaving) {
        $("#" + pReportID + " .savedDecorator").addClass("saved");
        $("#" + pReportID + " .saveLink").text("Remove");
        $("#" + pReportID + " .saveToFrom").text("from");

    } else {
        $("#" + pReportID + " .savedDecorator").removeClass("saved");
        $("#" + pReportID + " .saveLink").text("Save");
        $("#" + pReportID + " .saveToFrom").text("to");
    } //end if/else is saving

    setMarkerSavedImage(myMarker, myMarkerImage);

    if (!IsSaving && (/_SAVED/).exec(myType) !== null) {
        //refresh the saved display
        ShowSavedResults(myType.replace('_SAVED', ''), false);
    }

    setTimeout(PersistTrackers, 1000);
    if (IsSaving) {
        LogAccessStatistic([pReportID], 1);
    }

    //Log that the entity was saved
    if (IsSaving) {
        LogUsage({ "Type": "SAVEOBJECT", "ID": pReportID, "Value": myType });
    }
} //end function Save Property


function setMarkerSavedImage(pMarker, pImage) {

    var existingIcon = pMarker.getIcon();
    var image = new google.maps.MarkerImage(pImage, existingIcon.size, new google.maps.Point(0, 0), existingIcon.anchor);
    pMarker.setIcon(pImage);
}

function SaveAllCurrentResults() {
    var myType = _SSR._CurrentViewType;
    var myTracker = _SSR._Trackers[myType];
    var mySliderInfo = CalcSliderInfo();

    var mySavedProperties = [];
    var thisSavedProperty;
    //save all the viewable results if they are downloaded
    for (var i = mySliderInfo.FirstViewable; i < mySliderInfo.LastViewable + 1; i++) {
        if (myTracker.Results[i] !== false) {
            thisSavedProperty = myTracker.Results[i].ID;
            _SSR.SaveResult(thisSavedProperty, myType);
            mySavedProperties.push(thisSavedProperty);
            LogUsage({ "Type": "SAVEOBJECT", "ID": thisSavedProperty, "Value": myType });
        } //end if not false
    }

    _SSR.UpdateMyFolder();
    CreateLoadingScreen("CONTENT");
    setTimeout(ManagePropertyResults, 100);
    setTimeout(PersistTrackers, 1000);
    LogAccessStatistic(mySavedProperties, 1);

} //end function

function FindPropertyMarker(pPropertyID) {
    var myMarker = null;
    for (var i = 0; i < _propertyMarkers.length; i++) {
        if (_propertyMarkers[i].ID == pPropertyID) {
            myMarker = _propertyMarkers[i];
            break;
        } //end if property found
    } //end for each property marker

    return myMarker;
}

function ViewAllResults() {
    CreateLoadingScreen("CONTENT");

    //in order to accomplish this, we have to download all the pages
    var myType = _SSR._CurrentViewType;
    var numPages = _SSR._GetNumPages(myType);
    var myTotalRecords = _SSR._GetCount(myType);

    alert("Not implemented yet");
}

function SiteSearchViewAllSuccess(pResult) {
} //end function

function CreateLoadingScreen(pType) {
    ReplaceView(pType, "<div class='loadingResults'><img src='/common/images/loader_bert2_orange.gif'/></div>");
}

function ShowGeoSubsearch(pWhatSub) {
    switch (pWhatSub) {
        case "ADDRESS": ShowAddressSubSearch(); break;
        case "CITY": ShowCitySubSearch(); break;
        case "COUNTY": ShowCountySubSearch(); break;
        case "STATE": ShowStateSubSearch(); break;
        case "REGION": ShowRegionSubSearch(); break;
        default: break;
    } //end switch sub type
} //end function

function ShowAddressSubSearch() {
    ShowSubSearchForm("ADDRESS");
}
function LoadGeoEntities(pType, pAlias, pSearch) {
    var myFields = GetGeoEntityInputFieldsBySearchType(pType, pSearch);
    var myListPlaceholder = myFields.from;
    var myList = $("#LIST_" + pType);
    var mySearchBox = myFields.search;
    //make the appropriate list viewable

    //hide all geo containers
    HideGeoList();
    
    //set the global reference to the current geolist
    _currentGeoList.List = myList;
    _currentGeoList.Anchor = myListPlaceholder;

    PositionCurrentGeoList();



    setTimeout(function () {
        setTimeout(function () { SetupSearchAutocomplete(mySearchBox, myList); }, 10);
    }, 10);


    //add the double click events
    myList.unbind("click").bind("click", function (evt) {
        var myItem = evt.target;
        $(myItem).toggleClass("ui-selected").siblings().removeClass("ui-selected");
        GISP_AddGeoEntityToSelectList(pType, pAlias, pSearch);
    });

  



    //update the +- buttons
    $(myFields.plus).unbind("click").click(function () { GISP_AddGeoEntityToSelectList(pType, pAlias, pSearch); });
    $(myFields.minus).unbind("click").click(function () { GISP_RemoveSelectedGeoEntity(pType, pSearch); });



}

function PositionCurrentGeoList() {
    //position and show the geoList
    setTimeout(function () {
        if (_currentGeoList.List != null && _currentGeoList.Anchor != null) {
            //insure placeholder is visible and then get its offset
            $(_currentGeoList.Anchor).show();
            var myPosition = $(_currentGeoList.Anchor).offset();

            _currentGeoList.List.css({ "top": myPosition.top + "px", "left": myPosition.left + "px" });
            _currentGeoList.List.show();
        }
    }, 10);
}

function HideGeoList() {
    $(".geoListContainer").hide();
    _currentGeoList.List = null;
    _currentGeoList.Anchor = null;
}

function SetupSearchAutocomplete(pSearchElement, pList) {
    //possible this will be called and not be ready
    if (pList.attr("id") != null) {
        // Clear previous autocomplete cache
        var searchBox = $(pSearchElement);


        var mySearchType = pList.attr("id").replace("LIST_", "");

        // Wire-up autocomplete
        searchBox.autocomplete({
            minLength: 2,
            source: function (request, response) {
                PostToService("/common/services/GeoEntities.asmx/Get" + mySearchType + "ByName", //URL
				JSON.stringify({ pSubsetTOKEN: _GISP_Theme, term: request.term }), //data
				function (data) {//success function

				    var pEntities = [];
				    for (var i = 0; i < data.d.length; i++) {
				        var item = data.d[i];
				        pEntities.push({ "value": item.ID, "label": item.DisplayName });
				    }
				    response(pEntities);
				},
				function (xhr, text) {//fail function
				    //do nothing
				});
            },
            focus: function (evt, ui) {
                searchBox.val(ui.item.label);
                return false;
            },
            select: function (evt, ui) {
                searchBox.val(ui.item.label);
                AutocompleteSelectValue(evt, ui.item);
                return false;
            }
        });
    }//end if this is not the custom list
 

} //end function

function AutocompleteSelectValue(event, pEntity) {

    //TODO: pull this based on search type and possibly change the way EntityType is determined
    var activeSection = $(".search-column.right > li.active .Geography .content > div.active");
    activeSection.removeClass("active");
    var myEntityType = activeSection.attr("class").toUpperCase(); //i.e. CITIES
    activeSection.addClass("active");
    var myEntityTypeAlias = 'entity';
    var container = $(".search-column.right > li.active");
    var mySearchType = container.clone().removeClass("active").attr("class").toUpperCase();

    var myFields = GetGeoEntityInputFieldsBySearchType(myEntityType, mySearchType);
    var myEntityList = myFields.from;
    var mySelectedList = myFields.to;
    var mySelectedListUL = $("ul", mySelectedList);

    //make sure its not already added to the other list before adding it
    if (!GISP_DetermineIfOptionSelected(mySelectedList, pEntity.value)) {
        var myItem = "<li geoID='" + pEntity.value + "' title='Double click to exclude this " + myEntityTypeAlias.toLowerCase() + "'>[+]" + pEntity.label + "</li>";
        mySelectedListUL.append(myItem);
    } //end if not added

    //clean up the box and activate scroll
    $("li.prompt", mySelectedListUL).css("display", "none");
    //$(mySelectedList).jScrollPane();
    $("ul", mySelectedList).selectable();

    $("li[geoID=" + pEntity.value + "]", mySelectedList).addClass("ui-selecting");

    setTimeout(function () {
        $(myFields.search).val(""); //clear search box
        $("li[geoID=" + pEntity.value + "]", mySelectedList).removeClass("ui-selecting");
    }, 250);

}

function GetGeoEntityInputFieldsBySearchType(pType, pSearch) {
    var myFields = {};
    var pTypeLower = pType.toLowerCase();
    var pSearchLower = pSearch.toLowerCase();

    //sites_cities, buildings_regions
    var toFromBlock = $("#" + pSearchLower + "_" + pTypeLower + " .tofromBlock");

    myFields.search = toFromBlock.find(".search")[0];
    myFields.from = toFromBlock.find(".from")[0];
    myFields.to = toFromBlock.find(".to")[0];
    myFields.plus = toFromBlock.find(".tofromBtns .plus")[0];
    myFields.minus = toFromBlock.find(".tofromBtns .minus")[0];
    myFields.toFrom = toFromBlock[0];
    myFields.fromList = $("#LIST_" + pSearch.toUpperCase() + " ul")[0];

    return myFields;
}

function GISP_AddGeoEntityToSelectList(pEntityType, pTypeAlias, pSearchType) {
    var myFields = GetGeoEntityInputFieldsBySearchType(pEntityType, pSearchType);
    var myEntityList = myFields.fromList;
    var mySelectedList = myFields.to;
    var myEntitySelectedListItems = $("li.ui-selected", myEntityList);
    var mySelectedListUL = $("ul", mySelectedList);

    for (var i = 0; i < myEntitySelectedListItems.length; i++) {
        //make sure its not already added to the other list before adding it
        var myEntity = $(myEntitySelectedListItems[i]);
        if (!GISP_DetermineIfOptionSelected(mySelectedList, myEntity.attr("g"))) {
            var myItem = "<li geoID='" + myEntity.attr("g") + "' title='Double click to exclude this " + pTypeAlias.toLowerCase() + "'>[+]" + myEntity.text() + "</li>";
            mySelectedListUL.append(myItem);
        } //end if not added
    } //end for each element

    //clean up the box and activate scroll
    $("li.prompt", mySelectedListUL).css("display", "none");
    $(mySelectedList).jScrollPane();
    $("ul", mySelectedList).selectable();
    $("li", myEntityList).removeClass("ui-selected").removeClass("ui-selectee");

} //end function
function GISP_RemoveSelectedGeoEntity(pEntityType, pSearchType) {
    var myFields = GetGeoEntityInputFieldsBySearchType(pEntityType, pSearchType);
    var mySelectedList = myFields.to;

    GISP_RemoveSelectedOptionsFromList(mySelectedList);

    //clean up selected items highlight
    $("li", mySelectedList).removeClass("ui-selected").removeClass("ui-selectee");
} //end function

function GISP_NegateSelectedGeoEntity(pEntityType, pTypeAlias, pSearchType) {
    var myFields = GetGeoEntityInputFieldsBySearchType(pEntityType, pSearchType);
    var mySelectedList = $("ul", myFields.to)[0];

    for (var i = mySelectedList.childNodes.length - 1; i >= 0; i--) {
        var myOption = mySelectedList.childNodes[i];
        if ($(myOption).hasClass("ui-selected")) {
            if (myOption.innerText.indexOf("[-]") == -1) {
                myOption.innerText = myOption.innerText.replace("[+]", "[-]");
                myOption.title = "Double click to include this " + pTypeAlias.toLowerCase();
                $(myOption).addClass("red");
            } else {
                myOption.innerText = myOption.innerText.replace("[-]", "[+]");
                myOption.title = "Double click to exclude this " + pTypeAlias.toLowerCase();
                $(myOption).removeClass("red");
            }
        }
    }


    //clean up selected items highlight
    $("li", mySelectedList).removeClass("ui-selected").removeClass("ui-selectee");

} //end function

function UpdateSearchTickler(pType) {
    //this is a placeholder for now
} //end function



function GISP_DetermineIfOptionSelected(pList, pValue) {
    return myItemIsAlreadyAdded = $("li[geoID='" + pValue + "']", pList).length > 0;
} //end function

function GISP_RemoveSelectedOptionsFromList(pList) {
    $("li.ui-selected", pList).remove();
} //end function




function ShowSearchResults(pType) {
    _SSR._CurrentViewType = pType;
    map.setMapTypeId(google.maps.MapTypeId.ROADMAP);
    _SSR.ClearCurrentReportOverlays();
    _SSR.ClearOtherReportOverlays();
    _SSR._StopProcessCurrentIterativeAsyncResultOperation = false;


    //Setup the appropriate menu and result area
    _SSR._CurrentViewClass = "RESULTS";
    SetContentItemContainerForResults();
    ChangeResultOrientation(_SSR._Trackers[pType].ResultOrientation);
    LoadStyleSheet("REPORT_NULL");
    ReplaceView("HEADER_PRIMARY", "Results");
    LoadContentMenu(pType + "_RESULTS");


    if (_SSR._GetCount(pType) > 0) {
        var myPage = _SSR._GetCurrentPage(_SSR._CurrentViewType);
        DisplaySearchResultsProxy(myPage, null, pType);
    } else {
        DisplayNoResultsMessage("There are currently no results to view.", "Click one of the search buttons above to start finding properties/communities, or you may need to broaden the search criteria from a previous search.");
    }
} //end function Save Property

function ShowSavedResults(pType, pAddNavHistory) {
    _SSR.ClearCurrentReportOverlays();
    _SSR.ClearOtherReportOverlays();
    _businessMap.hide();
    _mapBar.SetMapMode("MAP");
    _SSR._StopProcessCurrentIterativeAsyncResultOperation = false;
    map.setMapTypeId(google.maps.MapTypeId.ROADMAP);
    _SSR._Trackers[pType].SlideDirection = 1; //cfurrow - reset the slide direction back to 1
    $("div.contentBoxHeader_menu h4").html("");


    if (_SSR._GetCount(pType + "_SAVED") > 0) {

        //Setup the appropriate menu and result area
        _SSR._CurrentViewClass = "RESULTS";
        _SSR._CurrentViewType = pType + "_SAVED";
        SetContentItemContainerForResults();
        // May need to clear content here
        ReplaceView("CONTENT", "");
        ChangeResultOrientation(_SSR._Trackers[pType].ResultOrientation);
        LoadStyleSheet("REPORT_NULL");
        ReplaceView("HEADER_PRIMARY", "Saved " + pType.toLowerCase());
        LoadContentMenu(pType + "_SAVED");

        setTimeout(function () {
            ManagePropertyResults(pAddNavHistory);
            //Set up the back button
            var myNavHistoryLink = _SSR.GetHistoryLink();
            $("#backNavigation").html(myNavHistoryLink).css("display", "block");
            $(".historyNavigation .ContentToolsItem").hover(
					function () {
					    $("ul:first", this).css("display", "block");
					    $(this).attr("id", "ContentToolCurrent");
					},
					function () {
					    $("ul:first", this).css("display", "none");
					    $(this).attr("id", "");
					}
				);

            FixIE7IndexingContainer($("#backNavigation"), 7800);

        }, 100);
    } else {
        DisplayNoResultsMessage("You have not saved any " + pType.toLowerCase(), "Once you have saved results, they will be visible here.");
    }

} //end function Save Property



function SortSaved(pSortBy) {
    var myType = _SSR._CurrentViewType;
    var myResults = _SSR._Trackers[myType].Results;
    var mySortFunction = eval('CompareBy' + pSortBy);
    myResults.sort(mySortFunction);
    ShowSavedResults(myType.split('_')[0]);
}

function CompareByName(p1, p2) {
    return CompareGeneric(p1.BuildingName, p2.BuidingName);
}

function CompareByZipCode(p1, p2) {
    return CompareGeneric(p1.ZipCode, p2.ZipCode);
}

function CompareByCity(p1, p2) {
    return CompareGeneric(p1.CityName, p2.CityName);
}

function CompareByCounty(p1, p2) {
    return CompareGeneric(p1.CountyName, p2.CountyName);
}

function CompareByState(p1, p2) {
    return CompareGeneric(p1.StateName, p2.StateName);
}

function CompareByAddress(p1, p2) {
    return CompareGeneric(p1.Address, p2.Address);
}

function CompareByMinSize(p1, p2) {
    return CompareGeneric(parseFloat(p1.MinSize.replace(',', '')), parseFloat(p2.MinSize.replace(',', '')));
}

function CompareByMaxSize(p1, p2) {
    return CompareGeneric(parseFloat(p1.MaxSize.replace(',', '')), parseFloat(p2.MaxSize.replace(',', '')));
}

function CompareGeneric(p1, p2) {
    return ((p1 < p2) ? -1 : ((p1 > p2) ? 1 : 0));
}


function CreateSavedSearchResult() {

    var myCurrentIndex = _SSR._GetCurrentIndex(_SSR._CurrentViewType);
    var myCurrentType = _SSR._CurrentViewType;
    if ((_SSR._GetCurrentIndex(myCurrentType) < _SSR._GetStopAtIndex(myCurrentType)) & !_SSR._StopProcessCurrentIterativeAsyncResultOperation) {

        var myResult = _SSR.GetResultByIndex(myCurrentIndex, myCurrentType);
        var myResultType = myResult.ID.substr(0, myResult.ID.indexOf("_", 0));
        switch (myResultType) {
            case "SITES":
                _SiteSearchResultBuilder.CreateMarkerAndListing(myCurrentIndex, myCurrentType, _SSR.GetResultByIndex(myCurrentIndex, myCurrentType));
                break;
            case "COMMUNITY":
                _CommunitySearchResultBuilder.CreateMarkerAndListing(myCurrentIndex, myCurrentType, _SSR.GetResultByIndex(myCurrentIndex, myCurrentType));
                break;
            default: break;
        } //end switch type


        //if this is the last function, set the map zooom and remove the progress bar
        if (myCurrentIndex == _SSR._GetStopAtIndex(myCurrentType) - 1) {
            //remove the progress bar
            RemoveProgressBar();
        }
        else {
            _SSR._SetCurrentIndex(myCurrentIndex + 1, myCurrentType);

            var myCallback = function () {
                CreateSavedSearchResult();

            }; //end method
            setTimeout(myCallback, 1);
        } //end if last of not call self recursilvely
    } //end if
} //end function

function CompareItems(pComparisonType) {
    var myCompareHtml = "";
    if (pComparisonType == 'ALL') {
        myCompareHtml = CompareAllItemsInTracker();
    }
    else if (pComparisonType == 'CURRENT') {
        myCompareHtml = CompareVisibleItems();
    }
    else if (pComparisonType == 'SELECT') {
        myCompareHtml = ShowItemSelectCompareWindow();
    }
    ShowDynamicModal(myCompareHtml);
} // end function

function CompareAllItemsInTracker() {
    //warning: this function only compares items in the tracker
    var myType = _SSR._CurrentViewType;
    var myTracker = _SSR._Trackers[myType];
    var myStart = 0;
    var myEnd = 0;
    myStart = 0;
    myEnd = myTracker.Results.length - 1;

    var myComparisonHtml = "<div id='comparisonContent' style='background-color:#fff; height:500px; width:750px; overflow:scroll;'><table width='1500px' border='1' cellpadding='5'>";
    myComparisonHtml += GetComparisonHeaderRowHtmlByType(myType);
    for (var i = myStart; i <= myEnd; i++) {
        var myResult = myTracker.Results[i];
        var myRowHtml = "<tr>";
        myRowHtml += GetComparisonHtmlRowByType(myType, myResult);
        myRowHtml += "</tr>";
        myComparisonHtml += myRowHtml;
    }
    myComparisonHtml += "</table></div>";
    return myComparisonHtml;
}

function CompareVisibleItems() {
    var myType = _SSR._CurrentViewType;
    var myTracker = _SSR._Trackers[myType];
    var myStart = 0;
    var myEnd = 0;
    myStart = myTracker.CurrentIndex;
    myEnd = myStart + myTracker.PageSizeDefault - 1 < myTracker.Results.length - 1 ? myStart + myTracker.PageSizeDefault - 1 : myTracker.Results.length - 1;

    var myComparisonHtml = "<div id='comparisonContent' style='background-color:#fff; height:500px; width:750px; overflow:scroll;'><table width='1500px' border='1' cellpadding='5'>";
    myComparisonHtml += GetComparisonHeaderRowHtmlByType(myType);
    for (var i = myStart; i <= myEnd; i++) {
        var myResult = myTracker.Results[i];
        var myRowHtml = "<tr>";
        myRowHtml += GetComparisonHtmlRowByType(myType, myResult);
        myRowHtml += "</tr>";
        myComparisonHtml += myRowHtml;
    }
    myComparisonHtml += "</table></div>";
    return myComparisonHtml;
} //end function

function ShowItemSelectCompareWindow() {
    //TODO: Fill in function
    alert("That functionality is not implemented at this time.");
} //end function
function GetComparisonHeaderRowHtmlByType(pType) {
    var mySitesRegex = /SITES/;
    var myBuildingsRegex = /BUILDINGS/;
    var myCommunitiesRegex = /COMMUNITIES/;

    if (mySitesRegex.exec(pType) !== null || myBuildingsRegex.exec(pType) !== null) {
        return "<thead><tr><td>Photo</td><td>Name</td><td>Address</td><td>City,State Zip</td><td>County</td><td>Minimum SubDivide</td><td>Total SQFT</td><td>Sub Types</td><td>For Sale</td><td>For Lease</td><td>Sale Price</td><td>Lease Rate</td><td>Lease Terms</td><td>Number of Floors</td><td>Ceiling Max</td></tr></thead>";
    }
    else if (myCommunitiesRegex.exec(pType) !== null) {
        return "<thead><tr><td>Photo</td><td>Name/State</td><td>Population</td><td>Labor Force Size</td><td>Bachelors Degree or Higher</td><td>Household Income Median</td><td>Job Growth</td><td>Travel Time</td><td>Domestic Airports</td><td>Distance to International Airport</td><td>Distance to Rail</td></tr></thead>";
    }
}
function GetComparisonHtmlRowByType(pType, pResult) {
    var mySitesRegex = /SITES/;
    var myBuildingsRegex = /BUILDINGS/;
    var myCommunitiesRegex = /COMMUNITIES/;

    if (mySitesRegex.exec(pType) !== null || myBuildingsRegex.exec(pType) !== null) {
        return GetPropertiesComparisonHtmlRow(pResult);
    }
    else if (myCommunitiesRegex.exec(pType) !== null) {
        return GetCommunitiesComparisonHtmlRow(pResult);
    }
} //end function
function GetPropertiesComparisonHtmlRow(pResult) {
    //TODO: Fill in function
    var myHtml = "<td><img src='" + pResult.Thumbnail + "'/></td>";
    myHtml += "<td>" + pResult.BuildingName + "</td>";
    myHtml += "<td>" + pResult.Address + "</td>";
    myHtml += "<td>" + pResult.CityName + "," + pResult.StateName + " " + pResult.ZipCode + "</td>";
    myHtml += "<td>" + pResult.CountyName + "</td>";
    myHtml += "<td>" + pResult.MinSize + "sq ft</td>";
    myHtml += "<td>" + pResult.MaxSize + "sq ft</td>";
    myHtml += "<td><ul>";
    for (var i = 0; i < pResult.SubTypes.length; i++) {
        myHtml += "<li>" + pResult.SubTypes[i] + "</li>";
    }
    myHtml += "</ul></td>";

    var myCustomerDefinedAttributesRaw = pResult.CustomerDefinedAttributes.split(",");
    var myCustomerDefinedAttributes = {};
    var j = 0;
    for (j = 0; j < myCustomerDefinedAttributesRaw.length; j++) {
        var split = myCustomerDefinedAttributesRaw[j].split(":");
        myCustomerDefinedAttributes[split[0]] = split[1];
    }

    myHtml += "<td>" + (myCustomerDefinedAttributes['FOR_SALE'] == '1' ? 'yes' : 'no') + "</td>";
    myHtml += "<td>" + (myCustomerDefinedAttributes['FOR_LEASE'] == '1' ? 'yes' : 'no') + "</td>";
    myHtml += "<td>" + (myCustomerDefinedAttributes['SALE_PRICE'].length > 0 ? "$" + myCustomerDefinedAttributes['SALE_PRICE'] : "") + "</td>";
    myHtml += "<td>" + myCustomerDefinedAttributes['LEASE_RATE'] + "</td>";
    myHtml += "<td>" + myCustomerDefinedAttributes['LEASE_TERMS'] + "</td>";
    myHtml += "<td>" + myCustomerDefinedAttributes['FLOOR_NUM'] + "</td>";
    myHtml += "<td>" + myCustomerDefinedAttributes['CEILING_MAX'] + "</td>";

    return myHtml;
} //end function

function GetCommunitiesComparisonHtmlRow(pResult) {
    //TODO: Fill in function
    var myHtml = "<td><img src='" + pResult.photo + "'/></td>";
    myHtml += "<td>" + pResult.Name + " - " + pResult.State + "</td>";
    myHtml += "<td>" + pResult.Population + "</td>";
    myHtml += "<td>" + pResult.LaborForceSize + "</td>";
    myHtml += "<td>" + pResult.BachelorsHigherPct + "</td>";
    myHtml += "<td>" + pResult.HHIncomeMedian + "</td>";
    myHtml += "<td>" + pResult.JobGrowth + "</td>";
    myHtml += "<td>" + pResult.TravelTime + "</td>";
    myHtml += "<td>" + pResult.DomesticAirports + "</td>";
    myHtml += "<td>" + pResult.DistanceToInt + "</td>";
    myHtml += "<td>" + pResult.DistanceToRail + "</td>";

    return myHtml;
} //end function

//function CompareItems() {
//    GISPlanning_MapUtilities_RegisterScript("/common/scripts/ComparisonReport.js");
//    $get("tblComparisons").style.display = "none";
//    $get("tblComparisonsLoading").style.display = "block";
//    $find("mpeComparisons").show();
//    setTimeout(DisplayComparisonItemsWhenScriptLoaded, GISP_TIME_TO_WAIT_WHEN_CHECKING_LOAD_OF_SCRIPT);

//}; //end function
//function CloseComparison() {
//    DisplayInlineTable("tblComparisons");
//    $get("tblComparisonsLoading").style.display = "none";
//    $find("mpeComparisons").hide();
//}; //end function
//function DisplayComparisonItemsWhenScriptLoaded() {
//    if (typeof (ComparisonReporter) == "undefined") {
//        setTimeout(DisplayComparisonItemsWhenScriptLoaded, GISP_TIME_TO_WAIT_WHEN_CHECKING_LOAD_OF_SCRIPT);
//    } else {
//        SetupComparisonWindow();
//    }; //end if loaded
//}; //end function




function PersistTrackers() {
    var myFolderId = ReadCookie('ZPE_MY_FOLDER_ID');

    if (myFolderId === null) {
        CreateCookie('ZPE_MY_FOLDER_ID', 'TEST', 30);
        if (ReadCookie('ZPE_MY_FOLDER_ID') === null) {
            // cookies disabled, do not proceed
            return;
        }
    }

    var mySavedReportProxies = _SSR._Trackers["REPORTS_SAVED"].Results.slice();
    var myParentReports = [];

    //Persist the unique parent reports
    $(_SSR._Trackers["REPORTS_SAVED"].Results).each(function () {
        var alreadyAdded = false;
        //look for it
        for (var i = 0; i < mySavedReportProxies.length; i++) {
            if (mySavedReportProxies[i].ID == _SSR.GetReportByUniqueID(this.ID).Properties["ParentReportID"]) {
                alreadyAdded = true;
                break;
            }
        }

        if (!alreadyAdded) {
            myParentReports.push({ ID: _SSR.GetReportByUniqueID(this.ID).Properties["ParentReportID"] });
            mySavedReportProxies.push({ ID: _SSR.GetReportByUniqueID(this.ID).Properties["ParentReportID"] });
        }
    });





    var myLoadedReports = _SSR._Reports;
    var myReports = [];

    for (var i = 0; i < myLoadedReports.length; i++) {
        for (var j = 0; j < mySavedReportProxies.length; j++) {
            if (myLoadedReports[i].UniqueID == mySavedReportProxies[j].ID) {

                //only save the content if its  a parent report
                var myContent = "<script>ReloadReport('" + myLoadedReports[i].UniqueID + "');</script>";
                for (var k = 0; k < myParentReports.length; k++) {
                    if (myLoadedReports[i].UniqueID == myParentReports[k].ID) {
                        myContent = myLoadedReports[i].Content;
                    }
                }


                myReports.push({
                    ID: myLoadedReports[i].ID,
                    Type: myLoadedReports[i].Type,
                    Content: myContent,
                    Parameters: myLoadedReports[i].Parameters,
                    Properties: myLoadedReports[i].Properties,
                    Name: myLoadedReports[i].Name,
                    Icon: myLoadedReports[i].Icon,
                    SubReports: myLoadedReports[i].SubReports,
                    Description: myLoadedReports[i].Description,
                    DisplayImageURL: myLoadedReports[i].DisplayImageURL,
                    UniqueID: myLoadedReports[i].UniqueID
                });
            }
        }
    }


    var myData = new Array(_SSR._Trackers["SITES_SAVED"].Results,
							_SSR._Trackers["BUILDINGS_SAVED"].Results,
							_SSR._Trackers["REPORTS_SAVED"].Results,
							_SSR._Trackers["COMMUNITIES_SAVED"].Results,
							myReports,
							_SSR._Trackers["BUSINESSES_SAVED"].Results);


    PostToService("/common/services/Utilities.asmx/SetUserFolderData",
	  JSON.stringify({ pData: myData, pDataID: myFolderId }),
	  function (data) { PersistTrackersComplete(data.d); },
	  function (xhr, text) { PersistTrackersFail(text); });

}

function PersistTrackersComplete(pResult) {
    if (pResult !== null) {
        CreateCookie('ZPE_MY_FOLDER_ID', pResult, 30);
    }
}

function PersistTrackersFail(pError) {
    alert('Unable to save contents of My Folder.');
}

function RetrieveTrackers() {
    var myFolderId = ReadCookie('ZPE_MY_FOLDER_ID');
    if (myFolderId === null) {
        return;
    }
    PostToService("/common/services/Utilities.asmx/GetUserFolderData",
	  JSON.stringify({ pDataID: myFolderId }),
	  function (data) { RetrieveTrackersComplete(data.d); },
	  function (xhr, text) { RetrieveTrackersFailed(text); });
}

function RetrieveTrackersComplete(pResult) {
    var myFolderData = pResult;
    if (myFolderData !== null) {
        RestoreTracker(_SSR._Trackers["SITES_SAVED"], myFolderData[0]);
        RestoreTracker(_SSR._Trackers["BUILDINGS_SAVED"], myFolderData[1]);
        RestoreTracker(_SSR._Trackers["REPORTS_SAVED"], myFolderData[2]);
        RestoreTracker(_SSR._Trackers["COMMUNITIES_SAVED"], myFolderData[3]);
        RestoreTracker(_SSR._Trackers["BUSINESSES_SAVED"], myFolderData[5]);

        var myReports = myFolderData[4];
        for (var thisReport = 0; thisReport < myReports.length; thisReport++) {
            var myReport = new GISP_Report({});
            myReport.ID = myReports[thisReport].ID;
            myReport.Type = myReports[thisReport].Type;
            myReport.Content = myReports[thisReport].Content;
            myReport.Parameters = myReports[thisReport].Parameters;
            myReport.Properties = myReports[thisReport].Properties;
            myReport.Name = myReports[thisReport].Name;
            myReport.Icon = myReports[thisReport].Icon;
            myReport.SubReports = myReports[thisReport].SubReports;
            myReport.Description = myReports[thisReport].Description;
            myReport.DisplayImageURL = myReports[thisReport].DisplayImageURL;
            myReport.UniqueID = myReports[thisReport].UniqueID;
            _SSR._Reports.push(myReport);
        }
        _SSR.UpdateMyFolder();


        for (var i = 0; i < _SSR._SavedResultsIndex.length; i++) {
            UpdateDisplayedWithMyFolderData(_SSR._SavedResultsIndex[i]);
        }
    }
}

function RetrieveTrackersFailed(pError) {
    ShowErrorMessage(pError);
    alert('Unable to retrieve contents of My Folder.');
}


function RestoreTracker(pTracker, pSavedData) {
    //it is possible that the code base was updated since the last time the user
    //got their folder, this will allow for this.
    if (pSavedData !== undefined && pSavedData !== null) {
        pTracker.Results = pSavedData;
        pTracker.Count = pSavedData.length;
        for (var i = 0; i < pSavedData.length; i++) {
            _SSR._SavedResultsIndex.push(pSavedData[i].ID);
        }
    } //end if data exists
}

function ClearSavedResults(pType, pShowSavedResultsAfter, pCallPersistTrackers) {
    //loop through and togleSave on  each item
    var myBaseType = pType.replace("_SAVED", "");
    var myTracker = _SSR._Trackers[myBaseType];
    var i = 0;
    var myID = null;
    switch (pType) {
        case "SITES_SAVED":
        case "BUILDINGS_SAVED":
        case "COMMUNITIES_SAVED":
            for (i = 0; i < myTracker.Results.length; i++) {
                myID = myTracker.Results[i].ID;
                _SSR.RemoveResult(myID, myBaseType);
            }
            break;
        case "REPORTS_SAVED":
        case "BUSINESSES_SAVED":
            for (i = 0; i < myTracker.Results.length; i++) {
                myID = myTracker.Results[i].ID;
                //NOTE: RemoveResult does this for you, but becaues we done actually want to remove this report, we have to call this ourselves
                _SSR.DeleteFromSavedResultIndex(myID);
            }


            break;
        default: break;
    }



    //Clear the trackers
    _SSR.ResetTracker(pType);


    _SSR.UpdateMyFolder();

    if (pCallPersistTrackers !== false) {
        //Update the cleared trackers in the DB
        PersistTrackers();
    }


    //refresh the saved display
    if (pShowSavedResultsAfter !== false) {
        ShowSavedResults(myBaseType);
    }
    setTimeout(ManagePropertyResults, 200);
}

function ViewAll() {
    CreateLoadingScreen("CONTENT");
    var myType = _SSR._CurrentViewType;
    var myTracker = _SSR._Trackers[myType];
    var myContinue = true;
    var myParams = myTracker.SearchParameters;
    if (myTracker.Results.length > 100) {
        myContinue = confirm("Viewing all " + myTracker.Results.length + " at once can cause your browser to freeze and crash at times. Are you sure you wish to continue? Otherwise, click cancel and try to limit your results to less than 100 properties.");
    }
    if (myContinue) {
        //check to see if user is viewing saved results, if they are, don't order new data
        if (/_SAVED/.exec(myType) === null) {
            myParams.StartRowID = 1;
            myParams.EndRowID = myTracker.Results.length;

            OrderData(myType, myParams,
				function (pResults) {
				    //myTracker.ResultOrientation = 'horizontal';
				    ResetContentItemHolder();

				    _SSR._SetSearchResults(pResults);
				    ChangeResultOrientation('horizontal');
				    _SSR._SetPageSize(pResults.Results.length, myType);
				    setTimeout(ManagePropertyResults, 200);
				},
				function () { });
        }
        else {
            //viewing saved data, therefore the items should be loaded already. No need to order.
            //myTracker.ResultOrientation = 'horizontal';
            ResetContentItemHolder();
            ChangeResultOrientation('horizontal');
            _SSR._SetPageSize(myTracker.Results.length, myType);
            setTimeout(ManagePropertyResults, 200);
        }
    }
    else {
        ResetContentItemHolder();

        _SSR._SetSearchResults({ Type: myType, Results: myTracker.Results, Count: myTracker.Results.length, InputParameters: myParams });
        ChangeResultOrientation();
        setTimeout(ManagePropertyResults, 200);
    }
}


function OrderAll(pType, pCallback) {
    var myType = pType;
    var myTracker = _SSR._Trackers[myType];
    var myParams = myTracker.SearchParameters;

    myParams.StartRowID = 1;
    myParams.EndRowID = myTracker.Results.length;

    OrderData(myType, myParams,
		function (pResults) {
		    _SSR._SetSearchResults(pResults);
		    pCallback();
		},
		function () { }
	);
} //end function


//Saves all properties in the search results area to the user's "my folder" area
function SaveAll() {
    var myType = _SSR._CurrentViewType;
    var myTracker = _SSR._Trackers[myType];
    var myParams = myTracker.SearchParameters;
    var mySaveTracker = _SSR._Trackers[myType + "_SAVED"];
    var myUpdateTextCallback = ShowLoadingWindow('Gathering data for all ' + myTracker.Results.length + ' properties from the database.');
    myParams.StartRowID = 1;
    myParams.EndRowID = myTracker.Results.length;
    //Order/request all the data from the database, and save it.
    OrderData(myType, myParams,
	function (pResults) {
	    var myCurrentIndex = 0;
	    myUpdateTextCallback('Saving all property results. This may take a while.', null);
	    //Every x-milliseconds, add the next property
	    //When we've gone through allt he properties, clear the interval, and update the UI
	    var myTimerID = setInterval(function () {
	        if (myCurrentIndex > pResults.Results.length - 1) {
	            FinishSaveAllAndUpdateUI(myTimerID);
	            return;
	        }
	        if (!IsLoadingWindowVisible()) {
	            FinishSaveAllAndUpdateUI(myTimerID);
	            return;
	        }

	        UpdateMarkerForID(pResults.Results[myCurrentIndex].ID);

	        if (!_SSR.IsResultSaved(pResults.Results[myCurrentIndex].ID)) {
	            SavePropertyUpdateSavedIndex(mySaveTracker, pResults, myCurrentIndex);

	            myUpdateTextCallback(null, "Saved " + (myCurrentIndex + 1) + " of " + pResults.Results.length);
	            LogUsage({ "Type": "SAVEOBJECT", "ID": pResults.Results[myCurrentIndex].ID, "Value": pResults.Type });
	        } // end if already saved
	        myCurrentIndex++;
	    }, 5);
	},
	function () { });
}


function UpdateMarkerForID(pID) {
    try {
        //Try to update marker
        var myMarker = FindPropertyMarker(pID);
        var myMarkerImage = myMarker.getIcon().image;
        var myIndexOfLastSlash = myMarkerImage.lastIndexOf('_');
        myMarkerImage = myMarkerImage.substr(0, myIndexOfLastSlash) + "_on" + myMarkerImage.substr(myIndexOfLastSlash, myMarkerImage.length - myIndexOfLastSlash);
    }
    catch (exception) { /*just move on*/ }
}

function SavePropertyUpdateSavedIndex(pSaveTracker, pResults, pIndex) {
    pSaveTracker.Results.push($.extend(true, {}, pResults.Results[pIndex]));
    _SSR._SavedResultsIndex.push(pResults.Results[pIndex].ID);
    pSaveTracker.Count++;
}
function FinishSaveAllAndUpdateUI(pTimerID) {
    clearInterval(pTimerID);

    _SSR.UpdateMyFolder();
    setTimeout(PersistTrackers, 1000);
    setTimeout(ManagePropertyResults, 200);
    HideDynamicModal();
}


function FindInCommunities(pSearchType, pScope) {
    //Where search type is BUILDING -SITES - BUSINESSES and Scope is SINGLE - SAVED - RESULTS

    var myCallback = function (pCommunities) {

        _SSR._CurrentViewType = pSearchType;
        var myGeoList = [];

        for (var i = 0; i < pCommunities.length; i++) {
            if (pCommunities[i]) {//can be false based pre order results
                myGeoList.push(pCommunities[i].GeoEntityID);
            }
        } //end for each community

        var myParams = _SSR._Trackers[pSearchType].SearchParameters = GetNewSearchParams(pSearchType);
        if (myParams.GeoEntities != undefined) {
            myParams.GeoEntities = "+" + myGeoList.join(',+');
        }
        if (myParams.GeoEntityList != undefined) {
            myParams.GeoEntityList = "+" + myGeoList.join(',+');
        }

        CreateLoadingScreen("CONTENT");
        switch (pSearchType.toUpperCase()) {
            case "BUILDINGS": CallBuildingSearchService(myParams, { successCallback: SearchSuccess, failureCallback: SearchFail }); break;
            case "SITES": CallSiteSearchService(myParams, { successCallback: SearchSuccess, failureCallback: SearchFail }); break;
            case "BUSINESSES": CallBusinessSearchService(myParams, { successCallback: SearchSuccess }); break;

            default: break;
        }
    };

    GetAllCommunitiesForSearchWithin(pScope, myCallback);

}

function StartSearchWithCommunities(pSearchType, pScope) {
    //Where search type is BUILDING -SITES - BUSINESSES and Scope is SINGLE - SAVED - RESULTS

    var myCallback = function (pCommunities) {

        _SSR._CurrentViewType = pSearchType;
        DisplaySearch(false, pSearchType);

        for (var i = 0; i < pCommunities.length; i++) {
            if (pCommunities[i]) {//can be false based pre order results
                var myType = '';
                switch (pCommunities[i].CommunityType.toLowerCase()) {
                    case "city": myType = 'cities'; break;
                    case "county": myType = 'counties'; break;
                    case "state": myType = 'states'; break;
                    case "msa": myType = 'msas'; break;
                    default: break;

                }
                var myFields = GetGeoEntityInputFieldsBySearchType(myType, pSearchType);
                var mySelectedList = myFields.to;
                var mySelectedListUL = $("ul", mySelectedList);
                $("li.prompt", mySelectedListUL).css("display", "none");
                var myItem = "<li geoID='" + pCommunities[i].GeoEntityID + "' title='Double click to exclude this " + pCommunities[i].Name.toLowerCase() + "'>[+]" + pCommunities[i].Name + "</li>";
                mySelectedListUL.append(myItem);
            }

        } //end for each community




    };

    GetAllCommunitiesForSearchWithin(pScope, myCallback);
}

function GetAllCommunitiesForSearchWithin(pScope, pCallback) {
    var myCommunities = [];

    var myCallback = null;
    switch (pScope) {
        case "SINGLE":
            pCallback([_SSR._Trackers["COMMUNITIES"].Results[_SSR._Trackers["COMMUNITIES"].CurrentIndex]]);

            break;

        case "SAVED":
            myCallback = function () {
                var myCommunityResults = _SSR._Trackers["COMMUNITIES_SAVED"].Results;
                //add each community to the array
                for (var i = 0; i < myCommunityResults.length; i++) {
                    myCommunities.push(myCommunityResults[i]);
                }
                pCallback(myCommunities);
            };
            OrderAll("COMMUNITIES", myCallback);
            break;
        case "RESULTS":
            myCallback = function () {
                var myCommunityResults = _SSR._Trackers["COMMUNITIES"].Results;
                //add each community to the array
                for (var i = 0; i < myCommunityResults.length; i++) {
                    myCommunities.push(myCommunityResults[i]);
                }
                pCallback(myCommunities);
            };
            OrderAll("COMMUNITIES", myCallback);
            break;
        default: break;
    }
}

function ViewRSSFeed() {
    var myType = _SSR._CurrentViewType;
    var myTracker = _SSR._Trackers[myType];
    var myParams = myTracker.SearchParameters;
    if (myParams.__type != undefined) {
        delete myParams.__type;
    }

    //jsonify SearchParameters
    var myParamsAsString = JSON.stringify(myParams);
    var RSSUrl = "/main/tools/SearchFeeds.ashx?SST=" + _GISP_Theme + "&Q=" + myParamsAsString;
    GISPlanning_Popup_Window(RSSUrl, { toolbar: "1", scrollbars: "1", location: "1", statusbar: "1", menubar: "1", resizable: "1" });

    //track usage
    LogUsage({ "Type": "RSSVIEW", "ID": _GISP_Theme, "Value": RSSUrl });
}

function SanitizeNumber(pNumString) {
    // remove commas
    if (pNumString === null || pNumString === undefined) {
        return pNumString;
    }
    return parseFloat(String(pNumString).replace(",", ""));
}
// Value is the value to be sanitized and returned.
// Element is the jQuery object the value came from
function SanitizeSearchValueNumber(value, element) {
    if (typeof (value) === "undefined" || value === null || value === "") {
        return value;
    }
    var theID = element.attr("id");
    var theClasses = element.attr("class");
    var rNumberElements = [
	/minSize/gi,
	/maxSize/gi,
	/salesPrice/gi,
	/leaseRate/gi
  ];
    var newValue = value;
    var rNonNumbers = /[^0-9]*/g;
    var len = rNumberElements.length;
    var i = 0;
    var r = null;
    var isMatch = false;
    // Let's try to find a number-match
    //  If the element is a number, we need to sanitize it
    for (; i < len; i++) {
        r = rNumberElements[i];
        isMatch = r.test(theID);
        if (isMatch) {
            newValue = value.replace(rNonNumbers, "");
            break;
        }
    }
    return newValue;
}





function ZoomToStreetViewCurrentMaker() {
    var myPano = map.getStreetView();
    var myPosition = _infoWindow.getAnchor().position;

    var myPanoFound = function (data, status) {
        log.info(status);

        if (status == "OK") {

            var myPanoPosition = data.location.latLng;


            //calculate the bearing so the pegman points at the property
            var lat2 = myPosition.lat();
            var lat1 = myPanoPosition.lat();
            var dLon = Math.abs(myPosition.lng() - myPanoPosition.lng());

            var y = Math.sin(dLon) * Math.cos(lat2);
            var x = Math.cos(lat1) * Math.sin(lat2) - Math.sin(lat1) * Math.cos(lat2) * Math.cos(dLon);
            var brng = Math.atan2(y, x).toDeg();
            if (brng < 0)
                brng = 360 - brng;


            myPano.setPano(data.location.pano);
            myPano.setPosition(data.location.latLng);
            myPano.setPov({ heading: brng, zoom: 0, pitch: 0 });
            setTimeout(function () { myPano.setVisible(true); }, 300); //this must be done out of process so that the pano shows up correctly the firs time.
        }
        else {
            alert("We apologize, but streetview is not available at this location");
        }
    };

    log.info("requesting pano by location");
    var mySVS = new google.maps.StreetViewService();
    mySVS.getPanoramaByLocation(myPosition, 50, myPanoFound);

}


function findInArray(array, attribute, value) {
    var found = -1;
    for (var i = 0; i < array.length; i++) {
        if (array[i][attribute] == value) {
            found = i;
            break;
        }
    } //end for each


    return found;
};    //end find function

