﻿/// <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 _SiteSearchResultBuilder = new GISP_SiteSearchResultBulider();
var _CommunitySearchResultBuilder = new GISP_CommunitySearchResultBulider();

function DisplaySearch(pIsRefinement) {
    if (!pIsRefinement) {
        ResetClientSearch();
    }; //end if not refining


    //Setup the menu
    SetupPolyPointsSearchItem();



    $find("mpeSearch").show();
}; //end function

function DisplaySearchWhenLoaded() {
    if ($find("mpeSearch") == null) {
        setTimeout(DisplaySearchWhenLoaded, 10);
    } else {
        DisplaySearch();
    }; //end ifelse found
}; // this can be called and will keep calling itself until found

function DoSiteSearch() {
    $("#tblSearchForm").css({ display: "none" });
    $("#tblSearchWaiting").css({ display: "block" });
    CloseAllSubSearchForms();

    CallSiteSearchService(SearchSuccess, SearchFail, 0, _SSR._PageSizeDEFAULT);

    return false;
}; //end function

function CallSiteSearchService(pSuccessCallback, pFailureCallback, pStartRecordNumber, pEndRecordNumber) {
    var mySearchParams = GetSiteSearchParams();
    mySearchParams.StartRowID = pStartRecordNumber;
    mySearchParams.EndRowID = pEndRecordNumber;

    TVAGoogle.common.services.Sites.GetSites(mySearchParams, pSuccessCallback, pFailureCallback);


};

function GetSiteSearchParams() {
    var mySize = GetSizeFromSearchForm();
    var myCeiling = GetCeilingFromSearchForm();
    var mySaleLease = GetSaleLeaseFromSearchForm();

    var mySearchParams = {
        PropertyType: GetPropertyTypesFromSearchForm(),
        mins: mySize.Min,
        maxs: mySize.Max,
        minc: myCeiling.Min,
        maxc: myCeiling.Max,
        countylist: GetCountiesFromSearchForm(),
        citylist: GetCitiesFromSearchForm(),
        statelist: GetStatesFromSearchForm(),
        regionlist: GetRegionsFromSearchForm(),
        forsale: mySaleLease.Sale,
        forlease: mySaleLease.Lease,
        address: GetAddressFromSearchForm(),
        rail: GetRailFromSearchForm(),
        polyPoints: $get("hfldPolyPoints").value,
        subsetToken: _GISP_Theme,
        SortBy: _SSR._GetSortBy("SITES"),        
        SortDirection: false,
        RequestID: GISPlanning_MapUtilities_GUID()
    };
    return mySearchParams;
}; //end function

function GetSiteSearchDisplayParams() {
    var mySeachParams = GetSiteSearchParams();

    var mySelectedCities = GISPlanning_GetListboxDisplayItemsAsList($get("ctl00_cphModal_lboxSelectedCities"), ",");
    var mySelectedCounties = GISPlanning_GetListboxDisplayItemsAsList($get("ctl00_cphModal_lboxSelectedCounties"), ",");
    var mySelectedStates = GISPlanning_GetListboxDisplayItemsAsList($get("ctl00_cphModal_lboxSelectedStates"), ",");
    var mySelectedRegions = GISPlanning_GetListboxDisplayItemsAsList($get("ctl00_cphModal_lboxSelectedRegions"), ",");

    var myDisplayParams = {
        Property_Type: mySeachParams.PropertyType,
        Minimum_Size: (mySeachParams.mins && mySeachParams.mins > 0 ? mySeachParams.mins : null),
        Maximum_Size: (mySeachParams.maxs && mySeachParams.maxs > 0 ? mySeachParams.maxs : null),
        Minimum_Ceiling: (mySeachParams.mins && mySeachParams.minc > 0 ? mySeachParams.minc : null),
        Maximum_Ceiling: (mySeachParams.maxs && mySeachParams.maxc > 0 ? mySeachParams.maxc : null),
        For_Sale: mySeachParams.forsale,
        For_Lease: mySeachParams.forlease,
        Rail_Access: (mySeachParams.rail && mySeachParams.rail > 0 ? (mySeachParams.rail == 1 ? "Possible" : "Already Has") : null),
        Area_Filter: (mySeachParams.polyPoints != "" ? "Area Selected" : null),
        Address: mySeachParams.address,
        City_List: mySelectedCities,
        County_List: mySelectedCounties,
        State_List: mySelectedStates,
        Region_List: mySelectedRegions
    };
    return myDisplayParams;
}; //end funciton

function SetupPolyPointsSearchItem() {
    var myPolyPointsSelected = $get("hfldPolyPoints").value != "";
    var myPolySelectedDiv = $get("divPolySelectedDescription");
    var myPolyNotSelectedDiv = $get("divPolyNotSelectedDescription");

    myPolySelectedDiv.style.display = (myPolyPointsSelected ? "block" : "none");
    myPolyNotSelectedDiv.style.display = (!myPolyPointsSelected ? "block" : "none");
}; //end function

function AddPersistantPolygonInidicatingSearchArea() {
    var myLatLngs = document.getElementById('hfldPolyPoints').value.split(',');
    var latlngs = [];
    for (i = 0; i < myLatLngs.length; i++) {
        var point = myLatLngs[i];
        var myLatLng = point.split(':');
        latlngs.push(new GLatLng(myLatLng[0], myLatLng[1]));
    }; //end for each point

    //create the polygon and add it to the map
    _GISP_Filtering_Poly_Overlay = new GPolygon(latlngs, "#7d0e01", 3, .8, "#7d0e01", .05, { clickable: false });
    _mapBar.map.addOverlay(_GISP_Filtering_Poly_Overlay);
};

function ModifyPoly() {
    alert("Not implemented yet");
}; //end function

function RemovePoly() {
    //reset the hidden field
    document.getElementById('hfldPolyPoints').value = "";
    //update UI
    SetupPolyPointsSearchItem();

    //remove overlay from map
    if (_GISP_Filtering_Poly_Overlay != null) {
        _mapBar.map.removeOverlay(_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 GetPropertyTypesFromSearchForm() {
    var mySelectedPropertyTypes = [];
    if ($("#hrefPropertyType_Office > img:first").attr("src").indexOf("_active", 0) != -1) { mySelectedPropertyTypes.push("Office"); };
    if ($("#hrefPropertyType_Industrial > img:first").attr("src").indexOf("_active", 0) != -1) { mySelectedPropertyTypes.push("Industrial"); };
    if ($("#hrefPropertyType_Warehouse > img:first").attr("src").indexOf("_active", 0) != -1) { mySelectedPropertyTypes.push("Warehouse"); };
    if ($("#hrefPropertyType_Callcenter > img:first").attr("src").indexOf("_active", 0) != -1) { mySelectedPropertyTypes.push("CallCenter"); };
    if ($("#hrefPropertyType_Land > img:first").attr("src").indexOf("_active", 0) != -1) { mySelectedPropertyTypes.push("Land"); };

    var myReturnString = '';

    for (var i = 0; i < mySelectedPropertyTypes.length; i++) {
        myReturnString += mySelectedPropertyTypes[i];

        if (i < mySelectedPropertyTypes.length - 1) { myReturnString += ','; };
    }; //end for

    return myReturnString;

}; //end method

function GetSizeFromSearchForm() {
    var myMinSize = $get("ctl00_cphModal_tboxMinSize").value;
    var myMaxSize = $get("ctl00_cphModal_tboxMaxSize").value;
    var myIsAcres = $get("ctl00_cphModal_rblSizeType_1").checked;

    //remove any empty string
    myMinSize = myMinSize == '' ? null : myMinSize;
    myMaxSize = myMaxSize == '' ? null : myMaxSize;

    //correct for acres
    if (myIsAcres) {
        myMinSize = myMinSize == '' ? null : myMinSize * 43560;
        myMaxSize = myMaxSize == '' ? null : myMaxSize * 43560;
    }; //end if acres


    return { Min: myMinSize, Max: myMaxSize };
}

function GetRailFromSearchForm() {
    var myRail_0 = $get("ctl00_cphModal_rblRailAccess_0");
    var myRail_1 = $get("ctl00_cphModal_rblRailAccess_1");
    var myRail_2 = $get("ctl00_cphModal_rblRailAccess_2");

    return ((myRail_0.checked ? 1 : 0) * myRail_0.value) + ((myRail_1.checked ? 1 : 0) * myRail_1.value) + ((myRail_2.checked ? 1 : 0) * myRail_2.value);
};
function GetCeilingFromSearchForm() {
    var myMinMaxHeight = { Min: null, Max: null };
    if ($get("hfldCeilingHeightSet").value != null) {
        myMinMaxHeight.Min = $get('ctl00_cphModal_tboxMinCeiling').value;
        myMinMaxHeight.Max = null;
    };

    return myMinMaxHeight;
};
function GetSaleLeaseFromSearchForm() {
    var mySaleLease = {
        Sale: $get("ctl00_cphModal_rblFinance_2").checked,
        Lease: $get("ctl00_cphModal_rblFinance_1").checked
    };
    return mySaleLease;
};
function GetAddressFromSearchForm() {
    return $get("ctl00_cphModal_tboxAddress").value;
};
function GetCitiesFromSearchForm() {

    var mySelectedEntities = $get("ctl00_cphModal_lboxSelectedCities");
    return GISPlanning_GetListboxItemsAsIncludeExcludeList(mySelectedEntities, ",");
};
function GetCountiesFromSearchForm() {
    var mySelectedEntities = $get("ctl00_cphModal_lboxSelectedCounties");
    return GISPlanning_GetListboxItemsAsIncludeExcludeList(mySelectedEntities, ",");
};
function GetStatesFromSearchForm() {
    var mySelectedEntities = $get("ctl00_cphModal_lboxSelectedStates");
    return GISPlanning_GetListboxItemsAsIncludeExcludeList(mySelectedEntities, ",");
};
function GetRegionsFromSearchForm() {
    var mySelectedEntities = $get("ctl00_cphModal_lboxSelectedRegions");
    return GISPlanning_GetListboxItemsAsIncludeExcludeList(mySelectedEntities, ",");
};











function SearchSuccess(result) {
    var myType = result.Type;
    _mapBar.map.setMapType(G_NORMAL_MAP);
    _SSR.ResetSearchResults(myType);
    _SSR._SetSearchResults(result);
    SetCurrentTypeButton("SEARCH");

    _SSR._StopProcessCurrentIterativeAsyncResultOperation = false;

    if (_SSR._GetCount(myType) > 0) {
        _SSR._CurrentViewType = myType;
        _SSR._LastSearchType = myType;

        DisplaySearchResultsProxy(0, null, myType);
    }
    else {
        var mySearchParams = null;
        switch (myType) {
            case "SITES": mySearchParams = GetSiteSearchDisplayParams(); break;
            case "COMMUNITY": mySearchParams = GetCommunitySearchDisplayParameters(); break;
        }; //end switch

        var mySearchTickler = CreateSearchTickler(mySearchParams, myType);
        var myNoResultsDiv = document.createElement("div");
        myNoResultsDiv.appendChild(document.createTextNode("No results where found with this search. "));
        myNoResultsDiv.appendChild(mySearchTickler);
        DisplayNoResultsMessage(myNoResultsDiv.innerHTML);
    }; //end ifelse

    switch (myType) {
        case "SITES": CancelSearch(); break;
        case "COMMUNITY": CancelCommunitySearch(); break;
    }; //end function


    //here is where we look and see if there are more results and get the next page worth
    if (_SSR._GetNumPages(myType) > 1) {
        switch (myType) {
            case "SITES":
                CallSiteSearchService(SearchAdditionalPageSuccess, SearchFail, _SSR._GetPageSize(myType) + 1, _SSR._GetPageSize(myType) * 2);
                break;
            case "COMMUNITY":
                CallCommunitySearchService(SearchAdditionalPageSuccess, SearchFail, _SSR._GetPageSize(myType) + 1, _SSR._GetPageSize(myType) * 2);
                break;
        }; //end function
    }; //end if more results
}; //end function


function SearchAdditionalPageSuccess(result) {
    var myType = result.Type;
    var myPage = Math.floor(result.StartID / _SSR._GetPageSize(myType));
    _SSR.GetResults(result.Type)[myPage] = result.Results;
    _SSR._GetPages(result.Type)[myPage] = true;

    if (_SSR._AdditionalPageCallback != null) {
        setTimeout(_SSR._AdditionalPageCallback, 1);
    }; //end if

}; //end method

function DisplayNoResultsMessage(pContent) {
    //show a no results message
    RemoveMarkers(_mapBar.map, _propertyMarkers);
    _propertyMarkers = [];

    var myNoResultsDiv = document.createElement("div");

    myNoResultsDiv.style.padding = "20px";
    myNoResultsDiv.innerHTML = pContent;


    ClearHeaderAndFooter();
    ReplaceView("CONTENT", myNoResultsDiv);

}; //end function display no results

function ReplaceView(pType, pNode, pOverrideCloseAnyThickBoxes) {
    //Replaces the specified node with the new one
    var myContentNodeToRemove = null;
    var myContentPlaceHolder = null;

    if (pOverrideCloseAnyThickBoxes != true) {
        tb_remove();
    }; //end if not overriding


    //clear the progress bar
    RemoveProgressBar();

    switch (pType) {
        case "HEADER":
            myContentNodeToRemove = $get('HeaderNodeToReplace');
            myContentPlaceHolder = $get('tdHeader');
            GISPlanning_MapUtilities_SetHTMLAttributes(pNode, { id: "HeaderNodeToReplace" });
            break;
        case "FOOTER":
            myContentNodeToRemove = $get('FooterNodeToReplace');
            myContentPlaceHolder = $get('tdFooter');
            GISPlanning_MapUtilities_SetHTMLAttributes(pNode, { id: "FooterNodeToReplace" });
            break;
        case "CONTENT":
            myContentNodeToRemove = $get('ContentPlaceholderNodeToReplace');
            myContentPlaceHolder = $get('tdContentPlaceholder');
            GISPlanning_MapUtilities_SetHTMLAttributes(pNode, { className: "center", id: "ContentPlaceholderNodeToReplace" });
            break;
        case "SUBREPORT":
            myContentNodeToRemove = $('#SubReportNodeToReplace')[0];
            myContentPlaceHolder = $('#tdSubReportPlaceholder')[0];
            GISPlanning_MapUtilities_SetHTMLAttributes(pNode, { className: "center", id: "SubReportNodeToReplace" });
            break;
    }; //end swtich

    myContentPlaceHolder.removeChild(myContentNodeToRemove);
    myContentPlaceHolder.appendChild(pNode);

}; //end function

function DisplaySearchResultsProxy(pPage, pPageSize, pType) {
    //clear the markers from the map and the array
    RemoveMarkers(_mapBar.map, _propertyMarkers);
    _propertyMarkers = [];

    CreateLoadingScreen("CONTENT");

    //set the default page size if not specified
    pPageSize = (pPageSize == null ? _SSR._PageSizeDEFAULT : pPageSize);

    //set the default pType if not specified (paging links do this)
    pType = (pType == null ? _SSR._CurrentViewType : pType);

    var myContentPlaceHolder = $get("tdContentPlaceholder");
    var myClosure = function() {
        return new function() {
            DisplaySearchResults(pPage, pPageSize, _SSR._GetCount(_SSR._CurrentViewType), _mapBar.map, myContentPlaceHolder, _propertyMarkers, _progressBar);
        };
    };


    //check to make sure the page of results exist
    if (_SSR._GetPages(pType)[pPage]) {
        setTimeout(myClosure, 1);
    }
    else {
        _SSR._AdditionalPageCallback = myClosure;
        switch (pType) {
            case "SITES":
                CallSiteSearchService(SearchAdditionalPageSuccess, SearchFail, pPage * _SSR._PageSizeDEFAULT, pPage * _SSR._PageSizeDEFAULT + _SSR._PageSizeDEFAULT);
                break;
            case "COMMUNITY":
                CallCommunitySearchService(SearchAdditionalPageSuccess, SearchFail, pPage * _SSR._PageSizeDEFAULT, pPage * _SSR._PageSizeDEFAULT + _SSR._PageSizeDEFAULT);
                break;
        }; //end switch
    }; //end ifelse page exists


}; //end method




function DisplaySearchResults(pPage, pPageSize, pNumResults, pMap, pContentPlaceHolder, pPropertyMarkers, pProgressBar) {
    var startID = pPage * pPageSize;
    var endID = (pNumResults >= startID + pPageSize) ? startID + pPageSize : pNumResults;
    var myType = _SSR._CurrentViewType;

    //The results table
    _SSR._Table = _SiteSearchResultBuilder.CreateSiteSearchResultsTable();

    //Add the paging
    var mySearchParams = null;
    switch (myType) {
        case "SITES": mySearchParams = GetSiteSearchDisplayParams(); break;
        case "COMMUNITY": mySearchParams = GetCommunitySearchDisplayParameters(); break;
    }

    CreatePagingLinks(_SSR._GetCount(myType), pPageSize, pPage, mySearchParams);

    //add the new table
    ReplaceView("CONTENT", _SSR._Table);

    //Start the progress bar
    pProgressBar.start(endID - startID);

    //set the global page size reference
    _SSR._SetPageSize(pPageSize, myType);
    _SSR._SetCurrentIndex(startID, myType);
    _SSR._SetStopAtIndex(endID, myType);




    //update zoom level by looping thru the results and getting the bounds
    _bounds = new GLatLngBounds();
    var myBoundsShouldBeSet = false;
    var myPage = _SSR._GetCurrentPage(myType);
    var myCurrentIndex = _SSR._GetCurrentIndex(myType);
    var myStopIndex = _SSR._GetStopAtIndex(myType);
    for (var i = myCurrentIndex; i <= myStopIndex; i++) {
        var myResult = _SSR.GetResults(myType)[myPage][i % _SSR._GetPageSize(myType)];
        if (myResult != null) {
            myBoundsShouldBeSet = true;
            var myLatLng = new GLatLng(myResult.lat, myResult.lng);
            _bounds.extend(myLatLng);
        }; //end if result 

    }; //end for each result

    //do the update
    if (myBoundsShouldBeSet) {
        _mapBar.map.setZoom(_mapBar.map.getBoundsZoomLevel(_bounds));
        _mapBar.map.setCenter(_bounds.getCenter());
    }; //end if bounds should be set

    var myCallback = null;
    switch (myType) {
        case "SITES":
            myCallback = function() {
                return new function() {
                    _SiteSearchResultBuilder.CreateSiteSearchResult();
                };
            }; //end method; 
            break;
        case "COMMUNITY":
            myCallback = function() {
                return new function() {
                    _CommunitySearchResultBuilder.CreateCommunitySearchResult();
                };
            }; //end method; 
            break;
        case "SAVED":
            myCallback = function() {
                return new function() {
                    CreateSavedSearchResult();
                };
            }; //end method; 
            break;
    }; //end switchCurrentViewType

    setTimeout(myCallback, 1);

}; //end function


function CreatePagingLinks(pNumberOfRows, pPageSize, pCurrentPage, pSearchParams) {
    var myType = _SSR._CurrentViewType;

    //add the paging links
    var myPagingTable = document.createElement("table");
    GISPlanning_MapUtilities_SetHTMLAttributes(myPagingTable, { cellpadding: 0, cellspacing: 0, border: 0 });
    GISPlanning_MapUtilities_SetHTMLAttributes(myPagingTable.style, { width: "100%" });
    var myFunctionsRow = myPagingTable.insertRow(0);
    var myFunctionRowContainerCell = document.createElement("td");
    GISPlanning_MapUtilities_SetHTMLAttributes(myFunctionRowContainerCell, { align: "right" });
    var myPagesRow = myPagingTable.insertRow(1);
    var myPagingTableContainerCell = document.createElement("td");
    GISPlanning_MapUtilities_SetHTMLAttributes(myPagingTableContainerCell, { align: "left" });
    GISPlanning_MapUtilities_SetHTMLAttributes(myPagingTableContainerCell.style, { backgroundColor: "white" });
    myFunctionsRow.appendChild(myFunctionRowContainerCell);
    myPagesRow.appendChild(myPagingTableContainerCell);


    var myPager = document.createElement("table");
    GISPlanning_MapUtilities_SetHTMLAttributes(myPager, { cellpadding: 0, cellspacing: 0, border: 0 });
    var myFunctions = document.createElement("table");
    GISPlanning_MapUtilities_SetHTMLAttributes(myFunctions, { cellpadding: 0, cellspacing: 0, border: 0 });
    myFunctionRowContainerCell.appendChild(myFunctions);
    myPagingTableContainerCell.appendChild(myPager);

    var myPagingTableRow = myPager.insertRow(0);
    var myFunctionRow = myFunctions.insertRow(0);

    var myPagingResultsFoundCell = document.createElement("td");
    var myPagingPreviousCell = document.createElement("td");
    var myPagingPreviousSeperatorCell = document.createElement("td");
    var myPagingPageCell = document.createElement("td");
    var myPagingResultsCell = document.createElement("td");
    var myPagingNextSeperatorCell = document.createElement("td");
    var myPagingNextCell = document.createElement("td");
    var myPagingViewAllCell = document.createElement("td");
    var myPagingExportCell = document.createElement("td");
    var myPagingSortCell = document.createElement("td");
    var myRefineSearchCell = document.createElement("td");
    var myGroupFunctionCell = document.createElement("td");

    //set styles etc
    myPagingResultsCell.style.paddingRight = "10px";
    myPagingResultsCell.style.paddingLeft = "10px";
    myPagingViewAllCell.style.paddingRight = "10px";
    myPagingViewAllCell.style.paddingLeft = "10px";

    myPagingResultsFoundCell.style.whiteSpace = "nowrap";
    myPagingPreviousCell.style.whiteSpace = "nowrap";
    myPagingPreviousSeperatorCell.style.whiteSpace = "nowrap";
    myPagingPageCell.style.whiteSpace = "nowrap";
    myPagingResultsCell.style.whiteSpace = "nowrap";
    myPagingNextSeperatorCell.style.whiteSpace = "nowrap";
    myPagingNextCell.style.whiteSpace = "nowrap";
    myPagingResultsFoundCell.setAttribute("vAlign", "top");
    myPagingPreviousCell.setAttribute("vAlign", "top");
    myPagingPreviousSeperatorCell.setAttribute("vAlign", "top");
    myPagingPageCell.setAttribute("vAlign", "top");
    myPagingResultsCell.setAttribute("vAlign", "top");
    myPagingNextSeperatorCell.setAttribute("vAlign", "top");
    myPagingNextCell.setAttribute("vAlign", "top");


    myPagingTableRow.appendChild(myPagingResultsFoundCell);
    myPagingTableRow.appendChild(myPagingPreviousCell);
    myPagingTableRow.appendChild(myPagingPreviousSeperatorCell);
    myPagingTableRow.appendChild(myPagingPageCell);
    myPagingTableRow.appendChild(myPagingResultsCell);
    myPagingTableRow.appendChild(myPagingNextSeperatorCell);
    myPagingTableRow.appendChild(myPagingNextCell);
    myPagingTableRow.appendChild(myRefineSearchCell);

    myFunctionRow.appendChild(myGroupFunctionCell);
    myFunctionRow.appendChild(myPagingViewAllCell);
    myFunctionRow.appendChild(myPagingSortCell);
    myFunctionRow.appendChild(myPagingExportCell);


    //figure ot the number of pages and what pages to show (max pages to display at once is 20
    var numPages = (pNumberOfRows - (pNumberOfRows % pPageSize)) / pPageSize + ((pNumberOfRows % pPageSize > 0) ? 1 : 0);
    var myPagePadding = 5;

    //modifiers will allow always 20 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;



    //Setup previous and next
    var myPagingPreviousLink = document.createElement("a");
    GISPlanning_MapUtilities_SetHTMLAttributes(myPagingPreviousLink, { className: "PagingLink", href: "javascript:DisplaySearchResultsProxy(" + (pCurrentPage - 1 > 0 ? pCurrentPage - 1 : 0) + ");", innerHTML: "<<" });
    myPagingPreviousCell.appendChild(myPagingPreviousLink);
    var myPrevLinkIsDisabled = pCurrentPage == 0 ? "none" : "block";
    myPagingPreviousLink.style.display = myPrevLinkIsDisabled;

    var myPagingNextLink = document.createElement("a");
    GISPlanning_MapUtilities_SetHTMLAttributes(myPagingNextLink, { className: "PagingLink", href: "javascript:DisplaySearchResultsProxy(" + (pCurrentPage + 1 < numPages ? pCurrentPage + 1 : numPages - 1) + ");", innerHTML: ">>" });
    myPagingNextCell.appendChild(myPagingNextLink);
    var myNextLinkIsDisabled = pCurrentPage >= numPages - 1 ? "none" : "block";
    myPagingNextLink.style.display = myNextLinkIsDisabled;

    //Add the various text elements to the paging table
    myPagingPreviousSeperatorCell.appendChild(document.createTextNode("|"));
    myPagingNextSeperatorCell.appendChild(document.createTextNode("|"));
    myPagingPageCell.appendChild(document.createTextNode("Page: "));




    //loop thru the results
    for (var i = myStartPage; i < myEndPage; i++) {
        var myPageLink = document.createElement("a");
        GISPlanning_MapUtilities_SetHTMLAttributes(myPageLink.style, { paddingLeft: '1px', paddingRight: '1px' });
        GISPlanning_MapUtilities_SetHTMLAttributes(myPageLink, { className: "PagingLink" });
        //AddMouseOverEffectForLink(myPageLink);


        var myPageStart = i * pPageSize;
        var myPageEnd = (pNumberOfRows >= myPageStart + pPageSize) ? myPageStart + pPageSize : pNumberOfRows;
        var myPageText = (myPageStart + 1) + "-" + myPageEnd;

        if (i != pCurrentPage) {
            GISPlanning_MapUtilities_SetHTMLAttributes(myPageLink, { href: "javascript:DisplaySearchResultsProxy(" + i + ")", innerHTML: i + 1 });
        }
        else {
            //update the top results/viewing link
            myPagingResultsFoundCell.appendChild(document.createTextNode(pNumberOfRows + ' found. Viewing ' + myPageText));

            GISPlanning_MapUtilities_SetHTMLAttributes(myPageLink, { innerHTML: i + 1 });
            myPageLink.style.fontWeight = 'bold';
        }; //end if else current page
        myPagingResultsCell.appendChild(myPageLink);


    }; //end for each page

    //clone the paging table
    var myFooterPagingTable = myPagingTable.cloneNode(true);

    ReplaceView("HEADER", myPagingTable);
    ReplaceView("FOOTER", myFooterPagingTable);




    //add a link to either view paged results or all results
    if (pNumberOfRows != pPageSize) {
        //create a link that lets the user view all results 
        var myViewAllLink = document.createElement("a");
        GISPlanning_MapUtilities_SetHTMLAttributes(myViewAllLink, { className: "tinyButtonLink PagingLink", href: "javascript:ViewAllResults();", innerHTML: "<img src='/common/images/buttons/doublearrows_inactive.png' align='absmiddle'><span>View All</span>" });
        myPagingViewAllCell.appendChild(myViewAllLink);
    }
    else {

        //create a link that lets the user view paged results
        var myViewPagedLink = document.createElement("a");
        GISPlanning_MapUtilities_SetHTMLAttributes(myViewPagedLink, { className: "tinyButtonLink PagingLink", href: "javascript:DisplaySearchResultsProxy(0," + _SSR._PageSizeDEFAULT + ")", innerHTML: "<img src='/common/images/buttons/doubleleft_inactive.png' align='absmiddle'><span>View Paged</span>" });
        myPagingViewAllCell.appendChild(myViewPagedLink);
    }


    //add the links and content to the top row
    var myExportResultsLink = document.createElement("a");
    GISPlanning_MapUtilities_SetHTMLAttributes(myExportResultsLink, { className: "tinyButtonLink PagingLink", href: "javascript:ExportCurrentContent();", innerHTML: "<img src='/common/images/buttons/export_inactive.png' align='absmiddle'><span>Export</span>" });
    myPagingExportCell.appendChild(myExportResultsLink);

    //add the sort by link
    var mySortSpan = document.createElement("span");
    mySortSpan.style.position = "relative";
    var mySortLink = document.createElement("a");
    GISPlanning_MapUtilities_SetHTMLAttributes(mySortLink, { className: "tinyButtonLink PagingLink popupLink", id: "hrefSortBy", title: "Click here to change the sort column", innerHTML: "<img src='/common/images/buttons/sort_inactive.png' align='absmiddle'><span>Sort By</span>" });
    mySortSpan.appendChild(mySortLink);
    myPagingSortCell.appendChild(mySortSpan);

    var mySortByHTML = "";
    switch (myType) {
        case "SITES": mySortByHTML = _SiteSearchResultBuilder.GetSortByHTML(_SSR._GetSortBy(myType)); break;
        case "COMMUNITY": mySortByHTML = _CommunitySearchResultBuilder.GetSortByHTML(_SSR._GetSortBy(myType)); break;
    }; //end switch
    GISPlanning_AddPopup(mySortLink, mySortByHTML);

    //add view specific functions
    if (myType == "COMMUNITY") {
        var myLinkHTML = "\
            <a class='tinyButtonLink' href=\"javascript:SearchPropertiesInCommunitResults()\"\
             title='Click here to search for properties in this community'><img src='/common/images/buttons/property_inactive.png' align='absmiddle'><span>Find Properties in these communities</span></a>";
        myGroupFunctionCell.innerHTML = myLinkHTML;
    }; //end if community

    if (myType == "SAVED") {
        var myLinkHTML = "\
            <a class='tinyButtonLink' href=\"javascript:CompareItems()\"\
             title='Click here to do a comparison of your saved items'><img src='/common/images/buttons/compare_inactive.png' align='absmiddle'><span>Compare</span></a>";
        myGroupFunctionCell.innerHTML = myLinkHTML;
    }; //end if community

    //create the search tickler
    var mySearchTickler = CreateSearchTickler(pSearchParams, myType);
    myRefineSearchCell.appendChild(mySearchTickler);
}

function CreateSearchTickler(pSearchParams, pType) {

    var myRefineSearchFunction = "";
    switch (pType) {
        case "SITES": myRefineSearchFunction = "DisplaySearch(true)"; break;
        case "COMMUNITY": myRefineSearchFunction = "DisplayCommunitySearchForm(true)"; break;
    }; //end switch

    var mySearchTickler = document.createElement("a");
    mySearchTickler.setAttribute("href", "javascript:" + myRefineSearchFunction + ";");
    mySearchTickler.setAttribute("title", "Click here to refine your current search");
    var mySearchTicklerText = "Refine Search: ";
    for (var p in pSearchParams) {
        if (pSearchParams[p] != null && pSearchParams[p] != "") {
            mySearchTicklerText += "<span style='font-weight:bold;'>" + p.replace("_", " ") + "</span>: [<em>" + pSearchParams[p] + "</em>] ";
        }; //end if parameter passed
    }; //end for each parameter
    mySearchTickler.innerHTML = mySearchTicklerText;

    return mySearchTickler;
}; //end function

function SearchFail(error) {
    alert("Failed to retreive results from the search:" + error._message);
    CancelSearch();
}; //end function

function CancelSearch() {
    //TODO: Figure out how to cancel async in progress

    CloseSearchForm();
}; //end function

function SortResults(pWhatField) {
    //clear the markers from the map and the array
    var myType = _SSR._CurrentViewType;
    RemoveMarkers(_mapBar.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(SearchSuccess, SearchFail, 0, _SSR._PageSizeDEFAULT);
            break;
        case "COMMUNITY":
            CallCommunitySearchService(SearchSuccess, SearchFail, 0, _SSR._PageSizeDEFAULT);
            break;
        case "SAVED": alert("Sorting saved results is not implemented yet.");
            break;
    }; //end switch
};

function CloseSearchForm() {
    $("#tblSearchForm").css({ display: "block" });
    $("#tblSearchWaiting").css({ display: "none" });
    $find("mpeSearch").hide();
}; //end method

function ShowSubSearchForm(pWhatForm) {
    var myMainSearchForm = $get("tblSearchForm");
    var mySubSearchForm = GetSubSearchForm(pWhatForm);


    myMainSearchForm.style.display = 'none';
    mySubSearchForm.style.display = 'block';


}; //end method
function ResetClientSearch() {
    $(".PropertyTypeSelectionButton").each(
        function() {
            GISPlanning_SetImageInactive($(this).find("img:first")[0]);
        });
    $get('ctl00_cphModal_tboxMinSize').value = '';
    $get('ctl00_cphModal_tboxMaxSize').value = '';
    $get('ctl00_cphModal_rblSizeType_0').checked = true;
    RemovePoly();

    var mySubForms = ["RAIL", "CEILING", "FINANCE", "ADDRESS", "CITY", "COUNTY", "STATE", "REGION"];
    for (var i = 0; i < mySubForms.length; i++) {
        ResetSubSearchForm(mySubForms[i]);
        UpdateSubSearchIndicator(mySubForms[i]);
    };

    var myPageValid = Page_ClientValidate();

    return false;
}; //end function

function ResetSubSearchForm(pWhatForm) {
    switch (pWhatForm) {
        case "RAIL":
            $get("ctl00_cphModal_rblRailAccess_0").checked = true;
            break;
        case "CEILING":
            $get("ctl00_cphModal_tboxMinCeiling").value = 0;
            $get("hfldCeilingHeightSet").value = false;
            break;
        case "FINANCE":
            $get("ctl00_cphModal_rblFinance_0").checked = true;
            $get("ctl00_cphModal_rblFinance_1").checked = false;
            $get("ctl00_cphModal_rblFinance_2").checked = false;
            break;
        case "ADDRESS":
            $get("ctl00_cphModal_tboxAddress").value = '';
            break;
        case "CITY":
        case "COUNTY":
        case "STATE":
        case "REGION":
            var myFields = GetInputFieldsByGeoEntityType(pWhatForm);
            myFields[0].value = "";
            for (var i = myFields[2].options.length - 1; i >= 0; i--) {
                myFields[2].options.remove(i);
            }; //end for each element

            break;
    }; //end switch
}; //end function

function SubSearchFormValidated(pWhatForm) {

    var myMainSearchForm = $get("tblSearchForm");
    var mySubSearchForm = GetSubSearchForm(pWhatForm);


    myMainSearchForm.style.display = 'block';
    mySubSearchForm.style.display = 'none';

    switch (pWhatForm) {
        case "RAIL":
            //nothing special to do in this case
            break;
        case "FINANCE":

            break;
        case "CEILING":
            $get("hfldCeilingHeightSet").value = true;
            break;
        case "DEMO":

            break;
        case "ADDRESS":

            break;
        case "CITY":

            break;
        case "COUNTY":

            break;
        case "STATE":

            break;
        case "REGION":

            break;
    }; //end switch

    //set image
    UpdateSubSearchIndicator(pWhatForm);
}; //end function

function CloseSubSearchForm(pWhatForm, pIsCancel) {
    var myPageValid = Page_ClientValidate(pWhatForm.toLowerCase());
    if (myPageValid) {
        SubSearchFormValidated(pWhatForm);
    }
}; //end function

function CloseAllSubSearchForms() {
    var mySubForms = ["RAIL", "CEILING", "FINANCE", "ADDRESS", "CITY", "COUNTY", "STATE", "REGION"];
    for (var i = 0; i < mySubForms.length; i++) {
        CloseSubSearchForm(mySubForms[i], false);
    }; //end for each subform
};

function UpdateSubSearchIndicator(pWhatForm) {
    var myValueIsSet = DetermineIfSubSearchCriteriaExist(pWhatForm);
    var myButtonToUpdate = GetSubSearchFormImage(pWhatForm);
    if (myValueIsSet) {
        GISPlanning_SetImageActive(myButtonToUpdate);
    }
    else {
        GISPlanning_SetImageInactive(myButtonToUpdate);
    }; //end ifelse value set
};

function GetSubSearchFormImage(pWhatForm) {
    var myImage = null;
    switch (pWhatForm) {
        case "RAIL":
            myImage = $get("imgRailAccessButton");
            break;
        case "CEILING":
            myImage = $get("imgCeilingHeightButton");
            break;
        case "FINANCE":
            myImage = $get("imgSaleLeaseButton");
            break;
        case "DEMO":
            //Do nothing until this is added
            break;
        case "ADDRESS":
            myImage = $get("imgGeoSubAddress");
            break;
        case "CITY":
            myImage = $get("imgGeoSubCity");
            break;
        case "COUNTY":
            myImage = $get("imgGeoSubCounty");
            break;
        case "STATE":
            myImage = $get("imgGeoSubState");
            break;
        case "REGION":
            myImage = $get("imgGeoSubRegion");
            break;
    }; //end switch

    return myImage;

}; //end function

function DetermineIfSubSearchCriteriaExist(pWhatForm) {
    var myValueIsSet = false;
    switch (pWhatForm) {
        case "RAIL":
            myValueIsSet = $get("ctl00_cphModal_rblRailAccess_0").checked != true;
            break;
        case "CEILING":
            myValueIsSet = $get("ctl00_cphModal_tboxMinCeiling").value > 0;
            break;
        case "FINANCE":
            myValueIsSet = $get("ctl00_cphModal_rblFinance_0").checked != true;
            break;
        case "DEMO":
            //Do nothing until this is added
            break;
        case "ADDRESS":
            myValueIsSet = $get("ctl00_cphModal_tboxAddress").value != '';
            break;
        case "CITY":
            myValueIsSet = GetInputFieldsByGeoEntityType(pWhatForm)[2].options.length > 0;
            break;
        case "COUNTY":
            myValueIsSet = GetInputFieldsByGeoEntityType(pWhatForm)[2].options.length > 0;
            break;
        case "STATE":
            myValueIsSet = GetInputFieldsByGeoEntityType(pWhatForm)[2].options.length > 0;
            break;
        case "REGION":
            myValueIsSet = GetInputFieldsByGeoEntityType(pWhatForm)[2].options.length > 0;
            break;
    }; //end switch

    return myValueIsSet;
}; //end function

function GetSubSearchForm(pWhatForm) {
    var mySubSearchForm;

    switch (pWhatForm) {
        case "RAIL":
            mySubSearchForm = $get("tblRailAccess");
            break;
        case "FINANCE":
            mySubSearchForm = $get("tblFinance");
            break;
        case "CEILING":
            mySubSearchForm = $get("tblCeiling");
            break;
        case "DEMO":
            mySubSearchForm = $get("tblDemographics");
            break;
        case "ADDRESS":
            mySubSearchForm = $get("tblAddress");
            break;
        case "CITY":
            mySubSearchForm = $get("tblCitySelector");
            break;
        case "COUNTY":
            mySubSearchForm = $get("tblCountySelector");
            break;
        case "STATE":
            mySubSearchForm = $get("tblStateSelector");
            break;
        case "REGION":
            mySubSearchForm = $get("tblRegionSelector");
            break;
    }; //end switch

    return mySubSearchForm;
};



function ToggleSaveRemoveProperty(pPropertyID) {
    //Saves or removes the property

    var myResultImage = $get("imgSearchResultIcon_" + pPropertyID);
    var mySaveLink = $get("hrefSaveResult_" + pPropertyID);
    var myMarker = FindPropertyMarker(pPropertyID);
    var myCurrentIcon = myMarker.getIcon();
    var IsSaving = !_SSR.IsResultSaved(pPropertyID);
    var myMarkerImage = myMarker.getIcon().image;
    var myButtonImage = "";

    var myType = pPropertyID.substring(0, pPropertyID.indexOf("_", 0));

    //Save or remove
    if (IsSaving) {
        _SSR.SaveResult(pPropertyID, myType);
        jQuery.noticeAdd({
            text: 'Your result has been saved, you can view it here.',
            stay: false,
            appendTo: '#divSavedResultsCell'
        });
    } else {
        _SSR.RemoveResult(pPropertyID, myType);
    }


    //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", "");
    }

    myMarker.setImage(myMarkerImage); //the standard visual icon change
    myCurrentIcon.image = myMarkerImage; //this is undocumented by google, but basically needed right now so when you mouseout of the icon, it reverts to this new icon
    myResultImage.src = myMarkerImage;

    //Update the buttons
    if (IsSaving) {
        myButtonImage = "/common/images/buttons/cross_inactive.png";
    }
    else {
        myButtonImage = "/common/images/buttons/save_inactive.png";
    }
    mySaveLink.getElementsByTagName("img")[0].src = myButtonImage;


    //update the tooltip
    var myTooltip = !IsSaving ? "Click here to add this property to your save list." : "Click here to remove this property from your save list.";
    mySaveLink.title = myTooltip;

    //update the text
    var myTextSpan = mySaveLink.getElementsByTagName("span")[0];
    myTextSpan.innerHTML = (myTextSpan.innerHTML == "Save" ? "Remove" : "Save");


    //update the info window link (this updates the stored HTML that is rendered when clicking on the icon)
    var myHTML = myMarker.HTML;
    var myWorkingDiv = document.createElement("div");
    myWorkingDiv.innerHTML = myHTML;
    var myLink = myWorkingDiv.getElementsByTagName("a")[1].getElementsByTagName("span")[0];
    var myInnerHTML = myLink.innerHTML == "Save" ? "Remove" : "Save";
    GISPlanning_MapUtilities_SetHTMLAttributes(myLink, { innerHTML: myInnerHTML, title: myTooltip });
    myMarker.HTML = myWorkingDiv.innerHTML;
    //This updates the link if saved from the info window
    var myInfoWindowLink = $get("hrefSaveResultInfoWindow_" + pPropertyID);
    if (myInfoWindowLink != null) {
        var mySpan = myInfoWindowLink.getElementsByTagName("span")[0];
        mySpan.innerHTML = (mySpan.innerHTML == "Save") ? "Remove" : "Save";
    }; //end if not null

}; //end function Save Property



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);


    //if not viewing search results, or all pages are downloaded, then just call the display immediately
    var myDisplayShouldBeCalled = true;

    for (var i = 0; i < numPages; i++) {

        if (!_SSR._GetPages(myType)[i]) {
            myDisplayShouldBeCalled = false;
            if (myType == "SITES") {
                CallSiteSearchService(SiteSearchViewAllSuccess, SearchFail, 0, myTotalRecords);
            }; //end if sites
            if (myType == "COMMUNITY") {
                CallCommunitySearchService(SiteSearchViewAllSuccess, SearchFail, 0, myTotalRecords);
            }; //end if community
            break;
        } //end if page is not downloaded

    }; //end for

    if (myDisplayShouldBeCalled) {
        DisplaySearchResultsProxy(0, myTotalRecords, myType);
    };
};

function SiteSearchViewAllSuccess(pResult) {
    //break this results into pages
    var myResultCount = pResult.Count;
    _SSR.ResetSearchResults(pResult.Type);
    _SSR._SetCount(myResultCount, pResult.Type);
    _SSR._DetermineNumPages(pResult.Type);

    var myTotalPages = _SSR._GetNumPages(pResult.Type);
    var myPageSize = _SSR._GetPageSize(pResult.Type);


    for (var i = 0; i < myTotalPages; i++) {
        var myStartIndex = i * myPageSize;
        var myEndIndex = myStartIndex + myPageSize;
        myEndIndex = (myEndIndex > myResultCount ? myResultCount : myEndIndex);
        _SSR.GetResults(pResult.Type)[i] = pResult.Results.slice(i * myPageSize, myEndIndex);

        _SSR._GetPages(pResult.Type).push(true);
    }; //end for each result

    DisplaySearchResultsProxy(0, pResult.Results.length, pResult.Type);
}; //end function

function CreateLoadingScreen(pType) {
    //show a loading screen
    var myLoadingResultsDiv = document.createElement("div");
    var myLoadingHTML = "<table cellpadding='5'><tr><td><img src='/common/images/lodingOrangeBig.gif' /></td><td style='font-size:12pt;color:#3a1703;'>Loading...</td></tr></table>";
    myLoadingResultsDiv.innerHTML = myLoadingHTML;
    myLoadingResultsDiv.style.padding = "20px";
    myLoadingResultsDiv.className = "center";
    ReplaceView(pType, myLoadingResultsDiv);
};

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;
    }; //end switch sub type
}; //end function

function ShowAddressSubSearch() {
    ShowSubSearchForm("ADDRESS");
};
function ShowCitySubSearch() {
    ShowSubSearchForm("CITY");

    var myFields = GetInputFieldsByGeoEntityType("CITY");
    if (myFields[1].options.length == 0) {
        var myProcessor = function(pResults) {
            var myListBox = myFields[1];
            for (var i = 0; i < pResults.length; i++) {
                var opt = document.createElement("option");
                opt.text = pResults[i].DisplayName;
                opt.value = pResults[i].ID;
                myListBox.options.add(opt);

            };
        };    //end method
        TVAGoogle.common.services.Cities.GetCities(_GISP_Theme,myProcessor);
    }; //end if cities have not been retrieved

    //add the double click events
    $(myFields[1]).unbind("dblclick").bind("dblclick", function() { GISP_AddGeoEntityToSelectList("CITY"); });
    $(myFields[2]).unbind("dblclick").bind("dblclick", function() { GISP_NegateSelectedGeoEntity("CITY"); });

    //Hide autocomplete if google chrome
    
};
function ShowCountySubSearch() {
    ShowSubSearchForm("COUNTY");

    var myFields = GetInputFieldsByGeoEntityType("COUNTY");
    if (myFields[1].options.length == 0) {
        var myProcessor = function(pResults) {
            var myListBox = myFields[1];
            for (var i = 0; i < pResults.length; i++) {
                var opt = document.createElement("option");
                opt.text = pResults[i].DisplayName;
                opt.value = pResults[i].ID;
                myListBox.options.add(opt);
            };
        };    //end method
        TVAGoogle.common.services.Counties.GetCounties(_GISP_Theme,myProcessor);
    }; //end if cities have not been retrieved
    $(myFields[1]).unbind("dblclick").bind("dblclick", function() { GISP_AddGeoEntityToSelectList("COUNTY"); });
    $(myFields[2]).unbind("dblclick").bind("dblclick", function() { GISP_NegateSelectedGeoEntity("COUNTY"); });
};
function ShowStateSubSearch() {
    ShowSubSearchForm("STATE");

    var myFields = GetInputFieldsByGeoEntityType("STATE");
    if (myFields[1].options.length == 0) {
        var myProcessor = function(pResults) {
            var myListBox = myFields[1];
            for (var i = 0; i < pResults.length; i++) {
                var opt = document.createElement("option");
                opt.text = pResults[i].ID;
                opt.value = pResults[i].ID;
                myListBox.options.add(opt);
            };
        };   //end method
        TVAGoogle.common.services.States.GetStates(myProcessor);
    }; //end if cities have not been retrieved

    $(myFields[1]).unbind("dblclick").bind("dblclick", function() { GISP_AddGeoEntityToSelectList("STATE"); });
    $(myFields[2]).unbind("dblclick").bind("dblclick", function() { GISP_NegateSelectedGeoEntity("STATE"); });
};
function ShowRegionSubSearch() {
    ShowSubSearchForm("REGION");

    var myFields = GetInputFieldsByGeoEntityType("REGION");
    if (myFields[1].options.length == 0) {
        var myProcessor = function(pResults) {
            var myListBox = myFields[1];
            for (var i = 0; i < pResults.length; i++) {
                var opt = document.createElement("option");
                opt.text = pResults[i].DisplayName;
                opt.value = pResults[i].ID;
                myListBox.options.add(opt);
            };
        };   //end method
        TVAGoogle.common.services.Regions.GetRegions(myProcessor);
    }; //end if cities have not been retrieved

    $(myFields[1]).unbind("dblclick").bind("dblclick", function() { GISP_AddGeoEntityToSelectList("REGION"); });
    $(myFields[2]).unbind("dblclick").bind("dblclick", function() { GISP_NegateSelectedGeoEntity("REGION"); });
};




function GetInputFieldsByGeoEntityType(pEntityType) {
    var myFields = [];
    switch (pEntityType) {
        case "CITY":
            myFields.push($get("ctl00_cphModal_tboxManualEnterCity"));
            myFields.push($get("ctl00_cphModal_lboxCities"));
            myFields.push($get("ctl00_cphModal_lboxSelectedCities"));
            break;
        case "COUNTY":
            myFields.push($get("ctl00_cphModal_tboxManualEnterCounty"));
            myFields.push($get("ctl00_cphModal_lboxCounties"));
            myFields.push($get("ctl00_cphModal_lboxSelectedCounties"));
            break;
        case "STATE":
            myFields.push($get("ctl00_cphModal_tboxManualEnterState"));
            myFields.push($get("ctl00_cphModal_lboxStates"));
            myFields.push($get("ctl00_cphModal_lboxSelectedStates"));
            break;
        case "REGION":
            myFields.push($get("ctl00_cphModal_tboxManualEnterRegion"));
            myFields.push($get("ctl00_cphModal_lboxRegions"));
            myFields.push($get("ctl00_cphModal_lboxSelectedRegions"));
            break;
    }; //end switch type

    return myFields;
};

function GISP_AddCityGeoEntityToSelectListManually() { GISP_AddGeoEntityToSelectListManually('CITY'); }; //end function
function GISP_AddCountyGeoEntityToSelectListManually() { GISP_AddGeoEntityToSelectListManually('COUNTY'); }; //end functio
function GISP_AddStateGeoEntityToSelectListManually() { GISP_AddGeoEntityToSelectListManually('STATE'); }; //end functionn
function GISP_AddRegionGeoEntityToSelectListManually() { GISP_AddGeoEntityToSelectListManually('REGION'); }; //end function
function GISP_AddGeoEntityToSelectListManually(pEntityType) {
    var myFields = GetInputFieldsByGeoEntityType(pEntityType);
    var mySelectedList = myFields[2];
    var myManaualEnterTextBox = myFields[0];

    var myProcessor = null;


    switch (pEntityType) {
        case "CITY":
            myProcessor = function(pResult) {
                if (pResult != null) {
                    if (!GISP_DetermineIfOptionSelected(mySelectedList, pResult.ID)) {
                        var myOption = document.createElement("option");
                        myOption.text = "[+]" + pResult.DisplayName;
                        myOption.value = pResult.ID;
                        mySelectedList.options.add(myOption);
                    }; //end if not already added
                }
                else {
                    alert("The city you entered was not found. Please try again.");
                }; //end ifelse result null
            };         //end method
            TVAGoogle.common.services.Cities.GetCityCode(myManaualEnterTextBox.value, myProcessor);
            break;
        case "COUNTY":
            myProcessor = function(pResult) {
                if (pResult != null) {
                    if (!GISP_DetermineIfOptionSelected(mySelectedList, pResult.ID)) {
                        var myOption = document.createElement("option");
                        myOption.text = "[+]" + pResult.DisplayName;
                        myOption.value = pResult.ID;
                        mySelectedList.options.add(myOption);
                    }; //end if not already added
                }
                else {
                    alert("The county you entered was not found. Please try again.");
                }; //end ifelse result null
            };         //end method
            TVAGoogle.common.services.Counties.GetCountyCode(myManaualEnterTextBox.value, myProcessor);
            break;
        case "STATE":
            myProcessor = function(pResult) {
                if (pResult != null) {
                    if (!GISP_DetermineIfOptionSelected(mySelectedList, pResult.ID)) {
                        var myOption = document.createElement("option");
                        myOption.text = "[+]" + pResult.ID;
                        myOption.value = pResult.ID;
                        mySelectedList.options.add(myOption);
                    }; //end if not already added
                }
                else {
                    alert("The state you entered was not found. Please try again.");
                }; //end ifelse result null
            };         //end method
            TVAGoogle.common.services.States.GetStateCode(myManaualEnterTextBox.value, myProcessor);
            break;
        case "REGION":
            myProcessor = function(pResult) {
                if (pResult != null) {
                    if (!GISP_DetermineIfOptionSelected(mySelectedList, pResult.ID)) {
                        var myOption = document.createElement("option");
                        myOption.text = "[+]" + pResult.DisplayName;
                        myOption.value = pResult.ID;
                        mySelectedList.options.add(myOption);
                    }; //end if not already added
                }
                else {
                    alert("The region you entered was not found. Please try again.");
                }; //end ifelse result null
            };         //end me
            TVAGoogle.common.services.Regions.GetRegionCode(myManaualEnterTextBox.value, myProcessor);
            break;
    }; //end switch

    //reset the textbox
    myManaualEnterTextBox.value = '';


}; //end function


function GISP_AddGeoEntityToSelectList(pEntityType) {
    var myFields = GetInputFieldsByGeoEntityType(pEntityType);
    var myEntityList = myFields[1];
    var mySelectedList = myFields[2];

    for (var i = 0; i < myEntityList.options.length; i++) {
        if (myEntityList.options[i].selected) {
            //make sure its not already added to the other list before adding it
            if (!GISP_DetermineIfOptionSelected(mySelectedList, myEntityList.options[i].value)) {
                var myOption = document.createElement("option");
                myOption.text = "[+]" + myEntityList.options[i].text;
                myOption.value = myEntityList.options[i].value
                myOption.title = "Double click to exclude this " + pEntityType.toLowerCase();
                mySelectedList.options.add(myOption);
            }; //end if not added
        }; //end if item selected
    }; //end for each element

}; //end function
function GISP_RemoveSelectedGeoEntity(pEntityType) {
    var myFields = GetInputFieldsByGeoEntityType(pEntityType);
    var mySelectedList = myFields[2];

    GISP_RemoveSelectedOptionsFromList(mySelectedList)
}; //end function

function GISP_NegateSelectedGeoEntity(pEntityType) {
    var myFields = GetInputFieldsByGeoEntityType(pEntityType);
    var mySelectedList = myFields[2];

    for (var i = mySelectedList.options.length - 1; i >= 0; i--) {
        var myOption = mySelectedList.options[i];
        if (myOption.selected) {
            if (myOption.text.indexOf("[-]") == -1) {
                myOption.text = myOption.text.replace("[+]", "[-]");
                myOption.title = "Double click to include this " + pEntityType.toLowerCase();
                myOption.className = "geoEntity red";
            } else {
                myOption.text = myOption.text.replace("[-]", "[+]");
                myOption.title = "Double click to exclude this " + pEntityType.toLowerCase();
                myOption.className = "geoEntity";
            }

        }; //end if item selected
    }; //end for each element

}; //end function

function ResearchWithSpecificGeoEntity(pEntity, pType) {
    var myFields = GetInputFieldsByGeoEntityType(pType.toUpperCase());

    ResetSubSearchForm(pType.toUpperCase());

    //Create a processor
    var myProcessor = function(pResults) {
        for (var i = 0; i < pResults.length; i++) {
            if (pResults[i].ID == pEntity) {
                var opt = document.createElement("option");
                opt.text = "[+]" + pResults[i].DisplayName;
                opt.value = pResults[i].ID;
                myFields[2].options.add(opt);
                break;
            }; //end if found
        }; //end for each result
        UpdateSubSearchIndicator(pType.toUpperCase());
        UpdateSearchTickler(pType.toUpperCase());

        //clear the markers from the map and the array
        RemoveMarkers(_mapBar.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(_SSR._CurrentViewType);
        CallSiteSearchService(SearchSuccess, SearchFail, 0, _SSR._PageSizeDEFAULT);
    };  //end method

    //call a service
    switch (pType.toUpperCase()) {
        case "CITY": TVAGoogle.common.services.Cities.GetCities(_GISP_Theme,myProcessor); break;
        case "COUNTY": TVAGoogle.common.services.Counties.GetCounties(_GISP_Theme,myProcessor); break;
        case "STATE": TVAGoogle.common.services.States.GetStates(myProcessor); break;
        case "REGION": TVAGoogle.common.services.Regions.GetRegions(myProcessor); break;
    }; //end switch
};
function AddGeoEntityToSearch(pEntity, pType, pAddOrRemove, pShowSearch) {
    var myFields = GetInputFieldsByGeoEntityType(pType.toUpperCase());

    if (!GISP_DetermineIfOptionSelected(myFields[2], pEntity)) {
        //Create a processor
        var myProcessor = function(pResults) {
            for (var i = 0; i < pResults.length; i++) {
                if (pResults[i].ID == pEntity) {
                    var opt = document.createElement("option");
                    opt.text = "[" + pAddOrRemove + "]" + pResults[i].DisplayName;
                    opt.value = pResults[i].ID;
                    myFields[2].options.add(opt);
                    break;
                }; //end if found
            }; //end for each result
            UpdateSubSearchIndicator(pType.toUpperCase());
            UpdateSearchTickler(pType.toUpperCase());
        }; //end method

        //call a service
        switch (pType.toUpperCase()) {
            case "CITY": TVAGoogle.common.services.Cities.GetCities(_GISP_Theme,myProcessor); break;
            case "COUNTY": TVAGoogle.common.services.Counties.GetCounties(_GISP_Theme,myProcessor); break;
            case "STATE": TVAGoogle.common.services.States.GetStates(myProcessor); break;
            case "REGION": TVAGoogle.common.services.Regions.GetRegions(myProcessor); break;
        }; //end switch
    }; //end if not already added

    if (pShowSearch) {
        DisplaySearch(true);
    };//end if show search
};




function UpdateSearchTickler(pType) {
    //this is a placeholder for now
}; //end function



function GISP_DetermineIfOptionSelected(pList, pValue) {
    var myItemIsAlreadyAdded = false;

    for (var ii = 0; ii < pList.options.length; ii++) {
        if (pList.options[ii].value == pValue) {
            myItemIsAlreadyAdded = true;
            break;
        }; //end if already added
    }; //end for each selected item

    return myItemIsAlreadyAdded;
}; //end function

function GISP_RemoveSelectedOptionsFromList(pList) {
    for (var i = pList.options.length - 1; i >= 0; i--) {
        if (pList.options[i].selected) {
            pList.removeChild(pList.options[i]);
        }; //end if item selected
    }; //end for each element

}; //end function




function ShowSearchResults() {
    var myType = _SSR._LastSearchType;
    _SSR._CurrentViewType = myType;
    SetCurrentTypeButton("SEARCH");
    _SSR.ClearCurrentReportOverlays();
    _SSR._StopProcessCurrentIterativeAsyncResultOperation = false;

    if (_SSR._GetCount(myType) > 0) {
        var myPage = _SSR._GetCurrentPage(_SSR._CurrentViewType);
        DisplaySearchResultsProxy(myPage, null, myType);
    } 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() {
    SetCurrentTypeButton("SAVED");
    _SSR.ClearCurrentReportOverlays();
    _SSR._StopProcessCurrentIterativeAsyncResultOperation = false;

    if (_SSR._GetCount("SAVED") > 0) {
        _SSR._CurrentViewType = "SAVED";
        var myPage = _SSR._GetCurrentPage(_SSR._CurrentViewType)

        DisplaySearchResultsProxy(myPage, null, "SAVED");
    } else {
        DisplayNoResultsMessage("You have not saved any results, once you have saved results, they will be visible here.");
    }
}; //end function Save Property


function ClearHeaderAndFooter() {
    var myNoResultsHeaderDiv = document.createElement("div");
    var myNoResultsFooterDiv = document.createElement("div");
    ReplaceView("HEADER", myNoResultsHeaderDiv);
    ReplaceView("FOOTER", myNoResultsFooterDiv);
}; //end function



function GetTypeButtons() {
    return mySearchButtons = {
        Search: $get('imgSearchResultsTypeButton'),
        Saved: $get('imgSavedResultsTypeButton'),
        Current: $get('imgCurrentReportTypeButton'),
        Reports: $get('imgSavedReportsTypeButton')
    };
}; //end function

function SetCurrentTypeButton(pType) {
    var mySearchButtons = GetTypeButtons();
    for (var button in mySearchButtons) {
        if (button.toUpperCase() == pType.toUpperCase()) {
            GISPlanning_SetImageActive(mySearchButtons[button]);
        } else {
            GISPlanning_SetImageInactive(mySearchButtons[button]);
        }; //end if type
    }; //end for each button

}; //end function


function InteractWithGeoEntity(pID, pType, pValue) {
    var myLink = $get("href" + pType + "_" + pID);
    if (myLink.getElementsByTagName("em").length == 0) {
        var myHTML = "<em>\
                <table>\
                    <tr>\
                        <td style='white-space:nowrap;'><a class='InteractivePopupLink' href='javascript:AddGeoEntityToSearch(\"" + pValue + "\",\"" + pType + "\", \"+\", true);GISPlanning_HidePopup(\"" + myLink.ID + "\");'>Add this " + pType + " to your filter list.</a></td>\
                    </tr>\
                    <tr>\
                        <td style='white-space:nowrap;'><a class='InteractivePopupLink' href='javascript:AddGeoEntityToSearch(\"" + pValue + "\",\"" + pType + "\", \"-\", true);GISPlanning_HidePopup(\"" + myLink.ID + "\");'>Exclude this " + pType + " from your filter list.</a></td>\
                    </tr>\
                    <tr>\
                        <td style='white-space:nowrap;'><a class='InteractivePopupLink' href='javascript:ResearchWithSpecificGeoEntity(\"" + pValue + "\",\"" + pType + "\");GISPlanning_HidePopup(\"" + myLink.ID + "\");'>Re-search using only this " + pType + ".</a></td>\
                    </tr>\
                </table>\
            </em>";

        $(myLink).append(myHTML);

        $(myLink).hover(function() { }, function() {
            $(this).find("em").animate({ opacity: "hide" }, "fast");
        });
    }; //end if em has not been added


    //show menu
    $(myLink).find("em").animate({ opacity: "show" }, "slow");

};

function InteractWithDemographicReport(pID, pBaseClientID) {
    var myLink = $get(pBaseClientID + pID);
    if (myLink.getElementsByTagName("em").length == 0) {
        var myHTML = "<em>\
                <table style='color:black;'>\
                    <tr>\
                        <td style='white-space:nowrap'><input type='radio' id='rbDemo0_" + pBaseClientID + pID + "' name='demoSelect_" + pBaseClientID + pID + "' value='CONSUMERSPENDING' onclick=\"ViewDemographicReport('" + pID + "','CONSUMERSPENDING')\"/></td><td>Consumer Expenditure</td>\
                    </tr>\
                    <tr>\
                        <td style='white-space:nowrap'><input type='radio' id='rbDemo1_" + pBaseClientID + pID + "' name='demoSelect_" + pBaseClientID + pID + "' value='DEMOGRAPHICS' onclick=\"ViewDemographicReport('" + pID + "','DEMOGRAPHICS')\"/></td><td>DEMOGRAPHICS</td>\
                    </tr>\
                     <tr>\
                        <td style='white-space:nowrap'><input type='radio' id='rbDemo2_" + pBaseClientID + pID + "' name='demoSelect_" + pBaseClientID + pID + "' value='LABORFORCE' onclick=\"ViewDemographicReport('" + pID + "','LABORFORCE')\"/></td><td>LABORFORCE</td>\
                    </tr>\
                </table>\
            </em>";

        $(myLink).append(myHTML);

        $(myLink).hover(function() { }, function() {
            $(this).find("em").animate({ opacity: "hide" }, "fast");
        });
    }; //end if em has not been added


    //show menu
    $(myLink).find("em").animate({ opacity: "show" }, "slow");

};



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;
        }; //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() {
    GISPlanning_MapUtilities_RegisterScript("/common/scripts/ComparisonReport.js");
    $get("tblComparisons").style.display = "none";
    $get("tblComparisonsLoading").style.display = "block";
    $find("mpeComparisons").show();
    setTimeout(DisplayComparisonItemsWhenScriptLoaded, 10);

}; //end function
function CloseComparison() {
    DisplayInlineTable("tblComparisons");
    $get("tblComparisonsLoading").style.display = "none";
    $find("mpeComparisons").hide();
}; //end function
function DisplayComparisonItemsWhenScriptLoaded() {
    if (typeof (ComparisonReporter) == "undefined") {
        setTimeout(DisplayComparisonItemsWhenScriptLoaded, 10);
    } else {
        SetupComparisonWindow();
    }; //end if loaded
}; //end function


function ExportCurrentContent() {
    //get the content and create a generic report
    var myContent = $('#ContentPlaceholderNodeToReplace').clone()[0];
    GISP_RemoveNonExportable(myContent);
    var myReportID = CreateResultsReport(myContent);

    ExportReport(myReportID);
}; //end method