﻿


function ManagePropertyResults(pAddNavHistory) {
    log.info("ManagePropertyResults");
    var myType = _SSR._CurrentViewType;
    var mySliderInfo = CalcSliderInfo();

    //when a new search, initialize the slider
    if (_SSR._IsNewSearch(myType)) {
        InitializePropertySlider(mySliderInfo);
    }; //end if new search

    var myTracker = _SSR._Trackers[myType];

    //when viewing horizontally, clear the contents
    if (myTracker.ResultOrientation == "horizontal") {
        ReplaceView("CONTENT", "");
    }; //end if horizontal


    //when a skip, clear and reload
    if (myTracker.SlideDirection == 0) {
        LoadSkip(myTracker, mySliderInfo);
    }; //end if skip

    //update listings
    UpdateListingsWithTempCards(myTracker);
    //update Markers
    UpdateMarkers(myTracker, mySliderInfo);
    //order missing data
    UpdateMissingData(myTracker, mySliderInfo);
    //update the listings currently being viewed and queued
    UpdateListings(myTracker, mySliderInfo);
    //update map bounds
    if (!_IsInitialFeaturedSearch) {
        SetBoundsForCurrentProperties(mySliderInfo.FirstViewable, mySliderInfo.LastViewable, myType);
    } else {
        _IsInitialFeaturedSearch = false;
    }

    //Update the pager
    CreatePagingLinks(myTracker.Count, myTracker.PageSize, _SSR._GetCurrentPage(myType));
    //Update the history
    if (pAddNavHistory == null || pAddNavHistory){
        _SSR.NavigationHistory_Add("LIST", myType, myTracker.CurrentIndex, 0);
    }

    LockNavigationBoundaries(myTracker);
    SendDocumentHeight();
}; //end function

function CreateListingByType(pType, pResult, pIndex, pResultOrientation) {
    log.info("CreateListingByType");
    var myListing = null;
    if (pType == "BUILDINGS" || pType == "BUILDINGS_SAVED" || pType == "SITES" || pType == "SITES_SAVED")
        myListing = _PropertySearchResultBuilder.CreateListing(pResult, pIndex, pType, pResultOrientation);
    else if (pType == "COMMUNITIES" || pType == "COMMUNITIES_SAVED")
        myListing = _CommunitySearchResultBuilder.CreateListing(pResult, pIndex, pType, pResultOrientation);
    else if (pType == "BUSINESSES" || pType == "BUSINESSES_SAVED")
        myListing = _BusinessSearchResultBuilder.CreateListing(pResult, pIndex, pType, pResultOrientation);
    else if (pType == "REPORTS" || pType == "REPORTS_SAVED")
        myListing = _ReportResultBuilder.CreateListing(pResult, pIndex, pType, pResultOrientation);
    return myListing;
}; //end function

function CreateNullListingByType(pIndex, pType) {
    log.info("CreateNullListingByType");
    var myListing = null;
    if (pType == "BUILDINGS" || pType == "BUILDINGS_SAVED" || pType == "SITES" || pType == "SITES_SAVED")
        myListing = _PropertySearchResultBuilder.CreateNullListing(pIndex, pType);
    else if (pType == "COMMUNITIES" || pType == "COMMUNITIES_SAVED")
        myListing = _CommunitySearchResultBuilder.CreateNullListing(pIndex, pType);
    else if (pType == "BUSINESSES" || pType == "BUSINESSES_SAVED")
        myListing = _BusinessSearchResultBuilder.CreateNullListing(pIndex, pType);
    else if (pType == "REPORTS" || pType == "REPORTS_SAVED")
        myListing = _ReportResultBuilder.CreateNullListing(pIndex, pType);
    return myListing;
}; // end function

function CreateMarkerByType(pResult, pType) {
    log.info("CreateMarkerByType");
    var myCommunitiesRegex = /COMMUNITIES/;
    var mySitesRegex = /SITES/;
    var myBuildingsRegex = /BUILDINGS/;
    var myReportsRegex = /REPORTS/;
    var myBusinesssRegex = /BUSINESSES/;

    if (mySitesRegex.exec(pType) != null || myBuildingsRegex.exec(pType) != null) {
        return _PropertySearchResultBuilder.CreateMarker(pResult, pType);
    }
    else if (myCommunitiesRegex.exec(pType) != null) {
        return _CommunitySearchResultBuilder.CreateMarker(pResult, pType);
    }
    else if (myBusinesssRegex.exec(pType) != null) {
        return _BusinessSearchResultBuilder.CreateMarker(pResult, pType);
    }
    else if (myReportsRegex.exec(pType) != null) {
        return _ReportResultBuilder.CreateMarker(pResult, pType);
    }
}; // end function

function LoadSkip(pTracker, pSliderInfo) {
    log.info("LoadSkip");
    //add in all queable properties
    var myType = _SSR._CurrentViewType;
    var myResults = pTracker.Results;
    var myListing;
    for (var i = pSliderInfo.FirstQueable; i < pSliderInfo.LastQueable + 1; i++) {
        if (myResults[i] != false) {
            myListing = CreateListingByType(myType, myResults[i], i, pTracker.ResultOrientation);
        } else {
            myListing = CreateNullListingByType(i, myType);
            //track that its temporary
            if (!_SSR._DetermineIfNeedsUpdatingExists(i, myType)) {
                pTracker.CurrentlyNeedsUpdating.push(i);
            }; //end if need doesnt already exist
        }; //end if/else

        //add the item
        $("#ContentItemHolder").append(myListing);
    };

}; //end function

function ManageOrderReceived() {
    log.info("ManageOrderReceived");
    var myType = _SSR._CurrentViewType;
    var mySliderInfo = CalcSliderInfo();
    var myTracker = _SSR._Trackers[myType];

    //update listings
    UpdateListingsWithTempCards(myTracker);
    //update Markers
    UpdateMarkers(myTracker, mySliderInfo);
    //update map bounds
    SetBoundsForCurrentProperties(mySliderInfo.FirstViewable, mySliderInfo.LastViewable, myType);
    //update interactivity
    UnbindInteractivityProperties();
    BindInteractivityProperties(mySliderInfo, myTracker.Results);

}; //end function

function UnbindInteractivityProperties() {
    log.info("UnbindInteractivityProperties");
    $(".property").each(function () { RemoveInteractivityProperty($(this)); });
}; //end function

function BindInteractivityProperties(pSliderInfo, pProperties) {
    log.info("BindInteractivityProperties");
    var myLastViewable = pSliderInfo.LastViewable + 1;
    if (myLastViewable > pSliderInfo.TotalResults) {
        myLastViewable = pSliderInfo.TotalResults;
    }; //end if greater than count

    for (var i = pSliderInfo.FirstViewable; i < myLastViewable; i++) {
        SetUpInteractivityProperty($("#" + pProperties[i].ID));
    }; //end for each viewable
}; //end function

function UpdateListings(pTracker, pSliderInfo) {
    log.info("UpdateListings");
    var myFirstQueable = pSliderInfo.FirstQueable;
    var myLastQueable = pSliderInfo.LastQueable;
    var myFirstViewable = pSliderInfo.FirstViewable;
    var myLastViewable = pSliderInfo.LastViewable;
    var myResults = pTracker.Results;
    var myType = _SSR._CurrentViewType;
    var myDirection = pTracker.SlideDirection;
    var IsHorizontal = pTracker.ResultOrientation == "horizontal";

    UnbindInteractivityProperties();

    //get a list of all the queable properties
    var myQueableProperties = [];
    for (var i = myFirstQueable; i < myLastQueable + 1; i++) {
        myQueableProperties.push(i);
    }; //end for each queable

    var myCurrentProperties = [];
    $(".property", "#ContentItemHolder").each(
    function () {
        myCurrentProperties.push($(this).attr("resultID"));
    }
    );


    //add the properties needed to queue
    var myPropertiesToAdd = [];
    if (myDirection == -1) {
        //slide left
        for (var i = pSliderInfo.FirstQueable; i < pSliderInfo.LastQueable + 1; i++) {
            if (myCurrentProperties[0] != i) {
                myPropertiesToAdd.push(i);
            }
            else {
                //all have been added
                break;
            };
        }; //end for each queable
    }; //end if my direction is lift
    if (myDirection == 1) {
        //slide right
        for (var i = pSliderInfo.LastQueable; i > pSliderInfo.FirstQueable - 1; i--) {
            if (myCurrentProperties[myCurrentProperties.length - 1] != i) {
                myPropertiesToAdd.push(i);
            }
            else {
                //all have been added
                break;
            };
        }; //end for each queable
    }; //end if direction = right


    //now add them
    //reverse the properties to add
    myPropertiesToAdd.reverse();
    for (var i = 0; i < myPropertiesToAdd.length; i++) {
        var myIndex = myPropertiesToAdd[i];

        if (myResults[myIndex] != false) {
            var myListing = CreateListingByType(myType, myResults[i], i, pTracker.ResultOrientation);
            //var myListing = _PropertySearchResultBuilder.CreateListing(myResults[myIndex], myIndex, myType, pTracker.ResultOrientation);

            if (myDirection == -1) {
                //prepend this property
                $("#ContentItemHolder").prepend(myListing);
            }; //end if my direciton = left 
            if (myDirection == 1) {
                //append this property
                $("#ContentItemHolder").append(myListing);
            }; //end if direction right
        };

    }; //end for each property to add



    //recalculate the properties in the slider
    myCurrentProperties = [];
    $(".property", "#ContentItemHolder").each(
    function () {
        myCurrentProperties.push($(this).attr("resultID"));
    }
    );

    //remove the properties no longer needed and adjust slider
    if (myCurrentProperties.length > GISP_PROPERTY_PAGE_BUFFER * pTracker.PageSize) {

        $(".property", "#ContentItemHolder").each(function () {
            var myResultID = $(this).attr("resultID");
            if (myResultID > myLastQueable || myResultID < myFirstQueable) {
                $(this).remove();
            }
        });

        //fix up the slider
        if (!IsHorizontal) {
            var myPos = (pSliderInfo.FirstViewable - pSliderInfo.FirstQueable) * GISP_PROPERTY_WIDTH;
            SetContentItemHolderLeft(myPos);
        }; //end if not horizontal

    }; //end if need to trip results

    //check properties for if saved, etc, and set decorator or remove decorator if needed
    $("#ContentItemHolder .property").each(function (key, val) {
        var myCurrentProperty = $(val);
        var myPropertyID = myCurrentProperty.attr("id");
        var myPropertyIsSaved = _SSR.IsResultSaved(myPropertyID);
        if (myPropertyIsSaved) {
            //add the decorator/class
            $(".savedDecorator", myCurrentProperty).addClass("saved");
            $(".saveLink", myCurrentProperty).text("Remove");
            $(".saveToFrom", myCurrentProperty).text("from");

        }
        else {
            //remove the decorator/class
            $(".savedDecorator", myCurrentProperty).removeClass("saved");
            $(".saveLink", myCurrentProperty).text("Save");
            $(".saveToFrom", myCurrentProperty).text("to");
        }
    });


    //add interactivity to viewable results
    BindInteractivityProperties(pSliderInfo, myResults);
};



function UpdateMissingData(pTracker, pSliderInfo) {
    log.info("UpdateMissingData");
    //look at the the reange of mappable and the create any temp listings needed
    //then create calls to fill in the needs updating
    var myFirstQueable = pSliderInfo.FirstQueable;
    var myLastQueable = pSliderInfo.LastQueable;
    var myResults = pTracker.Results;
    var myType = _SSR._CurrentViewType;
    var IsHorizontal = pTracker.ResultOrientation == "horizontal";

    //when viewing results vertically, First and Last Queable are the same as viewable, in this procedure, we want to extend them out +- page amount
    if (IsHorizontal) {
        myFirstQueable -= pTracker.PageSize;
        if (myFirstQueable < 0) { myFirstQueable = 0; }
        myLastQueable += pTracker.PageSize;
        if (myLastQueable >= pTracker.Count) { myLastQueable = pTracker.Count - 1; }
    }

    //add temp cards for needed data
    for (var i = myFirstQueable; i < myLastQueable + 1; i++) {
        var myIndex = pTracker.SlideDirection == 1 ? i : myLastQueable - (i - myFirstQueable);
        if (myResults[myIndex] == false) {
            //check if a null card has already been created
            if ($("#CARD_" + myIndex).length == 0) {
                //if horizontal orientation, we only want to add viewable properties
                if (!IsHorizontal || (myIndex >= pSliderInfo.FirstViewable && myIndex <= pSliderInfo.LastViewable)) {
                    //create a null listing and add it to the container
                    var myNullListing = CreateNullListingByType(myIndex, myType);
                    //var myNullListing = _PropertySearchResultBuilder.CreateNullListing(myIndex, myType);
                    if (pTracker.SlideDirection == 1) {
                        $("#ContentItemHolder").append(myNullListing);
                    } else {
                        $("#ContentItemHolder").prepend(myNullListing);
                    }; //end if/else direction
                }

                //update the needs updating array
                var myNeedsUpdateExists = _SSR._DetermineIfNeedsUpdatingExists(myIndex, myType);
                if (myNeedsUpdateExists == false) {
                    pTracker.CurrentlyNeedsUpdating.push(myIndex);
                }; //end if need doesnt already exist

            }; //end if not already a need
        } //end if result is Queable but no result
        else {
            //result is queable, and result exists, verify that its added to the container
            if ($("#" + myResults[myIndex].ID).length == 0) {
                //if horizontal orientation, we only want to add viewable properties
                if (!IsHorizontal || (myIndex >= pSliderInfo.FirstViewable && myIndex <= pSliderInfo.LastViewable)) {
                    //create a listing and add it to the container
                    var myListing = CreateListingByType(myType, myResults[myIndex], myIndex, pTracker.ResultOrientation);
                    //var myListing = _PropertySearchResultBuilder.CreateListing(myResults[myIndex], myIndex, myType, pTracker.ResultOrientation);
                    if (pTracker.SlideDirection == 1) {
                        $("#ContentItemHolder").append(myListing);
                    } else {
                        $("#ContentItemHolder").prepend(myListing);
                    }; //end if/else direction
                }
            }; //end if listing not already added to containter
        }; //end if result is queable and a result exists
    }; //end for each Queable result


    //create orders for all data that is missing. First we need to create a copy of the array
    var myCurrentNeedsObject = $.extend(false, {}, pTracker.CurrentlyNeedsUpdating);
    var myCurrentNeedsArray = [];
    for (var i = 0; i < pTracker.CurrentlyNeedsUpdating.length; i++) {
        myCurrentNeedsArray.push(pTracker.CurrentlyNeedsUpdating[i]);
    }
    //    for (var i in myCurrentNeedsObject) {
    //        myCurrentNeedsArray.push(myCurrentNeedsObject[i]);
    //    }; //end for each param
    myCurrentNeedsArray.sort(function (a, b) { return a - b }); //sorts in numberic order



    if (myCurrentNeedsArray.length > 0) {
        var myOrders = [];
        var myStartOrder = myCurrentNeedsArray[0] + 1;
        var myEndOrder = myCurrentNeedsArray[0] + 1;
        if (myCurrentNeedsArray.length > 1) {
            for (var i = 0; i < myCurrentNeedsArray.length - 1; i++) {
                if (myCurrentNeedsArray[i + 1] - myCurrentNeedsArray[i] > 1) {
                    myOrders.push({ Start: myStartOrder, Stop: myCurrentNeedsArray[i] + 1 });
                    myStartOrder = myCurrentNeedsArray[i + 1] + 1;
                }; //end if found break in seq
            }; //end for each need
        } //end if at least 2 needs
        myOrders.push({ Start: myStartOrder, Stop: myCurrentNeedsArray[myCurrentNeedsArray.length - 1] + 1 });

        //place the orders
        for (var i = 0; i < myOrders.length; i++) {
            if (!_SSR._DetermineIfOrderExists(myOrders[i], myType)) {
                var myParams = pTracker.SearchParameters;
                myParams.StartRowID = myOrders[i].Start;
                myParams.EndRowID = myOrders[i].Stop;

                OrderData(myType, myParams, SearchAdditionalPageSuccess, SearchFail);
            }; //end if order does not exist
        }; //end for each order
    } //end if at least 1 need
    //now loop thru and create continguous orders
};


function UpdateMarkers(pTracker, pSliderInfo) {
    log.warn("UpdateMarkers");
    var myType = _SSR._CurrentViewType;
    var myResults = pTracker.Results;




    //viewable markers should be GISP_PROPERTY_PAGE_BUFFER the page size  (an example is 3)

    //now add the viewable
    var myListViewable = pSliderInfo.LastViewable + 1;
    if (myListViewable > pTracker.Count + 1) {
        myListViewable = pTracker.Count + 1;
    }; //end if greater than count



    //Go thru and merge in new markers and remove ones that are not in the list.

    var myMarkerToKeep = []; //this will hold a list of all the markers to keep
    for (var i = pSliderInfo.FirstViewable; i < myListViewable; i++) {
        if (myResults[i] != false) {
            //determine if marker is already on map.
            var myID = myResults[i].ID;
            var myMarker = null;

            //create a new marker if not on the map
            var myExistingMarkerIndex = findInArray(_propertyMarkers, "ID", myID);
            if (myExistingMarkerIndex < 0) {//does not exist
                myMarker = CreateMarkerByType(myResults[i], myType);
                if (myMarker != null) {
                    //push the property to the array
                    _propertyMarkers.push(myMarker);

                } //end if marker not null
            } //end if marker does not exist
            else {
                //extract the marker from the existing property markers
                myMarker =  _propertyMarkers[myExistingMarkerIndex];
            }
            //add this marker to the keep array
            myMarkerToKeep.push(myMarker);
            myMarker.setMap(map);
        }; //end if property exists
    }; //end for each viewable

    //clear all markers that should not be there
    var myMarkersToRemove = [];
    for (var i = 0; i < _propertyMarkers.length; i++) {
        var myMarker = _propertyMarkers[i];
        if (findInArray(myMarkerToKeep, "ID", myMarker.ID) < 0) {
            myMarkersToRemove.push(myMarker);
            google.maps.event.clearInstanceListeners(myMarker);
        }
    } //end for each property marker

    //reassign the property markers to the new ones to keep.
    _propertyMarkers = myMarkerToKeep;


    //finally remove the old markers
    RemoveMarkers(map, myMarkersToRemove);
}; //end function


function UpdateListingsWithTempCards(pTracker) {
    log.info("UpdateListingsWithTempCards");
    //update any temporary listings
    var myType = _SSR._CurrentViewType;
    var myResults = pTracker.Results;
    var numItemsNeedingUpdate = pTracker.CurrentlyNeedsUpdating.length - 1;

    var myViewableListings = [];

    //go thru in reverse order and pull off items. This wont effect items being pushed onto it at the same time by an async update to it
    for (var i = numItemsNeedingUpdate; i > -1; i--) {
        var currentResultIndex = pTracker.CurrentlyNeedsUpdating[i];
        if (myResults[currentResultIndex] != false) {
            var myListing = CreateListingByType(myType, myResults[currentResultIndex], currentResultIndex, pTracker.ResultOrientation);
            myViewableListings.push(myResults[currentResultIndex].ID);
            //var myListing = _PropertySearchResultBuilder.CreateListing(myResults[currentResultIndex], currentResultIndex, myType, pTracker.ResultOrientation)
            //Update the listing
            $("#CARD_" + pTracker.CurrentlyNeedsUpdating[i]).replaceWith(myListing);
            //remove the tracker for updating
            pTracker.CurrentlyNeedsUpdating.splice(i, 1);
        };
    }; //end for each item currently needing updating

    if (myViewableListings.length > 0) {
        LogAccessStatistic(myViewableListings, 2);
    }

}; //end function


function InitializePropertySlider(pSliderInfo) {
    log.info("InitializePropertySlider");
    var myType = _SSR._CurrentViewType;
    var myTracker = _SSR._Trackers[myType];
    var myResultOrientation = myTracker.ResultOrientation;

    myTracker.IsNewSearch = false;
    ChangeResultOrientation(myResultOrientation);

    var myPageSize = myTracker.PageSize;
    var myResults = myTracker.Results;
    var mySliderInfo = pSliderInfo;

    var myResultsToCreate = (myResultOrientation == "vertical") ? myPageSize * GISP_PROPERTY_PAGE_BUFFER : myPageSize;
    if (myResultsToCreate > mySliderInfo.TotalResults) {
        myResultsToCreate = mySliderInfo.TotalResults;
    }; //end if more than total results


    var myViewableListings = [];
    var $contentItemHolder = $("#ContentItemHolder");
    $contentItemHolder.addClass(".results");

    for (var i = 0; i < myResultsToCreate; i++) {
        var myListing;
        if (myResults[i] != false) {
            myListing = CreateListingByType(myType, myResults[i], i, myTracker.ResultOrientation);
            myViewableListings.push(myResults[i].ID);
        } else {
            myListing = CreateNullListingByType(i, myType);

            //track that its temporary
            myTracker.CurrentlyNeedsUpdating.push(i);
        }; //end if/else

        //add the item
        $contentItemHolder.append(myListing);
        //this item is in the viewable realm
    }; //end for each result to create

    LogAccessStatistic(myViewableListings, 2);

}; //end function




function CalcSliderInfo() {
    log.info("CalcSliderInfo");
    var myType = _SSR._CurrentViewType;
    var myViewPortWidth = GetClientWidth() - GISP_PROPERTY_CONTAINER_MARGIN;
    var myPosition = _resultsPosition;
    var myTracker = _SSR._Trackers[myType];
    var myTotalResults = myTracker.Count;

    //calc properties currently in view port
    var myFirstPropertyInViewPort = myTracker.CurrentIndex;
    var myLastPropertyInViewPort = myTracker.CurrentIndex + myTracker.PageSize - 1;
    //sanity check
    if (myLastPropertyInViewPort >= myTracker.Count) { myLastPropertyInViewPort = myTracker.Count - 1; }


    //calc the mapped properties
    var myResultPadding = myTracker.PageSize;
    var myCurrentResultIndex = myFirstPropertyInViewPort;
    //modifiers will allow always 1 + GISP_PROPERTY_PAGE_BUFFER pages to be displayed
    var myEndResultModifier = (myCurrentResultIndex - myResultPadding) > 0 ? 0 : -(myCurrentResultIndex - myResultPadding);
    var myStartResultModifier = myCurrentResultIndex + myResultPadding < myTotalResults ? 0 : myResultPadding;

    var myFirstQueable = (myCurrentResultIndex - myResultPadding - myStartResultModifier) > 0 ? myCurrentResultIndex - myResultPadding - myStartResultModifier : 0;
    var myLastQueable = myLastPropertyInViewPort + myResultPadding + myEndResultModifier < myTotalResults ? myLastPropertyInViewPort + myResultPadding + myEndResultModifier : myTotalResults - 1;

    //if the results are being shown horizontally, the idea of queable versus viewable goes away (you only ever load what is viewable
    if (myTracker.ResultOrientation == "horizontal") {
        myFirstQueable = myFirstPropertyInViewPort;
        myLastQueable = myLastPropertyInViewPort;
    }; //end if horizontal results
    return {
        FirstViewable: myFirstPropertyInViewPort,
        LastViewable: myLastPropertyInViewPort,
        TotalResults: myTotalResults,
        ViewPortWidth: myViewPortWidth,
        CurrentPosition: myPosition,
        FirstQueable: myFirstQueable,
        LastQueable: myLastQueable
    };
};


function SetBoundsForCurrentProperties(pStartIndex, pEndIndex, pType) {
    log.info("SetBoundsForCurrentProperties");
    //update zoom level by looping thru the results and getting the bounds
    _bounds = new google.maps.LatLngBounds();
    var myBoundsShouldBeSet = false;
    var myPage = _SSR._GetCurrentPage(pType);
    var myCurrentIndex = pStartIndex;
    var myTracker = _SSR._Trackers[pType];

    var myStopIndex = pEndIndex;
    if (myStopIndex >= myTracker.Count) {
        myStopIndex = myTracker.Count - 1;
    }; //end if greater than count

    for (var i = myCurrentIndex; i < myStopIndex + 1; i++) {
        var myResult = _SSR.GetResults(pType)[i];
        if (myResult != false) {
            if (/REPORTS_SAVED/.exec(pType) == null) {
                if (myResult.lat != null && myResult.lng != null) {
                    myBoundsShouldBeSet = true;
                    var myLatLng = new google.maps.LatLng(myResult.lat, myResult.lng);
                    _bounds.extend(myLatLng);
                }
            }
            else {
                //myResult is a guid, need to get the report
                var mySavedReport = _SSR.GetReportByUniqueID(myResult);
                if (mySavedReport != null) {
                    if (mySavedReport.Parameters.Lat != null && mySavedReport.Parameters.Lng != null) {
                        myBoundsShouldBeSet = true;
                        var myLatLng = new google.maps.LatLng(mySavedReport.Parameters.Lat, mySavedReport.Parameters.Lng);
                        _bounds.extend(myLatLng);
                    }
                }

            }
        }; //end if result

    }; //end for each result

    //do the update
    if (myBoundsShouldBeSet) {
        map.fitBounds(_bounds);
    }; //end if bounds should be set
}; //end function

function ChangeResultOrientation(pOrientation) {
    log.info("ChangeResultOrientation");
    var myType = _SSR._CurrentViewType;
    var myTracker = _SSR._Trackers[myType];
    var IsVertical = false;

    if (pOrientation !== undefined && pOrientation !== null) {
        IsVertical = pOrientation == "vertical";
    }
    else {
        IsVertical = myTracker.ResultOrientation == "vertical";
    }

    myTracker.CurrentIndex = 0;

    // change the orientation of #orientationContainer
    var newOrientation = "horizontal";
    if (pOrientation !== undefined && pOrientation !== null) {
        newOrientation = pOrientation;
    }
    else {
        newOrientation = IsVertical ? "horizontal" : "vertical";
    }
    myTracker.ResultOrientation = newOrientation;
    $("#orientationContainer, #contentNav").removeClass("vertical").removeClass("horizontal").addClass(newOrientation);

    var myWidth = CalculateResultWidth();
    ResetContentItemHolder();
    SetContentItemHolderWidth(myWidth);
    //$("#ContentItemContainer").css({ height: !IsVertical ? GISP_PROPERTY_HEIGHT + "px" : "100%" });

    if (!IsVertical) {
        //Now showing horizontal so change the page size default
        var myCurrentPageSize = _SSR._PageSizeDEFAULT;
        _SSR._SetPageSize(myCurrentPageSize, myType);
    } else {
        var myCurrentPageSize = CalcCurrentPageSizeBasedOnClientWidth();
        _SSR._SetPageSize(myCurrentPageSize, myType);
    }; //end if/else vertical

}; //end function

function CalculateResultWidth() {
    log.info("CalculateResultWidth");
    var myType = _SSR._CurrentViewType;
    var myTracker = _SSR._Trackers[myType];
    var IsVertical = myTracker.ResultOrientation == "vertical";

    var widthOfHorizontalList = $("#orientationContainer").width(); //easier than getting window width, etc.

    return !IsVertical ? (widthOfHorizontalList) : GISP_PROPERTY_WIDTH * GISP_PROPERTY_PAGE_BUFFER * myTracker.PageSize;
};

