﻿function GISPlanning_SearchResults() {
    var me = this;

    this._SavedResultsIndex = [];  //a one dimensional array of the IDS of all the saved results
    this._StopProcessCurrentIterativeAsyncResultOperation = false; //set this flag to interrupt the processing of search results;

    this._Table = null;
    this._PageSizeDEFAULT = 26; //Do not modify this value

    this.Tracker = function (pDefaultPageSize) {
        var me = this;
        this.Results = []; //an array of pages of results
        this.Count = 0;
        this.CurrentIndex = 0;
        this.PageSize = 26;
        this.StopAtIndex = 0;
        this.NumPages = 0;
        this.SortBy = "default";
        this.Pages = [];
        this.PageSizeDefault = pDefaultPageSize;
        this.CurrentlyMapped = []; //unique id of item
        this.CurrentlyViewable = []; //list of index of items viewable
        this.CurrentlyNeedsUpdating = []; //list of index of items with temp cards
        this.IsNewSearch = true;
        this.CurrentOrders = [];
        this.SlideDirection = 1;
        this.SearchParameters = {};
        this.ResultOrientation = _ZPEDefaultOrientation; // defined in master page

        this.Reset = function () {
            me.Results = [];
            me.Count = 0;
            me.CurrentIndex = 0;
            me.NumPages = 0;
            me.PageSize = me.PageSizeDefault;
            me.Pages = [];
            me.StopAtIndex = 0;
            me.CurrentlyMapped = [];
            me.CurrentlyNeedsUpdating = [];
            me.IsNewSearch = true;
            me.CurrentOrders = [];
            me.SlideDirection = 1;
            me.SearchParameters = {};
            //me.ResultOrientation = "vertical"; (note, this should be maintained between searches)
        }; //end method
    };

    this._SitesTracker = new this.Tracker(me._PageSizeDEFAULT);
    this._BuildingsTracker = new this.Tracker(me._PageSizeDEFAULT);
    this._CommunitiesTracker = new this.Tracker(me._PageSizeDEFAULT);
    this._BusinessesTracker = new this.Tracker(me._PageSizeDEFAULT);
    this._SavedSitesTracker = new this.Tracker(me._PageSizeDEFAULT);
    this._SavedBuildingsTracker = new this.Tracker(me._PageSizeDEFAULT);
    this._SavedCommunitiesTracker = new this.Tracker(me._PageSizeDEFAULT);
    this._SavedBusinessesTracker = new this.Tracker(me._PageSizeDEFAULT);
    this._ReportsTracker = new this.Tracker(me._PageSizeDEFAULT);
    this._PointsTracker = new this.Tracker(me._PageSizeDEFAULT);

    this._CommunitiesTracker.SortBy = "ID"; //note, this is the default value for this type of search

    this._Trackers = {
        SITES: this._SitesTracker,
        BUILDINGS: this._BuildingsTracker,
        COMMUNITIES: this._CommunitiesTracker,
        BUSINESSES: this._BusinessesTracker,
        REPORTS: this._ReportsTracker,
        REPORTS_SAVED: this._ReportsTracker,
        SITES_SAVED: this._SavedSitesTracker,
        BUILDINGS_SAVED: this._SavedBuildingsTracker,
        COMMUNITIES_SAVED: this._SavedCommunitiesTracker,
        BUSINESSES_SAVED: this._SavedBusinessesTracker,
        POINTS: this._PointsTracker
    };


    this._CurrentReportID = null;
    this._Reports = [];
    this._SavedReports = [];

    this._NavigationHistory = [];
    this._CurrentViewClass = "RESULTS"; //||or REPORT, this controls the pan featuere and the resize window behavior
    this._CurrentViewType = "BUILDINGS"; //"SITES","COMMUNITY" etc.
    this._LastSearchType = "BUILDINGS";
    this._IsBackTracking = false;

    this._AdditionalPageCallback = [];

    this.GeoEntities = {}; //holds list of geoentities for searching (cities, counties, states etc)


    //==============Callbacks================/
    this.AddCallback = function (pRequestID, pCallback) {
        me._AdditionalPageCallback.push({ RequestID: pRequestID, Callback: pCallback });
    };      //end function

    this.FindCallback = function (pRequestID) {
        var myReturnVal = -1;
        $.each(me._AdditionalPageCallback,
            function (i, val) {
                if (val.RequestID == pRequestID) {
                    myReturnVal = i;
                    return false;
                } //end if found
            }
        ); //end for each callback

        return myReturnVal;
    };

    this.RemoveCallback = function (pRequestID) {
        var myIndex = me.FindCallback(pRequestID);
        if (myIndex != -1) {
            me._AdditionalPageCallback.splice(myIndex, 1);
        }

    };      //end function

    this.ExecuteCallback = function (pRequestID, pOptions) {
        var myIndex = me.FindCallback(pRequestID);
        me._AdditionalPageCallback[myIndex].Callback(pOptions);
    };       //end function

    //SEARCH RESULTS****************************************************************************************************************************************

    this.GetResults = function (pType) {
        return me._Trackers[pType].Results;
    }; //end function

    this._SetSearchResults = function (pResults) {
        var myType = pResults.Type;
        me._Trackers[myType].Count = pResults.Count;
        me._DetermineNumPages(myType);

        //fill the results with empty items
        var getCount = me._GetCount(myType);
        for (var i = 0; i < getCount; i++) {
            me._Trackers[myType].Results.push(false);
        } //end for each result

        //fill in the return results
        var resultsLength = pResults.Results.length;
        for (var j = 0; j < resultsLength; j++) {
            me._Trackers[myType].Results[j] = pResults.Results[j];
        } //end for each result

        me._Trackers[myType].SearchParameters = pResults.InputParameters;

    };         //end function

    this._CheckPage = function (pValue, pType) {
        //verify all results within that page exist
        var myResultsAreThere = true;
        var myResults = me.GetResults(pType);
        var myPageSize = me._GetPageSize(pType);
        var myStartResult = myPageSize * pValue;
        var myEndResult = myStartResult + myPageSize;
        for (var i = myStartResult; i < myEndResult; i++) {
            if (!myResults[i]) {
                myResultsAreThere = false;
                break;
            } //end if false found
        } //end for each result

        return myResultsAreThere;
    };

    this._AddResults = function (pResultsToAdd, pStartRowID, pType) {
        //add the Range of Results
        var myResults = me.GetResults(pType);
        var myStartResult = pStartRowID;
        var myEndResult = pStartRowID + pResultsToAdd.length;
        for (var i = myStartResult; i < myEndResult; i++) {
            myResults[i] = pResultsToAdd[i - myStartResult];
        } //end for each result
    };

    this._AddResult = function (pResult, pType) {
        //determine if last page is full
        var myResultCollection = me._Trackers[pType].Results;

        myResultCollection.push(pResult);

    };

    this._DetermineNumPages = function (pType) {

        //set up the pages
        me._SetNumPages((me._GetCount(pType) - (me._GetCount(pType) % me._GetPageSize(pType))) / me._GetPageSize(pType) + ((me._GetCount(pType) % me._GetPageSize(pType) > 0) ? 1 : 0), pType);

    }; //end function

    this._GetCount = function (pType) { return me._Trackers[pType].Count; };
    this._GetCurrentIndex = function (pType) { return me._Trackers[pType].CurrentIndex; };
    this._GetPageSize = function (pType) { return me._Trackers[pType].PageSize; };
    this._GetPages = function (pType) { return me._Trackers[pType].Pages; };
    this._GetStopAtIndex = function (pType) { return me._Trackers[pType].StopAtIndex; };
    this._GetNumPages = function (pType) { return me._Trackers[pType].NumPages; };
    this._GetSortBy = function (pType) { return me._Trackers[pType].SortBy; };
    this._IsNewSearch = function (pType) { return me._Trackers[pType].IsNewSearch; };
    this._GetCurrentPage = function (pType) {
        return Math.floor((me._GetCurrentIndex(pType)) / me._GetPageSize(pType));
    };
    this._GetFirstResult = function (pType) { return me._Trackers[pType].Results[0]; };

    this._SetCount = function (pValue, pType) { me._Trackers[pType].Count = pValue; };
    this._SetCurrentIndex = function (pValue, pType) { me._Trackers[pType].CurrentIndex = pValue; };
    this._SetPageSize = function (pValue, pType) {
        me._Trackers[pType].PageSize = pValue;
        me._Trackers[pType].PageSizeDefault = pValue;
    };
    this._SetStopAtIndex = function (pValue, pType) { me._Trackers[pType].StopAtIndex = pValue; };
    this._SetNumPages = function (pValue, pType) { me._Trackers[pType].NumPages = pValue; };
    this._SetIsNewSearch = function (pValue, pType) { me._Trackers[pType].IsNewSearch = pValue; };

    this._SetSortBy = function (pValue, pType) { me._Trackers[pType].SortBy = pValue; };


    this._DetermineIfOrderExists = function (pValue, pType) {
        var myOrders = _SSR._Trackers[pType].CurrentOrders;
        var myOrderExists = false;
        for (var i = 0; i < myOrders.length; i++) {
            if (myOrders[i].Start == pValue.Start && myOrders[i].Stop == pValue.Stop) {
                myOrderExists = true;
                break;
            }
        } //end for each current order

        return myOrderExists;
    };  //end function

    this._DetermineIfNeedsUpdatingExists = function (pValue, pType) {
        var myNeeds = _SSR._Trackers[pType].CurrentlyNeedsUpdating;
        var myNeedExists = false;
        for (var i = 0; i < myNeeds.length; i++) {
            if (myNeeds[i] == pValue) {
                myNeedExists = true;
                break;
            }
        } //end for each need

        return myNeedExists;
    };  //end function


    this.GetResultByID = function (pID, pType) {
        log.info("GetResultByID() ID: " + pID + " Type: " + pType);
        //Because results is an array of arrays, it can be difficut to find the item so this method does it for you
        var myFoundResult = null;
        var myResults = me.GetResults(pType);
        var myResultsLength = myResults.length;
        log.info("- Results Length: " + myResults.length);

        for (var i = 0; i < myResultsLength; i++) {
            if (myResults[i].ID == pID) {
                log.info("- Found result in SSR");
                myFoundResult = myResults[i];
                break;
            } //end if match
        } //end for each result in a page

        return myFoundResult;
    };   //end method

    this.GetResultByIndex = function (pIndex, pType) {
        return me.GetResults(pType)[pIndex];
    };   //end function


    this.SetTrackerIndexToCurrentReport = function (pType) {

        var myResults = me.GetResults(pType);
        var myCurrentID = me.GetCurrentReport().ID;
        for (var i = 0; i < myResults.length; i++) {
            if (myResults[i].ID == myCurrentID) {
                me._Trackers[pType].CurrentIndex = i;
                break;
            } //end if match
        } //end for each result in a page
    };         //end function

    this.SaveResult = function (pID, pType) {
        //find the result
        var myTrackerType = pType + "_SAVED";
        var myResult = me.GetResultByID(pID, pType);
        if (myResult !== null) {
            //adds a copy to the appropriate saved tracker
            me._Trackers[myTrackerType].Results.push($.extend(true, {}, myResult));
            //increment the count
            me._Trackers[myTrackerType].Count++;

            //updates a generic index of all saved items
            me._SavedResultsIndex.push(myResult.ID);
        } //end if result found
    };       //end method

    this.RemoveResult = function (pID, pType) {
        //find the result
        var myItemIndex = -1;
        var myTrackerType = pType.replace(/_SAVED/g, '') + "_SAVED";
        var myResults = me._Trackers[myTrackerType].Results;


        for (var i = 0; i < myResults.length; i++) {
            if (myResults[i].ID == pID) {
                myItemIndex = i;
                break;
            } //end if match
        } //end for each page

        //remove it
        if (myItemIndex > -1) {
            myResults.splice(myItemIndex, 1);

            me.DeleteFromSavedResultIndex(pID);

            //deincreament the count
            me._Trackers[myTrackerType].Count--;
            me.UpdateMyFolder();
        } //end if found
    };        //end method

    this.DeleteFromSavedResultIndex = function (pID) {
        //find the index value and remove it
        var myIndexIndex = 0;
        for (var i = 0; i < me._SavedResultsIndex.length; i++) {
            if (me._SavedResultsIndex[i] == pID) {
                myIndexIndex = i;
            } //end if found
        } //end for each index item

        me._SavedResultsIndex.splice(myIndexIndex, 1);
    };


    this.IsResultSaved = function (pID) {
        var myReturnValue = false;
        for (var i = 0; i < me._SavedResultsIndex.length; i++) {
            if (me._SavedResultsIndex[i] == pID) {
                myReturnValue = true;
                break;
            } //end if found
            if (myReturnValue === true) { break; }
        } //end for each saved result

        return myReturnValue;
    };        //end method

    this.ResetSearchResults = function (pType) {
        me._Trackers[pType].Reset();
        me._AdditionalPageCallback = [];
    };            //end method


    //TRACKERS******************************************************************************************************************************
    this.ResetTracker = function (pType) {
        me._Trackers[pType].Reset();
    }; //end method



    //REPORTS*******************************************************************************************************************************
    this.GetReportByUniqueID = function (pUniqueID, refIndexOfReport) {
        if (typeof (pUniqueID) === "undefined" || pUniqueID === null) {
            log.error("GetReportByUniqueID(). UniqueID: " + pUniqueID + " refIndexOfReport: " + refIndexOfReport);
        }
        var myReport = null;
        if (typeof (refIndexOfReport) === "undefined" || refIndexOfReport === null) {
            refIndexOfReport = {};
        } //end if refIndexOfReport is null

        for (var i = 0; i < me._Reports.length; i++) {
            if (me._Reports[i].UniqueID == pUniqueID) {
                myReport = me._Reports[i];
                refIndexOfReport.value = i;
                break;
            } //end if found
        }    //end for each report

        return myReport;
    };               //end function

    this.GetCurrentReport = function () {
        return me.GetReportByUniqueID(me._CurrentReportID);
    };

    this.GetReportByTypeAndID = function (pType, pID) {
        return FindFirstReportInCollectionByTypeAndID(pType, pID, me._Reports);
    };         //end function


    this.LoadReportOverlays = function (pUniqueReportID) {
        var myReport = me.GetReportByUniqueID(pUniqueReportID);
        if (myReport !== null) {
            for (var o in myReport.Overlays) {
                if (myReport.Overlays[o] !== null) {
                    myReport.Overlays[o].setMap(map);
                }//end if not null
            }//end for each overlay
        }//end if report not null
    };//end function

    this.ClearReportOverlays = function (pUniqueID) {
        var myReport = me.GetReportByUniqueID(pUniqueID);
        if (myReport !== null) {
            for (var o in myReport.Overlays) {
                if (myReport.Overlays[o] !== null) {
                    myReport.Overlays[o].setMap(null);
                    google.maps.event.clearListeners(myReport.Overlays[o]);
                    if (myReport.Type == "BUSINESS") {
                        _businessMap.hide();
                    }
                }
            } //end for each overlay
        }
    };

    this.ClearCurrentReportOverlays = function () {
        var myReport = me.GetReportByUniqueID(me._CurrentReportID);

        if (myReport !== null) {
            me.ClearReportOverlays(myReport.UniqueID);
            //Clear any subreport overlays. NOTE: this is not iterative, will not clear a subreports subreport if one exists
            for (var subReport in myReport.SubReports) {
                me.ClearReportOverlays(myReport.SubReports[subReport]);
            } //end for each subreport
        } //end if report
    };

    this.ClearOtherReportOverlays = function () {
        if (typeof RemoveAllPinpoints != "undefined") { RemoveAllPinpoints(); }  // from Identify.js
        
        for (var i = 0; i < this._Reports.length; i++) {
            if (this._Reports[i].ID === "") {
                if (this._Reports[i].Type == "COMMUNITY") {
                    this.ClearReportOverlays(this._Reports[i].Parameters.ID);
                }
            }//end if the report does not have an ID
            else {
                if (this._Reports[i].ID != this._CurrentReportID) {
                    this.ClearReportOverlays(this._Reports[i].ID);
                }//end if not current report
            }//end if the report does have an ID
        }//end for each report
    }//end function

    this.AddReport = function (pReport) {
        log.info("_SSR.AddReport() ReportID: " + pReport.ID);
        var alreadyAdded = false;
        for (var i = 0; i < this._Reports.length; i++) {
            if (this._Reports[i].ID == pReport.ID) {
                log.info("- Report was already added");
                alreadyAdded = true;
                break;
            }
        }
        if (!alreadyAdded) {
            log.info("- Report was not already added, pushing onto _Reports array");
            me._Reports.push(pReport);
        }

    };

    this.DeleteReport = function (pUniqueReportID) {
        var myReportIndex = {};
        var myReport = me.GetReportByUniqueID(pUniqueReportID, myReportIndex);
        myReport.Dispose();
        if (myReportIndex.value != -1) {
            me._Reports[myReportIndex.value] = null;
            me._Reports.splice(myReportIndex.value, 1);
        } //end if report found

        //remove the reportID from the saved list
        var mySavedReportIndex = me.GetSavedReportIndex(pUniqueReportID);
        if (mySavedReportIndex != -1) {
            me._Trackers["REPORTS_SAVED"].Results.splice(mySavedReportIndex, 1);
            me._Trackers["REPORTS_SAVED"].Count = me._Trackers["REPORTS_SAVED"].Results.length;
            me._SavedResultsIndex.splice(mySavedReportIndex, 1);
            me.UpdateMyFolder();
        } //end if saved
    };

    this.GetSavedReportIndex = function (pUniqueReportID) {
        var myIndex = -1;
        for (var i = 0; i < me._Trackers["REPORTS_SAVED"].Results.length; i++) {
            if (me._Trackers["REPORTS_SAVED"].Results[i].ID == pUniqueReportID) {
                myIndex = i;
                break;
            }
        }

        return myIndex;
    };            //end function

    this.DeleteReportIfNotSaved = function (pUniqueReportID) {
        if (me.GetSavedReportIndex(pUniqueReportID) == -1) {
            me.DeleteReport(pUniqueReportID);
        } //end if not saved
    };

    this.SaveReport = function (pUniqueReportID) {
        if (me.GetSavedReportIndex(pUniqueReportID) == -1) {
            var myParentReport = _SSR.GetCurrentReport();
            var myResult = _SSR.GetResultByID(myParentReport.ID, myParentReport.Type);
            var myReport = _SSR.GetReportByUniqueID(pUniqueReportID);
            //todo: pass in additional properties to the saved sub-report (lat, lng, etc)
            me._Trackers["REPORTS_SAVED"].Results.push({ ID: pUniqueReportID,
                lat: myParentReport.Parameters.Lat,
                lng: myParentReport.Parameters.Lng,
                Radius: myReport.Parameters.Radius,
                DriveTime: myReport.Parameters.DriveTime,
                type: myParentReport.Type,
                SubType: myReport.Type,
                Thumbnail: myResult.Thumbnail,
                PropertyID: myResult.ID
            });
            me._Trackers["REPORTS_SAVED"].Count = me._Trackers["REPORTS_SAVED"].Results.length;
            me._SavedResultsIndex.push(pUniqueReportID);
            me.UpdateMyFolder();
        }
    };            //end function


    //*******************COMMUNITIES
    this._SetCommunityResults = function (pResults) {
        me._Commnites[0] = pResults.Results;
        me._CommunityCount = pResults.Count;
        me._DetermineNumPages("COMMUNITY");

        //fill the pages collection with empty pages
        for (var i = 0; i < me._SitesTracker.NumPages; i++) {
            me._SitePages.push(false);
        } //end for each page

        //since this is always the first page, set to true
        me._SitePages[0] = true;
    };    //end function


    //============NAVIGATION=================
    this.NavigationHistory_Add = function (pViewType, pTrackerType, pTrackerIndex, pCallParameter) {
        if (!me._IsBackTracking) {
            var lastVisitData = me._NavigationHistory[me._NavigationHistory.length - 1];
            if ((typeof (lastVisitData) !== 'undefined' && lastVisitData !== null) && lastVisitData.ViewType == pViewType && lastVisitData.TrackerType == pTrackerType) {
                lastVisitData.Index = pTrackerIndex;
                lastVisitData.CallParameter = pCallParameter;
            }
            else {
                me._NavigationHistory.push({ ViewType: pViewType, TrackerType: pTrackerType, Index: pTrackerIndex, CallParameter: pCallParameter });
            }
        }
    };

    this.NavigationHistory_Remove = function () {
        me._IsBackTracking = true;
        me._NavigationHistory.pop(); // discard current step
        return me._NavigationHistory[me._NavigationHistory.length - 1]; // return last step but keep it
    };

    this.GoBack = function (pStepCount) {
        //this function will attempt to act like the back button and date the appropriate action based on the  this._NavigationHistory.push({ Tracker: pType, Index: pIndex });
        //pStepCount indicates how far back in NavigationHistory to go
        if (pStepCount === null) {
            pStepCount = 1;
        }
        var myNavInfo;
        for (var i = 0; i < pStepCount; i++) {
            myNavInfo = me.NavigationHistory_Remove();
            if (me._NavigationHistory.length === 0) {
                break;
            }
        }

        var myTracker = me._Trackers[myNavInfo.TrackerType];
        if (typeof (myTracker) === "undefined" || myTracker === null) {
            return;
        }
        myTracker.CurrentIndex = myNavInfo.Index;

        _SSR._CurrentViewType = myNavInfo.TrackerType; //cfurrow

        switch (myNavInfo.TrackerType) {
            case "BUILDINGS":
            case "SITES":
                if (myNavInfo.ViewType === "REPORT") {
                    ViewPropertyReport(myNavInfo.CallParameter, myNavInfo.TrackerType);
                }
                else if (myNavInfo.ViewType === "POINTS") {
                    var doesNothing = true;
                }
                else {
                    ShowSearchResults(myNavInfo.TrackerType);
                }
                break;
            case "BUILDINGS_SAVED":
            case "SITES_SAVED":
            case "COMMUNITIES_SAVED":
            case "BUSINESSES_SAVED":
            case "REPORTS_SAVED":
                if (myNavInfo.ViewType == "REPORT") {
                    ViewPropertyReport(myNavInfo.CallParameter, myNavInfo.TrackerType);
                }
                else {
                    ShowSavedResults(myNavInfo.TrackerType.split('_')[0]);
                }
                break;
            case "COMMUNITIES":
                if (myNavInfo.ViewType == "REPORT") {
                    ViewCommunityReport(myNavInfo.CallParameter, myNavInfo.TrackerType);
                }
                else {
                    ShowSearchResults(myNavInfo.TrackerType);
                }
                break;
            case "BUSINESSES":
                ShowSearchResults(myNavInfo.TrackerType);
                break;
            case "POINTS":
                var myLink = "/main/PropertyDetails.aspx?ID=" + myNavInfo.CallParameter;
                myLink += "&SST=" + _GISP_Theme + "&ReportType=POINTS";
                myLink += "&UniqueID=" + myNavInfo.CallParameter;
                myLink += "&tab=LABORFORCE";
                DisplayReport(myLink, myNavInfo.CallParameter);
                break;

            default: break;
        } //end switch


    };              //end function

    this.GetNavBackText = function (pStep) {

        var myReturnText = "";
        if (pStep > 0) {
            var myNavInfo = me._NavigationHistory[pStep - 1]; // entry n-1 in nav history
            switch (myNavInfo.TrackerType) {
                case "BUILDINGS":
                    if (myNavInfo.ViewType == "REPORT") {
                        myReturnText = "Property Report";
                    }
                    else {
                        myReturnText = "Search Results (Buildings)";
                    }
                    break;
                case "SITES":
                    if (myNavInfo.ViewType == "REPORT") {
                        myReturnText = "Property Report";
                    }
                    else {
                        myReturnText = "Search Results (Sites)";
                    }
                    break;
                case "BUILDINGS_SAVED":
                    myReturnText = "My Folder (Buildings)";
                    break;
                case "SITES_SAVED":
                    myReturnText = "My Folder (Sites)";
                    break;
                case "REPORTS_SAVED":
                    myReturnText = "My Folder (Reports)";
                    break;
                case "COMMUNITIES":
                    if (myNavInfo.ViewType == "REPORT") {
                        myReturnText = "Community Report";
                    }
                    else {
                        myReturnText = "Search Results (Community)";
                    }
                    break;
                case "COMMUNITIES_SAVED":
                    myReturnText = "My Folder (Community)";
                    break;
                case "BUSINESSES_SAVED":
                    myReturnText = "My Folder (Business)";
                    break;
                case "BUSINESSES":
                    myReturnText = "Search Results (Business)";
                    break;
                case "POINTS":
                    myReturnText = "Pinpoint Report";
                    break;
                default: break;
            } //end switch
        } //end if nav history
        me._IsBackTracking = false;

        return myReturnText;
    };      //end method

    this.GetHistoryLink = function () {
        var myBackLinks = [];
        var myHistoryDepth = me._NavigationHistory.length;

        if (myHistoryDepth > 2) {

            var myIndex = 2;
            for (var i = myHistoryDepth - 1; i > 1; i--) {
                myBackLinks.push("<li><a style='background-color:transparent;' href='javascript:_SSR.GoBack(" + myIndex + ");'>Back to " + me.GetNavBackText(i - 1) + "</a></li>");
                myIndex++;
            }

            var result = "";
            result += "<ul class='historyNavigation contentTools'>";
            result += "  <li class='ContentToolsItem'><a style='background-color:transparent;' href='javascript:_SSR.GoBack(1);' title='Go Back'>Back to " + me.GetNavBackText(myHistoryDepth - 1) + "</a>";
            result += "     <ul class='popDownMenu fragment'>";
            result += myBackLinks.join('\n');
            result += "     </ul>";
            result += "  </li>";
            result += "</ul>";
            return result;
        }
        else {
            var navBackText = me.GetNavBackText(myHistoryDepth - 1);
            var linkText = linkText = "Back to " + navBackText;
            return "<ul class='historyNavigation contentTools'><a style='background-color:transparent;' href='javascript:_SSR.GoBack(1);' title='Go Back'>" + linkText + "</a></ul>";
        }
    };


    this.UpdateMyFolder = function () {
        $("#myFolder_sites").text(_SSR._Trackers["SITES_SAVED"].Count);
        $("#myFolder_buildings").text(_SSR._Trackers["BUILDINGS_SAVED"].Count);
        $("#myFolder_reports").text(_SSR._Trackers["REPORTS_SAVED"].Count);
        $("#myFolder_communities").text(_SSR._Trackers["COMMUNITIES_SAVED"].Count);
        $("#myFolder_businesses").text(_SSR._Trackers["BUSINESSES_SAVED"].Count);

        //animate open the folder, then calls close after 2 seconds
        AnimateMyFolderOpen(function () { setTimeout(AnimateMyFolderClosed, 2000); });
    };
} //GISPlanning_SearchResults


function AnimateMyFolderOpen(pCallback) {
    //animate open the folder if not already animating open, then calls close after 2 seconds
    if (!$("#myFolder").hasClass("animatingOpen")) {
        $("#myFolder").addClass("animatingOpen");
        $("#myFolderMenu").show("slow", pCallback);
    }
}

function AnimateMyFolderClosed() {
    //remove the class that is is animating open
    $("#myFolder").removeClass("animatingOpen");

    //if the user does not have their mouse on the menu or folder, close the window
    if (!$("#myFolder").hasClass("current")) {
        $("#myFolderMenu").hide("slow");
    }
}

function UpdateDisplayedWithMyFolderData(pReportID) {

    var myMarker = FindPropertyMarker(pReportID);

    if (myMarker === null) {
        return;
    }

    var myCurrentIcon = myMarker.getIcon();
    var myMarkerImage = myMarker.getIcon().url;
    var myButtonImage = "";

    //update the property icon on the map and the display listing
    var myIndexOfLastSlash = myMarkerImage.lastIndexOf('.');
    myMarkerImage = myMarkerImage.substr(0, myIndexOfLastSlash) + "_on" + myMarkerImage.substr(myIndexOfLastSlash, myMarkerImage.length - myIndexOfLastSlash);
    setMarkerSavedImage(myMarker, myMarkerImage);

    //update the property listing
    $("#" + pReportID + " .savedDecorator").addClass("saved");
    $("#" + pReportID + " .saveLink").text("Remove");
    $("#" + pReportID + " .saveToFrom").text("from");

    // find link in marker, in the page's DOM-tree
    var $mymarker_link = $("#hrefSaveResultInfoWindow_" + pReportID);
    // find the link in the marker's HTML property
    var $mymarker_html_link = $("#hrefSaveResultInfoWindow_" + pReportID, myMarker.HTML);

    $mymarker_link.html("Remove");
    $mymarker_html_link.html("Remove");
    $mymarker_link.next().html(" from folder");
    $mymarker_html_link.next().html(" from folder");

    var newHtml = $mymarker_html_link.closest("table#miniwindow").wrapAll("<div/>").closest("div").html();
    myMarker.HTML = newHtml;

    setMarkerSavedImage(myMarker, myMarkerImage);
}

