
function DisplayListings(textObject, shouldRepositionMap, UseBoundingBox )
{ 
    criteriaType = _search.Criteria;
    searchName = _search.SearchName;
    displayListHeader(criteriaType,searchName);
    
    // Populate listing object from text object results
    var displayMode = $('searchMode').value;
    var elements = textObject.split("@^"); // make an array of elements
    var listingCount = parseFloat(elements[0]);
    var boundingBox = elements[1].split("@~");
    var latitudeMin = parseFloat(boundingBox[0]);
    var longitudeMin = parseFloat(boundingBox[1]);
    var latitudeMax = parseFloat(boundingBox[2]);
    var longitudeMax = parseFloat(boundingBox[3]);
    
    if (shouldRepositionMap == true || UseBoundingBox == true) {

        repositionMap(latitudeMin, longitudeMin, latitudeMax, longitudeMax);

    }
    
    if (listingCount == 0)
    {   // No matching properties.
        ShowListingSearchWarning("<span style=\"color:red;margin-left:3px;\">No matching properties.<br />&nbsp;Please expand your search.</span><div style=\"width:170px;color:blue;font-size:.7em;text-align:right; \"><a style=\"text-decoration:none;\" href=\"javascript:toggleMenu(\'spanMoreInfo\');\">more info \>\></a></div><span id=\"spanMoreInfo\" style=\"color:red;margin-left:3px;display:none;\">For better results:<br /><li>Try a different price range<br /><li>Zoom out to a wider view<br /><li><a href=\"javascript:window.location.reload(false);\">Remove search criteria</a><br /><li><a href=\"Homepage.aspx\">Select a new search area</a><li>Remove neighborhoods<br /></span>");
        deleteListings();
        _paging.clearPaging();
        
        // Display empty row on list view
        document.getElementById('divList').innerHTML = "<div style=\"font-size:1.6em;margin-top: 40px;color:gray;text-align:center;width:595px;\">No matching properties.<br />Please expand your search.</div>"
        document.getElementById('divListColumn').innerHTML = "";

        return;
    }
    else if (elements.length == 2) {
        // Too many matching properties.
        ShowListingSearchWarning("<span style=\"font-size:1.2em;font-weight:bold;color:red;margin-left:3px;\">"+listingCount+"</span><span style=\"color:red;\"> matching properties.<div style=\"color: gray; margin-left: 3px; margin-right: 3px;\"><a href=\"javascript:toggleView('List');GetListings();\">View in a list</a>, or refine your search to view results on the map.</div>");
        deleteListings();
        _paging.clearPaging();
        
        return;
    }
		
    // Show data: for debugging
    for (var n = 0, len = elements.length, listingItems; n < len; n++) {
        document.getElementById('divResult').innerHTML += elements[n]+"<br><br>";
       }
   
	// Display number of found listings
	displayMatchingListings("<span style=\"font-size:1.2em;font-weight:bold;color:green;margin-left:3px;\">" + addCommas(listingCount)+ "</span> <span style=\"font-size:.9em;\">matching properties</span>");
    // Display small grid header
    
    // Check to see if listing layer exists
    if (typeof(_listingLayer)!="undefined")
    {
        // Delete all existing listing icons
        _listingLayer.DeleteAllShapes(); 
    }
    else
    {
        // Create listing layer
        _listingLayer = new VEShapeLayer();
        //_listingLayer.SetClusteringConfiguration(VEClusteringType.Grid);
        _map.AddShapeLayer(_listingLayer);
    }
    
    var shapeArray = [];
	var gridArray = [];
	var listArray = [];
	var latLongArray = [];
	var listingsMap = new Object();
	
	//############################################# POPULATE LISTING OBJECT ####################################################
    // NOTE: Start on 3rd element -- first is total count, second is bounding box, third is first listing
	var firstPhoto = true;
	ListingManager.ClearListings();
	for (var n = 2, len = elements.length, listingItems; n < len; n++) {
		if(elements[n]) {								//take a single listing: listingElements[n]
			listingItems = elements[n].split("@~"); 	//make an array of its properties
			
			var listing = new Listing();                //Populate a ve_listing_object
   		    listing.Populate(listingItems, MLSID, ClonedMLSID, MetroAreaID);
   		    
			shapeArray.push(listing.GetShape());
			latLongArray.push(listing.GetLatLong());
			if(firstPhoto){listing.displayFirstPhoto();firstPhoto=false;} 
			
		    gridArray.push(listing.GetGridRowData(n));  //Display a row in the small grid
		    listArray.push(listing.GetListRowData(n));  //Display a row in the large list

            ListingManager.AddListing(listing);
		}
	}
	
	if(displayMode=="Map") {
        
	    document.getElementById('divGrid').innerHTML="<div class=\"gridRowAlt\">MLS&nbsp;Beds&nbsp;Baths&nbsp;Price</div>";
	    document.getElementById('divGrid').style.display='block';
	    document.getElementById('divSummary').style.display='block';
	    document.getElementById('divHeader1').style.display='block';
        document.getElementById('divHeader2').style.display='block';
        listing.DisplayShapeArray(shapeArray);   //Display listing on map
	    listing.DisplayGridArray(gridArray);     //Display right-side mini grid
	    if(criteriaType=="Address"||criteriaType=="MLSListingID"||criteriaType=="Favorites"||criteriaType=="Discards") {
	        _map.DetachEvent("onchangeview", OnMapViewChanged); 
	        _map.SetMapView(latLongArray);  //set map view if doing a search for address/MLSID or Favorites/Discards
	        setTimeout("_map.AttachEvent(\"onchangeview\", OnMapViewChanged);", 2000);
	    }
	    hideDemographics();
    }
    else {
        listing.DisplayListArray(listArray);       
        _paging.initPagingLinks(listingCount);
    }

    // Toggle back from Saved search to Basic
    if (_search.Criteria == "Saved") {
        _search.Criteria = "Basic";
    }

}

function displayListHeader(criteriaType, searchName) {
    var display;
    switch(criteriaType) {
            case "Saved": 
                display= unescape(searchName);
                break;
            case "Favorites": 
                display="Favorite Listings";
                break;
            case "Discards": 
                display="Discarded Listings";
                break;
            case "MLSListingID": 
                display="MLS ID Search Results";
                break;
            case "Address": 
                display="Address Search Results";
                break;
            case "REO": 
                display="Foreclosure Search Results";
                break;
            case "Basic":
            case "Advanced":
            case "":
                display = "Search Results";
                if (!IsNullOrEmpty(_search.SearchName) && !_search.SavedSearchCriteriaChanged) {
                    display = unescape(_search.SearchName);
                }
                break;  
            case "FeaturedAgent": 
                display="Featured Agent Listings";
                break;  
            case "FeaturedBroker": 
                display="Featured Broker Listings";
                break; 
            default: 
                 display = "searching ...";
       }    
	$('listViewTitle').innerHTML=display;
}

function repositionMap(latitudeMin, longitudeMin, latitudeMax, longitudeMax) {
    if (!IsNullOrEmpty(latitudeMin) && !IsNullOrEmpty(longitudeMin) && !IsNullOrEmpty(latitudeMax) && !IsNullOrEmpty(longitudeMax) != null
        && !isNaN(latitudeMin) && !isNaN(longitudeMin) && !isNaN(latitudeMax) && !isNaN(longitudeMax))
    {

		_search.LatitudeMin = latitudeMin;
        _search.LatitudeMax = latitudeMax;
        _search.LongitudeMin = longitudeMin;
        _search.LongitudeMax = longitudeMax;
        
        var mapView = _map.GetMapView();
        mapLatitudeMin = mapView.BottomRightLatLong.Latitude;
        mapLongitudeMax = mapView.BottomRightLatLong.Longitude;
        mapLongitudeMin = mapView.TopLeftLatLong.Longitude;
        mapLatitudeMax = mapView.TopLeftLatLong.Latitude;
        
	if (
         Math.abs(mapLatitudeMin - latitudeMin ) > 0.01 ||
         Math.abs(mapLongitudeMin - longitudeMin) > 0.01 ||
         Math.abs(mapLatitudeMax - latitudeMax) > 0.01 ||
         Math.abs(mapLongitudeMax - longitudeMax) > 0.01) {

	        _map.DetachEvent("onchangeview", OnMapViewChanged);

            // Create bounding box points
	        var topLeft = new VELatLong(latitudeMax, longitudeMin);
	        var lowerRight = new VELatLong(latitudeMin, longitudeMax); 
            var points = [topLeft, lowerRight];

            var dummyLayer = new VEShapeLayer();
            dummyLayer.AddShape( new VEShape( VEShapeType.Pushpin, topLeft));
            dummyLayer.AddShape( new VEShape( VEShapeType.Pushpin, lowerRight));
 
            _bestFitBoundingBox = dummyLayer.GetBoundingRectangle();
            
            setTimeout("MapSetMapView();", 1000);
            
	        setTimeout("_map.AttachEvent(\"onchangeview\", OnMapViewChanged);", 2000);

        }
    }
}

var _bestFitBoundingBox;
function MapSetMapView() {
    _map.SetMapView(_bestFitBoundingBox);
}
